es6.js 4.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411
  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. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6532. */
  6533. function EventState(mask, skipNextObservers, target, currentTarget) {
  6534. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6535. this.initalize(mask, skipNextObservers, target, currentTarget);
  6536. }
  6537. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6538. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6539. this.mask = mask;
  6540. this.skipNextObservers = skipNextObservers;
  6541. this.target = target;
  6542. this.currentTarget = currentTarget;
  6543. return this;
  6544. };
  6545. return EventState;
  6546. }());
  6547. BABYLON.EventState = EventState;
  6548. /**
  6549. * Represent an Observer registered to a given Observable object.
  6550. */
  6551. var Observer = /** @class */ (function () {
  6552. function Observer(callback, mask, scope) {
  6553. if (scope === void 0) { scope = null; }
  6554. this.callback = callback;
  6555. this.mask = mask;
  6556. this.scope = scope;
  6557. }
  6558. return Observer;
  6559. }());
  6560. BABYLON.Observer = Observer;
  6561. /**
  6562. * Represent a list of observers registered to multiple Observables object.
  6563. */
  6564. var MultiObserver = /** @class */ (function () {
  6565. function MultiObserver() {
  6566. }
  6567. MultiObserver.prototype.dispose = function () {
  6568. if (this._observers && this._observables) {
  6569. for (var index = 0; index < this._observers.length; index++) {
  6570. this._observables[index].remove(this._observers[index]);
  6571. }
  6572. }
  6573. this._observers = null;
  6574. this._observables = null;
  6575. };
  6576. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6577. if (mask === void 0) { mask = -1; }
  6578. if (scope === void 0) { scope = null; }
  6579. var result = new MultiObserver();
  6580. result._observers = new Array();
  6581. result._observables = observables;
  6582. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6583. var observable = observables_1[_i];
  6584. var observer = observable.add(callback, mask, false, scope);
  6585. if (observer) {
  6586. result._observers.push(observer);
  6587. }
  6588. }
  6589. return result;
  6590. };
  6591. return MultiObserver;
  6592. }());
  6593. BABYLON.MultiObserver = MultiObserver;
  6594. /**
  6595. * The Observable class is a simple implementation of the Observable pattern.
  6596. * 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.
  6597. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6598. * 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).
  6599. * 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.
  6600. */
  6601. var Observable = /** @class */ (function () {
  6602. function Observable(onObserverAdded) {
  6603. this._observers = new Array();
  6604. this._eventState = new EventState(0);
  6605. if (onObserverAdded) {
  6606. this._onObserverAdded = onObserverAdded;
  6607. }
  6608. }
  6609. /**
  6610. * Create a new Observer with the specified callback
  6611. * @param callback the callback that will be executed for that Observer
  6612. * @param mask the mask used to filter observers
  6613. * @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.
  6614. * @param scope optional scope for the callback to be called from
  6615. */
  6616. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6617. if (mask === void 0) { mask = -1; }
  6618. if (insertFirst === void 0) { insertFirst = false; }
  6619. if (scope === void 0) { scope = null; }
  6620. if (!callback) {
  6621. return null;
  6622. }
  6623. var observer = new Observer(callback, mask, scope);
  6624. if (insertFirst) {
  6625. this._observers.unshift(observer);
  6626. }
  6627. else {
  6628. this._observers.push(observer);
  6629. }
  6630. if (this._onObserverAdded) {
  6631. this._onObserverAdded(observer);
  6632. }
  6633. return observer;
  6634. };
  6635. /**
  6636. * Remove an Observer from the Observable object
  6637. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6638. */
  6639. Observable.prototype.remove = function (observer) {
  6640. if (!observer) {
  6641. return false;
  6642. }
  6643. var index = this._observers.indexOf(observer);
  6644. if (index !== -1) {
  6645. this._observers.splice(index, 1);
  6646. return true;
  6647. }
  6648. return false;
  6649. };
  6650. /**
  6651. * Remove a callback from the Observable object
  6652. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6653. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6654. */
  6655. Observable.prototype.removeCallback = function (callback, scope) {
  6656. for (var index = 0; index < this._observers.length; index++) {
  6657. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6658. this._observers.splice(index, 1);
  6659. return true;
  6660. }
  6661. }
  6662. return false;
  6663. };
  6664. /**
  6665. * Notify all Observers by calling their respective callback with the given data
  6666. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6667. * @param eventData
  6668. * @param mask
  6669. */
  6670. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6671. if (mask === void 0) { mask = -1; }
  6672. if (!this._observers.length) {
  6673. return true;
  6674. }
  6675. var state = this._eventState;
  6676. state.mask = mask;
  6677. state.target = target;
  6678. state.currentTarget = currentTarget;
  6679. state.skipNextObservers = false;
  6680. state.lastReturnValue = eventData;
  6681. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6682. var obs = _a[_i];
  6683. if (obs.mask & mask) {
  6684. if (obs.scope) {
  6685. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  6686. }
  6687. else {
  6688. state.lastReturnValue = obs.callback(eventData, state);
  6689. }
  6690. }
  6691. if (state.skipNextObservers) {
  6692. return false;
  6693. }
  6694. }
  6695. return true;
  6696. };
  6697. /**
  6698. * Calling this will execute each callback, expecting it to be a promise or return a value.
  6699. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  6700. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  6701. * and it is crucial that all callbacks will be executed.
  6702. * The order of the callbacks is kept, callbacks are not executed parallel.
  6703. *
  6704. * @param eventData The data to be sent to each callback
  6705. * @param mask is used to filter observers defaults to -1
  6706. * @param target the callback target (see EventState)
  6707. * @param currentTarget The current object in the bubbling phase
  6708. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  6709. */
  6710. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  6711. if (mask === void 0) { mask = -1; }
  6712. // create an empty promise
  6713. var p = Promise.resolve(eventData);
  6714. // no observers? return this promise.
  6715. if (!this._observers.length) {
  6716. return p;
  6717. }
  6718. var state = this._eventState;
  6719. state.mask = mask;
  6720. state.target = target;
  6721. state.currentTarget = currentTarget;
  6722. state.skipNextObservers = false;
  6723. // execute one callback after another (not using Promise.all, the order is important)
  6724. this._observers.forEach(function (obs) {
  6725. if (state.skipNextObservers) {
  6726. return;
  6727. }
  6728. if (obs.mask & mask) {
  6729. if (obs.scope) {
  6730. p = p.then(function (lastReturnedValue) {
  6731. state.lastReturnValue = lastReturnedValue;
  6732. return obs.callback.apply(obs.scope, [eventData, state]);
  6733. });
  6734. }
  6735. else {
  6736. p = p.then(function (lastReturnedValue) {
  6737. state.lastReturnValue = lastReturnedValue;
  6738. return obs.callback(eventData, state);
  6739. });
  6740. }
  6741. }
  6742. });
  6743. // return the eventData
  6744. return p.then(function () { return eventData; });
  6745. };
  6746. /**
  6747. * Notify a specific observer
  6748. * @param eventData
  6749. * @param mask
  6750. */
  6751. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6752. if (mask === void 0) { mask = -1; }
  6753. var state = this._eventState;
  6754. state.mask = mask;
  6755. state.skipNextObservers = false;
  6756. observer.callback(eventData, state);
  6757. };
  6758. /**
  6759. * return true is the Observable has at least one Observer registered
  6760. */
  6761. Observable.prototype.hasObservers = function () {
  6762. return this._observers.length > 0;
  6763. };
  6764. /**
  6765. * Clear the list of observers
  6766. */
  6767. Observable.prototype.clear = function () {
  6768. this._observers = new Array();
  6769. this._onObserverAdded = null;
  6770. };
  6771. /**
  6772. * Clone the current observable
  6773. */
  6774. Observable.prototype.clone = function () {
  6775. var result = new Observable();
  6776. result._observers = this._observers.slice(0);
  6777. return result;
  6778. };
  6779. /**
  6780. * Does this observable handles observer registered with a given mask
  6781. * @param {number} trigger - the mask to be tested
  6782. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6783. **/
  6784. Observable.prototype.hasSpecificMask = function (mask) {
  6785. if (mask === void 0) { mask = -1; }
  6786. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6787. var obs = _a[_i];
  6788. if (obs.mask & mask || obs.mask === mask) {
  6789. return true;
  6790. }
  6791. }
  6792. return false;
  6793. };
  6794. return Observable;
  6795. }());
  6796. BABYLON.Observable = Observable;
  6797. })(BABYLON || (BABYLON = {}));
  6798. //# sourceMappingURL=babylon.observable.js.map
  6799. var BABYLON;
  6800. (function (BABYLON) {
  6801. var SmartArray = /** @class */ (function () {
  6802. function SmartArray(capacity) {
  6803. this.length = 0;
  6804. this.data = new Array(capacity);
  6805. this._id = SmartArray._GlobalId++;
  6806. }
  6807. SmartArray.prototype.push = function (value) {
  6808. this.data[this.length++] = value;
  6809. if (this.length > this.data.length) {
  6810. this.data.length *= 2;
  6811. }
  6812. };
  6813. SmartArray.prototype.forEach = function (func) {
  6814. for (var index = 0; index < this.length; index++) {
  6815. func(this.data[index]);
  6816. }
  6817. };
  6818. SmartArray.prototype.sort = function (compareFn) {
  6819. this.data.sort(compareFn);
  6820. };
  6821. SmartArray.prototype.reset = function () {
  6822. this.length = 0;
  6823. };
  6824. SmartArray.prototype.dispose = function () {
  6825. this.reset();
  6826. if (this.data) {
  6827. this.data.length = 0;
  6828. this.data = [];
  6829. }
  6830. };
  6831. SmartArray.prototype.concat = function (array) {
  6832. if (array.length === 0) {
  6833. return;
  6834. }
  6835. if (this.length + array.length > this.data.length) {
  6836. this.data.length = (this.length + array.length) * 2;
  6837. }
  6838. for (var index = 0; index < array.length; index++) {
  6839. this.data[this.length++] = (array.data || array)[index];
  6840. }
  6841. };
  6842. SmartArray.prototype.indexOf = function (value) {
  6843. var position = this.data.indexOf(value);
  6844. if (position >= this.length) {
  6845. return -1;
  6846. }
  6847. return position;
  6848. };
  6849. SmartArray.prototype.contains = function (value) {
  6850. return this.data.indexOf(value) !== -1;
  6851. };
  6852. // Statics
  6853. SmartArray._GlobalId = 0;
  6854. return SmartArray;
  6855. }());
  6856. BABYLON.SmartArray = SmartArray;
  6857. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6858. __extends(SmartArrayNoDuplicate, _super);
  6859. function SmartArrayNoDuplicate() {
  6860. var _this = _super !== null && _super.apply(this, arguments) || this;
  6861. _this._duplicateId = 0;
  6862. return _this;
  6863. }
  6864. SmartArrayNoDuplicate.prototype.push = function (value) {
  6865. _super.prototype.push.call(this, value);
  6866. if (!value.__smartArrayFlags) {
  6867. value.__smartArrayFlags = {};
  6868. }
  6869. value.__smartArrayFlags[this._id] = this._duplicateId;
  6870. };
  6871. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6872. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6873. return false;
  6874. }
  6875. this.push(value);
  6876. return true;
  6877. };
  6878. SmartArrayNoDuplicate.prototype.reset = function () {
  6879. _super.prototype.reset.call(this);
  6880. this._duplicateId++;
  6881. };
  6882. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6883. if (array.length === 0) {
  6884. return;
  6885. }
  6886. if (this.length + array.length > this.data.length) {
  6887. this.data.length = (this.length + array.length) * 2;
  6888. }
  6889. for (var index = 0; index < array.length; index++) {
  6890. var item = (array.data || array)[index];
  6891. this.pushNoDuplicate(item);
  6892. }
  6893. };
  6894. return SmartArrayNoDuplicate;
  6895. }(SmartArray));
  6896. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6897. })(BABYLON || (BABYLON = {}));
  6898. //# sourceMappingURL=babylon.smartArray.js.map
  6899. var BABYLON;
  6900. (function (BABYLON) {
  6901. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6902. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6903. var LoadFileError = /** @class */ (function (_super) {
  6904. __extends(LoadFileError, _super);
  6905. function LoadFileError(message, request) {
  6906. var _this = _super.call(this, message) || this;
  6907. _this.request = request;
  6908. _this.name = "LoadFileError";
  6909. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6910. return _this;
  6911. }
  6912. // Polyfill for Object.setPrototypeOf if necessary.
  6913. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6914. return LoadFileError;
  6915. }(Error));
  6916. BABYLON.LoadFileError = LoadFileError;
  6917. var RetryStrategy = /** @class */ (function () {
  6918. function RetryStrategy() {
  6919. }
  6920. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6921. if (maxRetries === void 0) { maxRetries = 3; }
  6922. if (baseInterval === void 0) { baseInterval = 500; }
  6923. return function (url, request, retryIndex) {
  6924. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6925. return -1;
  6926. }
  6927. return Math.pow(2, retryIndex) * baseInterval;
  6928. };
  6929. };
  6930. return RetryStrategy;
  6931. }());
  6932. BABYLON.RetryStrategy = RetryStrategy;
  6933. // Screenshots
  6934. var screenshotCanvas;
  6935. var cloneValue = function (source, destinationObject) {
  6936. if (!source)
  6937. return null;
  6938. if (source instanceof BABYLON.Mesh) {
  6939. return null;
  6940. }
  6941. if (source instanceof BABYLON.SubMesh) {
  6942. return source.clone(destinationObject);
  6943. }
  6944. else if (source.clone) {
  6945. return source.clone();
  6946. }
  6947. return null;
  6948. };
  6949. var Tools = /** @class */ (function () {
  6950. function Tools() {
  6951. }
  6952. /**
  6953. * Interpolates between a and b via alpha
  6954. * @param a The lower value (returned when alpha = 0)
  6955. * @param b The upper value (returned when alpha = 1)
  6956. * @param alpha The interpolation-factor
  6957. * @return The mixed value
  6958. */
  6959. Tools.Mix = function (a, b, alpha) {
  6960. return a * (1 - alpha) + b * alpha;
  6961. };
  6962. Tools.Instantiate = function (className) {
  6963. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6964. return Tools.RegisteredExternalClasses[className];
  6965. }
  6966. var arr = className.split(".");
  6967. var fn = (window || this);
  6968. for (var i = 0, len = arr.length; i < len; i++) {
  6969. fn = fn[arr[i]];
  6970. }
  6971. if (typeof fn !== "function") {
  6972. return null;
  6973. }
  6974. return fn;
  6975. };
  6976. /**
  6977. * Provides a slice function that will work even on IE
  6978. * @param data defines the array to slice
  6979. * @returns the new sliced array
  6980. */
  6981. Tools.Slice = function (data) {
  6982. if (data.slice) {
  6983. return data.slice();
  6984. }
  6985. return Array.prototype.slice.call(data);
  6986. };
  6987. Tools.SetImmediate = function (action) {
  6988. if (window.setImmediate) {
  6989. window.setImmediate(action);
  6990. }
  6991. else {
  6992. setTimeout(action, 1);
  6993. }
  6994. };
  6995. Tools.IsExponentOfTwo = function (value) {
  6996. var count = 1;
  6997. do {
  6998. count *= 2;
  6999. } while (count < value);
  7000. return count === value;
  7001. };
  7002. /**
  7003. * Find the next highest power of two.
  7004. * @param x Number to start search from.
  7005. * @return Next highest power of two.
  7006. */
  7007. Tools.CeilingPOT = function (x) {
  7008. x--;
  7009. x |= x >> 1;
  7010. x |= x >> 2;
  7011. x |= x >> 4;
  7012. x |= x >> 8;
  7013. x |= x >> 16;
  7014. x++;
  7015. return x;
  7016. };
  7017. /**
  7018. * Find the next lowest power of two.
  7019. * @param x Number to start search from.
  7020. * @return Next lowest power of two.
  7021. */
  7022. Tools.FloorPOT = function (x) {
  7023. x = x | (x >> 1);
  7024. x = x | (x >> 2);
  7025. x = x | (x >> 4);
  7026. x = x | (x >> 8);
  7027. x = x | (x >> 16);
  7028. return x - (x >> 1);
  7029. };
  7030. /**
  7031. * Find the nearest power of two.
  7032. * @param x Number to start search from.
  7033. * @return Next nearest power of two.
  7034. */
  7035. Tools.NearestPOT = function (x) {
  7036. var c = Tools.CeilingPOT(x);
  7037. var f = Tools.FloorPOT(x);
  7038. return (c - x) > (x - f) ? f : c;
  7039. };
  7040. Tools.GetExponentOfTwo = function (value, max, mode) {
  7041. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7042. var pot;
  7043. switch (mode) {
  7044. case BABYLON.Engine.SCALEMODE_FLOOR:
  7045. pot = Tools.FloorPOT(value);
  7046. break;
  7047. case BABYLON.Engine.SCALEMODE_NEAREST:
  7048. pot = Tools.NearestPOT(value);
  7049. break;
  7050. case BABYLON.Engine.SCALEMODE_CEILING:
  7051. default:
  7052. pot = Tools.CeilingPOT(value);
  7053. break;
  7054. }
  7055. return Math.min(pot, max);
  7056. };
  7057. Tools.GetFilename = function (path) {
  7058. var index = path.lastIndexOf("/");
  7059. if (index < 0)
  7060. return path;
  7061. return path.substring(index + 1);
  7062. };
  7063. Tools.GetFolderPath = function (uri) {
  7064. var index = uri.lastIndexOf("/");
  7065. if (index < 0)
  7066. return "";
  7067. return uri.substring(0, index + 1);
  7068. };
  7069. Tools.GetDOMTextContent = function (element) {
  7070. var result = "";
  7071. var child = element.firstChild;
  7072. while (child) {
  7073. if (child.nodeType === 3) {
  7074. result += child.textContent;
  7075. }
  7076. child = child.nextSibling;
  7077. }
  7078. return result;
  7079. };
  7080. Tools.ToDegrees = function (angle) {
  7081. return angle * 180 / Math.PI;
  7082. };
  7083. Tools.ToRadians = function (angle) {
  7084. return angle * Math.PI / 180;
  7085. };
  7086. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7087. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7088. var output = "";
  7089. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7090. var i = 0;
  7091. var bytes = new Uint8Array(buffer);
  7092. while (i < bytes.length) {
  7093. chr1 = bytes[i++];
  7094. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7095. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7096. enc1 = chr1 >> 2;
  7097. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7098. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7099. enc4 = chr3 & 63;
  7100. if (isNaN(chr2)) {
  7101. enc3 = enc4 = 64;
  7102. }
  7103. else if (isNaN(chr3)) {
  7104. enc4 = 64;
  7105. }
  7106. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7107. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7108. }
  7109. return "data:image/png;base64," + output;
  7110. };
  7111. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7112. if (bias === void 0) { bias = null; }
  7113. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7114. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7115. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7116. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7117. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7118. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7119. }
  7120. if (bias) {
  7121. minimum.x -= minimum.x * bias.x + bias.y;
  7122. minimum.y -= minimum.y * bias.x + bias.y;
  7123. minimum.z -= minimum.z * bias.x + bias.y;
  7124. maximum.x += maximum.x * bias.x + bias.y;
  7125. maximum.y += maximum.y * bias.x + bias.y;
  7126. maximum.z += maximum.z * bias.x + bias.y;
  7127. }
  7128. return {
  7129. minimum: minimum,
  7130. maximum: maximum
  7131. };
  7132. };
  7133. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7134. if (bias === void 0) { bias = null; }
  7135. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7136. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7137. if (!stride) {
  7138. stride = 3;
  7139. }
  7140. for (var index = start; index < start + count; index++) {
  7141. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7142. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7143. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7144. }
  7145. if (bias) {
  7146. minimum.x -= minimum.x * bias.x + bias.y;
  7147. minimum.y -= minimum.y * bias.x + bias.y;
  7148. minimum.z -= minimum.z * bias.x + bias.y;
  7149. maximum.x += maximum.x * bias.x + bias.y;
  7150. maximum.y += maximum.y * bias.x + bias.y;
  7151. maximum.z += maximum.z * bias.x + bias.y;
  7152. }
  7153. return {
  7154. minimum: minimum,
  7155. maximum: maximum
  7156. };
  7157. };
  7158. Tools.Vector2ArrayFeeder = function (array) {
  7159. return function (index) {
  7160. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7161. var length = isFloatArray ? array.length / 2 : array.length;
  7162. if (index >= length) {
  7163. return null;
  7164. }
  7165. if (isFloatArray) {
  7166. var fa = array;
  7167. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7168. }
  7169. var a = array;
  7170. return a[index];
  7171. };
  7172. };
  7173. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7174. if (bias === void 0) { bias = null; }
  7175. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7176. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7177. var i = 0;
  7178. var cur = feeder(i++);
  7179. while (cur) {
  7180. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7181. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7182. cur = feeder(i++);
  7183. }
  7184. if (bias) {
  7185. minimum.x -= minimum.x * bias.x + bias.y;
  7186. minimum.y -= minimum.y * bias.x + bias.y;
  7187. maximum.x += maximum.x * bias.x + bias.y;
  7188. maximum.y += maximum.y * bias.x + bias.y;
  7189. }
  7190. return {
  7191. minimum: minimum,
  7192. maximum: maximum
  7193. };
  7194. };
  7195. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7196. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7197. return null;
  7198. return Array.isArray(obj) ? obj : [obj];
  7199. };
  7200. // Misc.
  7201. Tools.GetPointerPrefix = function () {
  7202. var eventPrefix = "pointer";
  7203. // Check if pointer events are supported
  7204. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7205. eventPrefix = "mouse";
  7206. }
  7207. return eventPrefix;
  7208. };
  7209. /**
  7210. * @param func - the function to be called
  7211. * @param requester - the object that will request the next frame. Falls back to window.
  7212. */
  7213. Tools.QueueNewFrame = function (func, requester) {
  7214. if (!Tools.IsWindowObjectExist()) {
  7215. return setTimeout(func, 16);
  7216. }
  7217. if (!requester) {
  7218. requester = window;
  7219. }
  7220. if (requester.requestAnimationFrame) {
  7221. return requester.requestAnimationFrame(func);
  7222. }
  7223. else if (requester.msRequestAnimationFrame) {
  7224. return requester.msRequestAnimationFrame(func);
  7225. }
  7226. else if (requester.webkitRequestAnimationFrame) {
  7227. return requester.webkitRequestAnimationFrame(func);
  7228. }
  7229. else if (requester.mozRequestAnimationFrame) {
  7230. return requester.mozRequestAnimationFrame(func);
  7231. }
  7232. else if (requester.oRequestAnimationFrame) {
  7233. return requester.oRequestAnimationFrame(func);
  7234. }
  7235. else {
  7236. return window.setTimeout(func, 16);
  7237. }
  7238. };
  7239. Tools.RequestFullscreen = function (element) {
  7240. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7241. if (!requestFunction)
  7242. return;
  7243. requestFunction.call(element);
  7244. };
  7245. Tools.ExitFullscreen = function () {
  7246. if (document.exitFullscreen) {
  7247. document.exitFullscreen();
  7248. }
  7249. else if (document.mozCancelFullScreen) {
  7250. document.mozCancelFullScreen();
  7251. }
  7252. else if (document.webkitCancelFullScreen) {
  7253. document.webkitCancelFullScreen();
  7254. }
  7255. else if (document.msCancelFullScreen) {
  7256. document.msCancelFullScreen();
  7257. }
  7258. };
  7259. Tools.SetCorsBehavior = function (url, element) {
  7260. if (url && url.indexOf("data:") === 0) {
  7261. return;
  7262. }
  7263. if (Tools.CorsBehavior) {
  7264. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7265. element.crossOrigin = Tools.CorsBehavior;
  7266. }
  7267. else {
  7268. var result = Tools.CorsBehavior(url);
  7269. if (result) {
  7270. element.crossOrigin = result;
  7271. }
  7272. }
  7273. }
  7274. };
  7275. // External files
  7276. Tools.CleanUrl = function (url) {
  7277. url = url.replace(/#/mg, "%23");
  7278. return url;
  7279. };
  7280. Tools.LoadImage = function (url, onLoad, onError, database) {
  7281. if (url instanceof ArrayBuffer) {
  7282. url = Tools.EncodeArrayBufferTobase64(url);
  7283. }
  7284. url = Tools.CleanUrl(url);
  7285. url = Tools.PreprocessUrl(url);
  7286. var img = new Image();
  7287. Tools.SetCorsBehavior(url, img);
  7288. img.onload = function () {
  7289. onLoad(img);
  7290. };
  7291. img.onerror = function (err) {
  7292. Tools.Error("Error while trying to load image: " + url);
  7293. if (onError) {
  7294. onError("Error while trying to load image: " + url, err);
  7295. }
  7296. };
  7297. var noIndexedDB = function () {
  7298. img.src = url;
  7299. };
  7300. var loadFromIndexedDB = function () {
  7301. if (database) {
  7302. database.loadImageFromDB(url, img);
  7303. }
  7304. };
  7305. //ANY database to do!
  7306. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7307. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7308. }
  7309. else {
  7310. if (url.indexOf("file:") !== -1) {
  7311. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7312. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7313. try {
  7314. var blobURL;
  7315. try {
  7316. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7317. }
  7318. catch (ex) {
  7319. // Chrome doesn't support oneTimeOnly parameter
  7320. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7321. }
  7322. img.src = blobURL;
  7323. }
  7324. catch (e) {
  7325. img.src = "";
  7326. }
  7327. return img;
  7328. }
  7329. }
  7330. noIndexedDB();
  7331. }
  7332. return img;
  7333. };
  7334. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7335. url = Tools.CleanUrl(url);
  7336. url = Tools.PreprocessUrl(url);
  7337. // If file and file input are set
  7338. if (url.indexOf("file:") !== -1) {
  7339. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7340. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7341. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7342. }
  7343. }
  7344. var loadUrl = Tools.BaseUrl + url;
  7345. var aborted = false;
  7346. var fileRequest = {
  7347. onCompleteObservable: new BABYLON.Observable(),
  7348. abort: function () { return aborted = true; },
  7349. };
  7350. var requestFile = function () {
  7351. var request = new XMLHttpRequest();
  7352. var retryHandle = null;
  7353. fileRequest.abort = function () {
  7354. aborted = true;
  7355. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7356. request.abort();
  7357. }
  7358. if (retryHandle !== null) {
  7359. clearTimeout(retryHandle);
  7360. retryHandle = null;
  7361. }
  7362. };
  7363. var retryLoop = function (retryIndex) {
  7364. request.open('GET', loadUrl, true);
  7365. if (useArrayBuffer) {
  7366. request.responseType = "arraybuffer";
  7367. }
  7368. if (onProgress) {
  7369. request.addEventListener("progress", onProgress);
  7370. }
  7371. var onLoadEnd = function () {
  7372. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7373. };
  7374. request.addEventListener("loadend", onLoadEnd);
  7375. var onReadyStateChange = function () {
  7376. if (aborted) {
  7377. return;
  7378. }
  7379. // In case of undefined state in some browsers.
  7380. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7381. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7382. request.removeEventListener("readystatechange", onReadyStateChange);
  7383. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7384. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7385. return;
  7386. }
  7387. var retryStrategy = Tools.DefaultRetryStrategy;
  7388. if (retryStrategy) {
  7389. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7390. if (waitTime !== -1) {
  7391. // Prevent the request from completing for retry.
  7392. request.removeEventListener("loadend", onLoadEnd);
  7393. request = new XMLHttpRequest();
  7394. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7395. return;
  7396. }
  7397. }
  7398. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7399. if (onError) {
  7400. onError(request, e);
  7401. }
  7402. else {
  7403. throw e;
  7404. }
  7405. }
  7406. };
  7407. request.addEventListener("readystatechange", onReadyStateChange);
  7408. request.send();
  7409. };
  7410. retryLoop(0);
  7411. };
  7412. // Caching all files
  7413. if (database && database.enableSceneOffline) {
  7414. var noIndexedDB_1 = function () {
  7415. if (!aborted) {
  7416. requestFile();
  7417. }
  7418. };
  7419. var loadFromIndexedDB = function () {
  7420. // TODO: database needs to support aborting and should return a IFileRequest
  7421. if (aborted) {
  7422. return;
  7423. }
  7424. if (database) {
  7425. database.loadFileFromDB(url, function (data) {
  7426. if (!aborted) {
  7427. onSuccess(data);
  7428. }
  7429. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7430. }, onProgress ? function (event) {
  7431. if (!aborted) {
  7432. onProgress(event);
  7433. }
  7434. } : undefined, noIndexedDB_1, useArrayBuffer);
  7435. }
  7436. };
  7437. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7438. }
  7439. else {
  7440. requestFile();
  7441. }
  7442. return fileRequest;
  7443. };
  7444. /**
  7445. * Load a script (identified by an url). When the url returns, the
  7446. * content of this file is added into a new script element, attached to the DOM (body element)
  7447. */
  7448. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7449. var head = document.getElementsByTagName('head')[0];
  7450. var script = document.createElement('script');
  7451. script.type = 'text/javascript';
  7452. script.src = scriptUrl;
  7453. script.onload = function () {
  7454. if (onSuccess) {
  7455. onSuccess();
  7456. }
  7457. };
  7458. script.onerror = function (e) {
  7459. if (onError) {
  7460. onError("Unable to load script", e);
  7461. }
  7462. };
  7463. head.appendChild(script);
  7464. };
  7465. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7466. var reader = new FileReader();
  7467. var request = {
  7468. onCompleteObservable: new BABYLON.Observable(),
  7469. abort: function () { return reader.abort(); },
  7470. };
  7471. reader.onloadend = function (e) {
  7472. request.onCompleteObservable.notifyObservers(request);
  7473. };
  7474. reader.onload = function (e) {
  7475. //target doesn't have result from ts 1.3
  7476. callback(e.target['result']);
  7477. };
  7478. reader.onprogress = progressCallback;
  7479. reader.readAsDataURL(fileToLoad);
  7480. return request;
  7481. };
  7482. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7483. var reader = new FileReader();
  7484. var request = {
  7485. onCompleteObservable: new BABYLON.Observable(),
  7486. abort: function () { return reader.abort(); },
  7487. };
  7488. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7489. reader.onerror = function (e) {
  7490. Tools.Log("Error while reading file: " + fileToLoad.name);
  7491. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7492. };
  7493. reader.onload = function (e) {
  7494. //target doesn't have result from ts 1.3
  7495. callback(e.target['result']);
  7496. };
  7497. if (progressCallBack) {
  7498. reader.onprogress = progressCallBack;
  7499. }
  7500. if (!useArrayBuffer) {
  7501. // Asynchronous read
  7502. reader.readAsText(fileToLoad);
  7503. }
  7504. else {
  7505. reader.readAsArrayBuffer(fileToLoad);
  7506. }
  7507. return request;
  7508. };
  7509. //returns a downloadable url to a file content.
  7510. Tools.FileAsURL = function (content) {
  7511. var fileBlob = new Blob([content]);
  7512. var url = window.URL || window.webkitURL;
  7513. var link = url.createObjectURL(fileBlob);
  7514. return link;
  7515. };
  7516. // Misc.
  7517. Tools.Format = function (value, decimals) {
  7518. if (decimals === void 0) { decimals = 2; }
  7519. return value.toFixed(decimals);
  7520. };
  7521. Tools.CheckExtends = function (v, min, max) {
  7522. if (v.x < min.x)
  7523. min.x = v.x;
  7524. if (v.y < min.y)
  7525. min.y = v.y;
  7526. if (v.z < min.z)
  7527. min.z = v.z;
  7528. if (v.x > max.x)
  7529. max.x = v.x;
  7530. if (v.y > max.y)
  7531. max.y = v.y;
  7532. if (v.z > max.z)
  7533. max.z = v.z;
  7534. };
  7535. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7536. for (var prop in source) {
  7537. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7538. continue;
  7539. }
  7540. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7541. continue;
  7542. }
  7543. var sourceValue = source[prop];
  7544. var typeOfSourceValue = typeof sourceValue;
  7545. if (typeOfSourceValue === "function") {
  7546. continue;
  7547. }
  7548. if (typeOfSourceValue === "object") {
  7549. if (sourceValue instanceof Array) {
  7550. destination[prop] = [];
  7551. if (sourceValue.length > 0) {
  7552. if (typeof sourceValue[0] == "object") {
  7553. for (var index = 0; index < sourceValue.length; index++) {
  7554. var clonedValue = cloneValue(sourceValue[index], destination);
  7555. if (destination[prop].indexOf(clonedValue) === -1) {
  7556. destination[prop].push(clonedValue);
  7557. }
  7558. }
  7559. }
  7560. else {
  7561. destination[prop] = sourceValue.slice(0);
  7562. }
  7563. }
  7564. }
  7565. else {
  7566. destination[prop] = cloneValue(sourceValue, destination);
  7567. }
  7568. }
  7569. else {
  7570. destination[prop] = sourceValue;
  7571. }
  7572. }
  7573. };
  7574. Tools.IsEmpty = function (obj) {
  7575. for (var i in obj) {
  7576. if (obj.hasOwnProperty(i)) {
  7577. return false;
  7578. }
  7579. }
  7580. return true;
  7581. };
  7582. Tools.RegisterTopRootEvents = function (events) {
  7583. for (var index = 0; index < events.length; index++) {
  7584. var event = events[index];
  7585. window.addEventListener(event.name, event.handler, false);
  7586. try {
  7587. if (window.parent) {
  7588. window.parent.addEventListener(event.name, event.handler, false);
  7589. }
  7590. }
  7591. catch (e) {
  7592. // Silently fails...
  7593. }
  7594. }
  7595. };
  7596. Tools.UnregisterTopRootEvents = function (events) {
  7597. for (var index = 0; index < events.length; index++) {
  7598. var event = events[index];
  7599. window.removeEventListener(event.name, event.handler);
  7600. try {
  7601. if (window.parent) {
  7602. window.parent.removeEventListener(event.name, event.handler);
  7603. }
  7604. }
  7605. catch (e) {
  7606. // Silently fails...
  7607. }
  7608. }
  7609. };
  7610. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7611. if (mimeType === void 0) { mimeType = "image/png"; }
  7612. // Read the contents of the framebuffer
  7613. var numberOfChannelsByLine = width * 4;
  7614. var halfHeight = height / 2;
  7615. //Reading datas from WebGL
  7616. var data = engine.readPixels(0, 0, width, height);
  7617. //To flip image on Y axis.
  7618. for (var i = 0; i < halfHeight; i++) {
  7619. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7620. var currentCell = j + i * numberOfChannelsByLine;
  7621. var targetLine = height - i - 1;
  7622. var targetCell = j + targetLine * numberOfChannelsByLine;
  7623. var temp = data[currentCell];
  7624. data[currentCell] = data[targetCell];
  7625. data[targetCell] = temp;
  7626. }
  7627. }
  7628. // Create a 2D canvas to store the result
  7629. if (!screenshotCanvas) {
  7630. screenshotCanvas = document.createElement('canvas');
  7631. }
  7632. screenshotCanvas.width = width;
  7633. screenshotCanvas.height = height;
  7634. var context = screenshotCanvas.getContext('2d');
  7635. if (context) {
  7636. // Copy the pixels to a 2D canvas
  7637. var imageData = context.createImageData(width, height);
  7638. var castData = (imageData.data);
  7639. castData.set(data);
  7640. context.putImageData(imageData, 0, 0);
  7641. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7642. }
  7643. };
  7644. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7645. if (mimeType === void 0) { mimeType = "image/png"; }
  7646. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7647. if (successCallback) {
  7648. successCallback(base64Image);
  7649. }
  7650. else {
  7651. // We need HTMLCanvasElement.toBlob for HD screenshots
  7652. if (!screenshotCanvas.toBlob) {
  7653. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7654. screenshotCanvas.toBlob = function (callback, type, quality) {
  7655. var _this = this;
  7656. setTimeout(function () {
  7657. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7658. for (var i = 0; i < len; i++) {
  7659. arr[i] = binStr.charCodeAt(i);
  7660. }
  7661. callback(new Blob([arr], { type: type || 'image/png' }));
  7662. });
  7663. };
  7664. }
  7665. screenshotCanvas.toBlob(function (blob) {
  7666. var url = URL.createObjectURL(blob);
  7667. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7668. if (("download" in document.createElement("a"))) {
  7669. var a = window.document.createElement("a");
  7670. a.href = url;
  7671. if (fileName) {
  7672. a.setAttribute("download", fileName);
  7673. }
  7674. else {
  7675. var date = new Date();
  7676. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7677. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7678. }
  7679. window.document.body.appendChild(a);
  7680. a.addEventListener("click", function () {
  7681. if (a.parentElement) {
  7682. a.parentElement.removeChild(a);
  7683. }
  7684. });
  7685. a.click();
  7686. }
  7687. else {
  7688. var newWindow = window.open("");
  7689. if (!newWindow)
  7690. return;
  7691. var img = newWindow.document.createElement("img");
  7692. img.onload = function () {
  7693. // no longer need to read the blob so it's revoked
  7694. URL.revokeObjectURL(url);
  7695. };
  7696. img.src = url;
  7697. newWindow.document.body.appendChild(img);
  7698. }
  7699. });
  7700. }
  7701. };
  7702. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7703. if (mimeType === void 0) { mimeType = "image/png"; }
  7704. var width;
  7705. var height;
  7706. // If a precision value is specified
  7707. if (size.precision) {
  7708. width = Math.round(engine.getRenderWidth() * size.precision);
  7709. height = Math.round(width / engine.getAspectRatio(camera));
  7710. }
  7711. else if (size.width && size.height) {
  7712. width = size.width;
  7713. height = size.height;
  7714. }
  7715. else if (size.width && !size.height) {
  7716. width = size.width;
  7717. height = Math.round(width / engine.getAspectRatio(camera));
  7718. }
  7719. else if (size.height && !size.width) {
  7720. height = size.height;
  7721. width = Math.round(height * engine.getAspectRatio(camera));
  7722. }
  7723. else if (!isNaN(size)) {
  7724. height = size;
  7725. width = size;
  7726. }
  7727. else {
  7728. Tools.Error("Invalid 'size' parameter !");
  7729. return;
  7730. }
  7731. if (!screenshotCanvas) {
  7732. screenshotCanvas = document.createElement('canvas');
  7733. }
  7734. screenshotCanvas.width = width;
  7735. screenshotCanvas.height = height;
  7736. var renderContext = screenshotCanvas.getContext("2d");
  7737. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7738. var newWidth = width;
  7739. var newHeight = newWidth / ratio;
  7740. if (newHeight > height) {
  7741. newHeight = height;
  7742. newWidth = newHeight * ratio;
  7743. }
  7744. var offsetX = Math.max(0, width - newWidth) / 2;
  7745. var offsetY = Math.max(0, height - newHeight) / 2;
  7746. var renderingCanvas = engine.getRenderingCanvas();
  7747. if (renderContext && renderingCanvas) {
  7748. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7749. }
  7750. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7751. };
  7752. /**
  7753. * Generates an image screenshot from the specified camera.
  7754. *
  7755. * @param engine The engine to use for rendering
  7756. * @param camera The camera to use for rendering
  7757. * @param size This parameter can be set to a single number or to an object with the
  7758. * following (optional) properties: precision, width, height. If a single number is passed,
  7759. * it will be used for both width and height. If an object is passed, the screenshot size
  7760. * will be derived from the parameters. The precision property is a multiplier allowing
  7761. * rendering at a higher or lower resolution.
  7762. * @param successCallback The callback receives a single parameter which contains the
  7763. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7764. * src parameter of an <img> to display it.
  7765. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7766. * Check your browser for supported MIME types.
  7767. * @param samples Texture samples (default: 1)
  7768. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7769. * @param fileName A name for for the downloaded file.
  7770. * @constructor
  7771. */
  7772. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7773. if (mimeType === void 0) { mimeType = "image/png"; }
  7774. if (samples === void 0) { samples = 1; }
  7775. if (antialiasing === void 0) { antialiasing = false; }
  7776. var width;
  7777. var height;
  7778. //If a precision value is specified
  7779. if (size.precision) {
  7780. width = Math.round(engine.getRenderWidth() * size.precision);
  7781. height = Math.round(width / engine.getAspectRatio(camera));
  7782. size = { width: width, height: height };
  7783. }
  7784. else if (size.width && size.height) {
  7785. width = size.width;
  7786. height = size.height;
  7787. }
  7788. else if (size.width && !size.height) {
  7789. width = size.width;
  7790. height = Math.round(width / engine.getAspectRatio(camera));
  7791. size = { width: width, height: height };
  7792. }
  7793. else if (size.height && !size.width) {
  7794. height = size.height;
  7795. width = Math.round(height * engine.getAspectRatio(camera));
  7796. size = { width: width, height: height };
  7797. }
  7798. else if (!isNaN(size)) {
  7799. height = size;
  7800. width = size;
  7801. }
  7802. else {
  7803. Tools.Error("Invalid 'size' parameter !");
  7804. return;
  7805. }
  7806. var scene = camera.getScene();
  7807. var previousCamera = null;
  7808. if (scene.activeCamera !== camera) {
  7809. previousCamera = scene.activeCamera;
  7810. scene.activeCamera = camera;
  7811. }
  7812. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7813. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7814. texture.renderList = null;
  7815. texture.samples = samples;
  7816. if (antialiasing) {
  7817. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7818. }
  7819. texture.onAfterRenderObservable.add(function () {
  7820. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7821. });
  7822. scene.incrementRenderId();
  7823. scene.resetCachedMaterial();
  7824. texture.render(true);
  7825. texture.dispose();
  7826. if (previousCamera) {
  7827. scene.activeCamera = previousCamera;
  7828. }
  7829. camera.getProjectionMatrix(true); // Force cache refresh;
  7830. };
  7831. // XHR response validator for local file scenario
  7832. Tools.ValidateXHRData = function (xhr, dataType) {
  7833. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7834. if (dataType === void 0) { dataType = 7; }
  7835. try {
  7836. if (dataType & 1) {
  7837. if (xhr.responseText && xhr.responseText.length > 0) {
  7838. return true;
  7839. }
  7840. else if (dataType === 1) {
  7841. return false;
  7842. }
  7843. }
  7844. if (dataType & 2) {
  7845. // Check header width and height since there is no "TGA" magic number
  7846. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7847. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7848. return true;
  7849. }
  7850. else if (dataType === 2) {
  7851. return false;
  7852. }
  7853. }
  7854. if (dataType & 4) {
  7855. // Check for the "DDS" magic number
  7856. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7857. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7858. return true;
  7859. }
  7860. else {
  7861. return false;
  7862. }
  7863. }
  7864. }
  7865. catch (e) {
  7866. // Global protection
  7867. }
  7868. return false;
  7869. };
  7870. /**
  7871. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7872. * Be aware Math.random() could cause collisions, but:
  7873. * "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"
  7874. */
  7875. Tools.RandomId = function () {
  7876. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7877. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7878. return v.toString(16);
  7879. });
  7880. };
  7881. Object.defineProperty(Tools, "NoneLogLevel", {
  7882. get: function () {
  7883. return Tools._NoneLogLevel;
  7884. },
  7885. enumerable: true,
  7886. configurable: true
  7887. });
  7888. Object.defineProperty(Tools, "MessageLogLevel", {
  7889. get: function () {
  7890. return Tools._MessageLogLevel;
  7891. },
  7892. enumerable: true,
  7893. configurable: true
  7894. });
  7895. Object.defineProperty(Tools, "WarningLogLevel", {
  7896. get: function () {
  7897. return Tools._WarningLogLevel;
  7898. },
  7899. enumerable: true,
  7900. configurable: true
  7901. });
  7902. Object.defineProperty(Tools, "ErrorLogLevel", {
  7903. get: function () {
  7904. return Tools._ErrorLogLevel;
  7905. },
  7906. enumerable: true,
  7907. configurable: true
  7908. });
  7909. Object.defineProperty(Tools, "AllLogLevel", {
  7910. get: function () {
  7911. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7912. },
  7913. enumerable: true,
  7914. configurable: true
  7915. });
  7916. Tools._AddLogEntry = function (entry) {
  7917. Tools._LogCache = entry + Tools._LogCache;
  7918. if (Tools.OnNewCacheEntry) {
  7919. Tools.OnNewCacheEntry(entry);
  7920. }
  7921. };
  7922. Tools._FormatMessage = function (message) {
  7923. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7924. var date = new Date();
  7925. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7926. };
  7927. Tools._LogDisabled = function (message) {
  7928. // nothing to do
  7929. };
  7930. Tools._LogEnabled = function (message) {
  7931. var formattedMessage = Tools._FormatMessage(message);
  7932. console.log("BJS - " + formattedMessage);
  7933. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7934. Tools._AddLogEntry(entry);
  7935. };
  7936. Tools._WarnDisabled = function (message) {
  7937. // nothing to do
  7938. };
  7939. Tools._WarnEnabled = function (message) {
  7940. var formattedMessage = Tools._FormatMessage(message);
  7941. console.warn("BJS - " + formattedMessage);
  7942. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7943. Tools._AddLogEntry(entry);
  7944. };
  7945. Tools._ErrorDisabled = function (message) {
  7946. // nothing to do
  7947. };
  7948. Tools._ErrorEnabled = function (message) {
  7949. Tools.errorsCount++;
  7950. var formattedMessage = Tools._FormatMessage(message);
  7951. console.error("BJS - " + formattedMessage);
  7952. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7953. Tools._AddLogEntry(entry);
  7954. };
  7955. Object.defineProperty(Tools, "LogCache", {
  7956. get: function () {
  7957. return Tools._LogCache;
  7958. },
  7959. enumerable: true,
  7960. configurable: true
  7961. });
  7962. Tools.ClearLogCache = function () {
  7963. Tools._LogCache = "";
  7964. Tools.errorsCount = 0;
  7965. };
  7966. Object.defineProperty(Tools, "LogLevels", {
  7967. set: function (level) {
  7968. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7969. Tools.Log = Tools._LogEnabled;
  7970. }
  7971. else {
  7972. Tools.Log = Tools._LogDisabled;
  7973. }
  7974. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7975. Tools.Warn = Tools._WarnEnabled;
  7976. }
  7977. else {
  7978. Tools.Warn = Tools._WarnDisabled;
  7979. }
  7980. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7981. Tools.Error = Tools._ErrorEnabled;
  7982. }
  7983. else {
  7984. Tools.Error = Tools._ErrorDisabled;
  7985. }
  7986. },
  7987. enumerable: true,
  7988. configurable: true
  7989. });
  7990. Tools.IsWindowObjectExist = function () {
  7991. return (typeof window) !== "undefined";
  7992. };
  7993. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7994. get: function () {
  7995. return Tools._PerformanceNoneLogLevel;
  7996. },
  7997. enumerable: true,
  7998. configurable: true
  7999. });
  8000. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8001. get: function () {
  8002. return Tools._PerformanceUserMarkLogLevel;
  8003. },
  8004. enumerable: true,
  8005. configurable: true
  8006. });
  8007. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8008. get: function () {
  8009. return Tools._PerformanceConsoleLogLevel;
  8010. },
  8011. enumerable: true,
  8012. configurable: true
  8013. });
  8014. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8015. set: function (level) {
  8016. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8017. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8018. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8019. return;
  8020. }
  8021. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8022. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8023. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8024. return;
  8025. }
  8026. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8027. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8028. },
  8029. enumerable: true,
  8030. configurable: true
  8031. });
  8032. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8033. };
  8034. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8035. };
  8036. Tools._StartUserMark = function (counterName, condition) {
  8037. if (condition === void 0) { condition = true; }
  8038. if (!Tools._performance) {
  8039. if (!Tools.IsWindowObjectExist()) {
  8040. return;
  8041. }
  8042. Tools._performance = window.performance;
  8043. }
  8044. if (!condition || !Tools._performance.mark) {
  8045. return;
  8046. }
  8047. Tools._performance.mark(counterName + "-Begin");
  8048. };
  8049. Tools._EndUserMark = function (counterName, condition) {
  8050. if (condition === void 0) { condition = true; }
  8051. if (!condition || !Tools._performance.mark) {
  8052. return;
  8053. }
  8054. Tools._performance.mark(counterName + "-End");
  8055. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8056. };
  8057. Tools._StartPerformanceConsole = function (counterName, condition) {
  8058. if (condition === void 0) { condition = true; }
  8059. if (!condition) {
  8060. return;
  8061. }
  8062. Tools._StartUserMark(counterName, condition);
  8063. if (console.time) {
  8064. console.time(counterName);
  8065. }
  8066. };
  8067. Tools._EndPerformanceConsole = function (counterName, condition) {
  8068. if (condition === void 0) { condition = true; }
  8069. if (!condition) {
  8070. return;
  8071. }
  8072. Tools._EndUserMark(counterName, condition);
  8073. if (console.time) {
  8074. console.timeEnd(counterName);
  8075. }
  8076. };
  8077. Object.defineProperty(Tools, "Now", {
  8078. get: function () {
  8079. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8080. return window.performance.now();
  8081. }
  8082. return new Date().getTime();
  8083. },
  8084. enumerable: true,
  8085. configurable: true
  8086. });
  8087. /**
  8088. * This method will return the name of the class used to create the instance of the given object.
  8089. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8090. * @param object the object to get the class name from
  8091. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8092. */
  8093. Tools.GetClassName = function (object, isType) {
  8094. if (isType === void 0) { isType = false; }
  8095. var name = null;
  8096. if (!isType && object.getClassName) {
  8097. name = object.getClassName();
  8098. }
  8099. else {
  8100. if (object instanceof Object) {
  8101. var classObj = isType ? object : Object.getPrototypeOf(object);
  8102. name = classObj.constructor["__bjsclassName__"];
  8103. }
  8104. if (!name) {
  8105. name = typeof object;
  8106. }
  8107. }
  8108. return name;
  8109. };
  8110. Tools.First = function (array, predicate) {
  8111. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8112. var el = array_1[_i];
  8113. if (predicate(el)) {
  8114. return el;
  8115. }
  8116. }
  8117. return null;
  8118. };
  8119. /**
  8120. * This method will return the name of the full name of the class, including its owning module (if any).
  8121. * 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).
  8122. * @param object the object to get the class name from
  8123. * @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.
  8124. */
  8125. Tools.getFullClassName = function (object, isType) {
  8126. if (isType === void 0) { isType = false; }
  8127. var className = null;
  8128. var moduleName = null;
  8129. if (!isType && object.getClassName) {
  8130. className = object.getClassName();
  8131. }
  8132. else {
  8133. if (object instanceof Object) {
  8134. var classObj = isType ? object : Object.getPrototypeOf(object);
  8135. className = classObj.constructor["__bjsclassName__"];
  8136. moduleName = classObj.constructor["__bjsmoduleName__"];
  8137. }
  8138. if (!className) {
  8139. className = typeof object;
  8140. }
  8141. }
  8142. if (!className) {
  8143. return null;
  8144. }
  8145. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8146. };
  8147. /**
  8148. * 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.
  8149. * @param array
  8150. */
  8151. Tools.arrayOrStringFeeder = function (array) {
  8152. return function (index) {
  8153. if (index >= array.length) {
  8154. return null;
  8155. }
  8156. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8157. if (val && val.getHashCode) {
  8158. val = val.getHashCode();
  8159. }
  8160. if (typeof val === "string") {
  8161. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8162. }
  8163. return val;
  8164. };
  8165. };
  8166. /**
  8167. * Compute the hashCode of a stream of number
  8168. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8169. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8170. * @return the hash code computed
  8171. */
  8172. Tools.hashCodeFromStream = function (feeder) {
  8173. // Based from here: http://stackoverflow.com/a/7616484/802124
  8174. var hash = 0;
  8175. var index = 0;
  8176. var chr = feeder(index++);
  8177. while (chr != null) {
  8178. hash = ((hash << 5) - hash) + chr;
  8179. hash |= 0; // Convert to 32bit integer
  8180. chr = feeder(index++);
  8181. }
  8182. return hash;
  8183. };
  8184. Tools.BaseUrl = "";
  8185. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8186. /**
  8187. * Default behaviour for cors in the application.
  8188. * It can be a string if the expected behavior is identical in the entire app.
  8189. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8190. */
  8191. Tools.CorsBehavior = "anonymous";
  8192. Tools.UseFallbackTexture = true;
  8193. /**
  8194. * Use this object to register external classes like custom textures or material
  8195. * to allow the laoders to instantiate them
  8196. */
  8197. Tools.RegisteredExternalClasses = {};
  8198. // Used in case of a texture loading problem
  8199. 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";
  8200. Tools.PreprocessUrl = function (url) {
  8201. return url;
  8202. };
  8203. // Logs
  8204. Tools._NoneLogLevel = 0;
  8205. Tools._MessageLogLevel = 1;
  8206. Tools._WarningLogLevel = 2;
  8207. Tools._ErrorLogLevel = 4;
  8208. Tools._LogCache = "";
  8209. Tools.errorsCount = 0;
  8210. Tools.Log = Tools._LogEnabled;
  8211. Tools.Warn = Tools._WarnEnabled;
  8212. Tools.Error = Tools._ErrorEnabled;
  8213. // Performances
  8214. Tools._PerformanceNoneLogLevel = 0;
  8215. Tools._PerformanceUserMarkLogLevel = 1;
  8216. Tools._PerformanceConsoleLogLevel = 2;
  8217. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8218. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8219. return Tools;
  8220. }());
  8221. BABYLON.Tools = Tools;
  8222. /**
  8223. * This class is used to track a performance counter which is number based.
  8224. * The user has access to many properties which give statistics of different nature
  8225. *
  8226. * The implementer can track two kinds of Performance Counter: time and count
  8227. * 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.
  8228. * 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.
  8229. */
  8230. var PerfCounter = /** @class */ (function () {
  8231. function PerfCounter() {
  8232. this._startMonitoringTime = 0;
  8233. this._min = 0;
  8234. this._max = 0;
  8235. this._average = 0;
  8236. this._lastSecAverage = 0;
  8237. this._current = 0;
  8238. this._totalValueCount = 0;
  8239. this._totalAccumulated = 0;
  8240. this._lastSecAccumulated = 0;
  8241. this._lastSecTime = 0;
  8242. this._lastSecValueCount = 0;
  8243. }
  8244. Object.defineProperty(PerfCounter.prototype, "min", {
  8245. /**
  8246. * Returns the smallest value ever
  8247. */
  8248. get: function () {
  8249. return this._min;
  8250. },
  8251. enumerable: true,
  8252. configurable: true
  8253. });
  8254. Object.defineProperty(PerfCounter.prototype, "max", {
  8255. /**
  8256. * Returns the biggest value ever
  8257. */
  8258. get: function () {
  8259. return this._max;
  8260. },
  8261. enumerable: true,
  8262. configurable: true
  8263. });
  8264. Object.defineProperty(PerfCounter.prototype, "average", {
  8265. /**
  8266. * Returns the average value since the performance counter is running
  8267. */
  8268. get: function () {
  8269. return this._average;
  8270. },
  8271. enumerable: true,
  8272. configurable: true
  8273. });
  8274. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8275. /**
  8276. * Returns the average value of the last second the counter was monitored
  8277. */
  8278. get: function () {
  8279. return this._lastSecAverage;
  8280. },
  8281. enumerable: true,
  8282. configurable: true
  8283. });
  8284. Object.defineProperty(PerfCounter.prototype, "current", {
  8285. /**
  8286. * Returns the current value
  8287. */
  8288. get: function () {
  8289. return this._current;
  8290. },
  8291. enumerable: true,
  8292. configurable: true
  8293. });
  8294. Object.defineProperty(PerfCounter.prototype, "total", {
  8295. get: function () {
  8296. return this._totalAccumulated;
  8297. },
  8298. enumerable: true,
  8299. configurable: true
  8300. });
  8301. Object.defineProperty(PerfCounter.prototype, "count", {
  8302. get: function () {
  8303. return this._totalValueCount;
  8304. },
  8305. enumerable: true,
  8306. configurable: true
  8307. });
  8308. /**
  8309. * Call this method to start monitoring a new frame.
  8310. * 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.
  8311. */
  8312. PerfCounter.prototype.fetchNewFrame = function () {
  8313. this._totalValueCount++;
  8314. this._current = 0;
  8315. this._lastSecValueCount++;
  8316. };
  8317. /**
  8318. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8319. * @param newCount the count value to add to the monitored count
  8320. * @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.
  8321. */
  8322. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8323. if (!PerfCounter.Enabled) {
  8324. return;
  8325. }
  8326. this._current += newCount;
  8327. if (fetchResult) {
  8328. this._fetchResult();
  8329. }
  8330. };
  8331. /**
  8332. * Start monitoring this performance counter
  8333. */
  8334. PerfCounter.prototype.beginMonitoring = function () {
  8335. if (!PerfCounter.Enabled) {
  8336. return;
  8337. }
  8338. this._startMonitoringTime = Tools.Now;
  8339. };
  8340. /**
  8341. * Compute the time lapsed since the previous beginMonitoring() call.
  8342. * @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
  8343. */
  8344. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8345. if (newFrame === void 0) { newFrame = true; }
  8346. if (!PerfCounter.Enabled) {
  8347. return;
  8348. }
  8349. if (newFrame) {
  8350. this.fetchNewFrame();
  8351. }
  8352. var currentTime = Tools.Now;
  8353. this._current = currentTime - this._startMonitoringTime;
  8354. if (newFrame) {
  8355. this._fetchResult();
  8356. }
  8357. };
  8358. PerfCounter.prototype._fetchResult = function () {
  8359. this._totalAccumulated += this._current;
  8360. this._lastSecAccumulated += this._current;
  8361. // Min/Max update
  8362. this._min = Math.min(this._min, this._current);
  8363. this._max = Math.max(this._max, this._current);
  8364. this._average = this._totalAccumulated / this._totalValueCount;
  8365. // Reset last sec?
  8366. var now = Tools.Now;
  8367. if ((now - this._lastSecTime) > 1000) {
  8368. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8369. this._lastSecTime = now;
  8370. this._lastSecAccumulated = 0;
  8371. this._lastSecValueCount = 0;
  8372. }
  8373. };
  8374. PerfCounter.Enabled = true;
  8375. return PerfCounter;
  8376. }());
  8377. BABYLON.PerfCounter = PerfCounter;
  8378. /**
  8379. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8380. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8381. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8382. * @param name The name of the class, case should be preserved
  8383. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8384. */
  8385. function className(name, module) {
  8386. return function (target) {
  8387. target["__bjsclassName__"] = name;
  8388. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8389. };
  8390. }
  8391. BABYLON.className = className;
  8392. /**
  8393. * An implementation of a loop for asynchronous functions.
  8394. */
  8395. var AsyncLoop = /** @class */ (function () {
  8396. /**
  8397. * Constroctor.
  8398. * @param iterations the number of iterations.
  8399. * @param _fn the function to run each iteration
  8400. * @param _successCallback the callback that will be called upon succesful execution
  8401. * @param offset starting offset.
  8402. */
  8403. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8404. if (offset === void 0) { offset = 0; }
  8405. this.iterations = iterations;
  8406. this._fn = _fn;
  8407. this._successCallback = _successCallback;
  8408. this.index = offset - 1;
  8409. this._done = false;
  8410. }
  8411. /**
  8412. * Execute the next iteration. Must be called after the last iteration was finished.
  8413. */
  8414. AsyncLoop.prototype.executeNext = function () {
  8415. if (!this._done) {
  8416. if (this.index + 1 < this.iterations) {
  8417. ++this.index;
  8418. this._fn(this);
  8419. }
  8420. else {
  8421. this.breakLoop();
  8422. }
  8423. }
  8424. };
  8425. /**
  8426. * Break the loop and run the success callback.
  8427. */
  8428. AsyncLoop.prototype.breakLoop = function () {
  8429. this._done = true;
  8430. this._successCallback();
  8431. };
  8432. /**
  8433. * Helper function
  8434. */
  8435. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8436. if (offset === void 0) { offset = 0; }
  8437. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8438. loop.executeNext();
  8439. return loop;
  8440. };
  8441. /**
  8442. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8443. * @param iterations total number of iterations
  8444. * @param syncedIterations number of synchronous iterations in each async iteration.
  8445. * @param fn the function to call each iteration.
  8446. * @param callback a success call back that will be called when iterating stops.
  8447. * @param breakFunction a break condition (optional)
  8448. * @param timeout timeout settings for the setTimeout function. default - 0.
  8449. * @constructor
  8450. */
  8451. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8452. if (timeout === void 0) { timeout = 0; }
  8453. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8454. if (breakFunction && breakFunction())
  8455. loop.breakLoop();
  8456. else {
  8457. setTimeout(function () {
  8458. for (var i = 0; i < syncedIterations; ++i) {
  8459. var iteration = (loop.index * syncedIterations) + i;
  8460. if (iteration >= iterations)
  8461. break;
  8462. fn(iteration);
  8463. if (breakFunction && breakFunction()) {
  8464. loop.breakLoop();
  8465. break;
  8466. }
  8467. }
  8468. loop.executeNext();
  8469. }, timeout);
  8470. }
  8471. }, callback);
  8472. };
  8473. return AsyncLoop;
  8474. }());
  8475. BABYLON.AsyncLoop = AsyncLoop;
  8476. })(BABYLON || (BABYLON = {}));
  8477. //# sourceMappingURL=babylon.tools.js.map
  8478. var BABYLON;
  8479. (function (BABYLON) {
  8480. var PromiseStates;
  8481. (function (PromiseStates) {
  8482. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  8483. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  8484. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  8485. })(PromiseStates || (PromiseStates = {}));
  8486. var FulFillmentAgregator = /** @class */ (function () {
  8487. function FulFillmentAgregator() {
  8488. this.count = 0;
  8489. this.target = 0;
  8490. this.results = [];
  8491. }
  8492. return FulFillmentAgregator;
  8493. }());
  8494. var InternalPromise = /** @class */ (function () {
  8495. function InternalPromise(resolver) {
  8496. var _this = this;
  8497. this._state = PromiseStates.Pending;
  8498. this._children = new Array();
  8499. this._rejectWasConsumed = false;
  8500. if (!resolver) {
  8501. return;
  8502. }
  8503. try {
  8504. resolver(function (value) {
  8505. _this._resolve(value);
  8506. }, function (reason) {
  8507. _this._reject(reason);
  8508. });
  8509. }
  8510. catch (e) {
  8511. this._reject(e.message);
  8512. }
  8513. }
  8514. Object.defineProperty(InternalPromise.prototype, "state", {
  8515. get: function () {
  8516. return this._state;
  8517. },
  8518. enumerable: true,
  8519. configurable: true
  8520. });
  8521. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  8522. get: function () {
  8523. return this._state === PromiseStates.Fulfilled;
  8524. },
  8525. enumerable: true,
  8526. configurable: true
  8527. });
  8528. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  8529. get: function () {
  8530. return this._state === PromiseStates.Rejected;
  8531. },
  8532. enumerable: true,
  8533. configurable: true
  8534. });
  8535. Object.defineProperty(InternalPromise.prototype, "isPending", {
  8536. get: function () {
  8537. return this._state === PromiseStates.Pending;
  8538. },
  8539. enumerable: true,
  8540. configurable: true
  8541. });
  8542. InternalPromise.prototype.value = function () {
  8543. if (!this.isFulfilled) {
  8544. throw new Error("Promise is not fulfilled");
  8545. }
  8546. return this._result;
  8547. };
  8548. InternalPromise.prototype.reason = function () {
  8549. if (!this.isRejected) {
  8550. throw new Error("Promise is not rejected");
  8551. }
  8552. return this._reason;
  8553. };
  8554. InternalPromise.prototype.catch = function (onRejected) {
  8555. return this.then(undefined, onRejected);
  8556. };
  8557. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  8558. var newPromise = new InternalPromise();
  8559. newPromise._onFulfilled = onFulfilled;
  8560. newPromise._onRejected = onRejected;
  8561. // Composition
  8562. this._children.push(newPromise);
  8563. if (this._state !== PromiseStates.Pending) {
  8564. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  8565. var returnedValue = newPromise._resolve(this._result);
  8566. if (returnedValue !== undefined && returnedValue !== null) {
  8567. if (returnedValue._state !== undefined) {
  8568. var returnedPromise = returnedValue;
  8569. newPromise._children.push(returnedPromise);
  8570. newPromise = returnedPromise;
  8571. }
  8572. else {
  8573. newPromise._result = returnedValue;
  8574. }
  8575. }
  8576. }
  8577. else {
  8578. newPromise._reject(this._reason);
  8579. }
  8580. }
  8581. return newPromise;
  8582. };
  8583. InternalPromise.prototype._moveChildren = function (children) {
  8584. this._children = children.splice(0, children.length);
  8585. if (this.isFulfilled) {
  8586. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8587. var child = _a[_i];
  8588. child._resolve(this._result);
  8589. }
  8590. }
  8591. else if (this.isRejected) {
  8592. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  8593. var child = _c[_b];
  8594. child._reject(this._reason);
  8595. }
  8596. }
  8597. };
  8598. InternalPromise.prototype._resolve = function (value) {
  8599. try {
  8600. this._state = PromiseStates.Fulfilled;
  8601. this._result = value;
  8602. var returnedValue = null;
  8603. if (this._onFulfilled) {
  8604. returnedValue = this._onFulfilled(value);
  8605. }
  8606. if (returnedValue !== undefined && returnedValue !== null) {
  8607. if (returnedValue._state !== undefined) {
  8608. // Transmit children
  8609. var returnedPromise = returnedValue;
  8610. returnedPromise._moveChildren(this._children);
  8611. }
  8612. }
  8613. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8614. var child = _a[_i];
  8615. child._resolve(value);
  8616. }
  8617. return returnedValue;
  8618. }
  8619. catch (e) {
  8620. this._reject(e.message);
  8621. }
  8622. return null;
  8623. };
  8624. InternalPromise.prototype._reject = function (reason) {
  8625. this._state = PromiseStates.Rejected;
  8626. this._reason = reason;
  8627. if (this._onRejected) {
  8628. this._onRejected(reason);
  8629. this._rejectWasConsumed = true;
  8630. }
  8631. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8632. var child = _a[_i];
  8633. if (this._rejectWasConsumed) {
  8634. child._resolve(null);
  8635. }
  8636. else {
  8637. child._reject(reason);
  8638. }
  8639. }
  8640. };
  8641. InternalPromise.resolve = function (value) {
  8642. var newPromise = new InternalPromise();
  8643. newPromise._resolve(value);
  8644. return newPromise;
  8645. };
  8646. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  8647. promise.then(function (value) {
  8648. agregator.results[index] = value;
  8649. agregator.count++;
  8650. if (agregator.count === agregator.target) {
  8651. agregator.rootPromise._resolve(agregator.results);
  8652. }
  8653. return null;
  8654. }, function (reason) {
  8655. if (!agregator.rootPromise.isRejected) {
  8656. agregator.rootPromise._reject(reason);
  8657. }
  8658. });
  8659. };
  8660. InternalPromise.all = function (promises) {
  8661. var newPromise = new InternalPromise();
  8662. var agregator = new FulFillmentAgregator();
  8663. agregator.target = promises.length;
  8664. agregator.rootPromise = newPromise;
  8665. for (var index = 0; index < promises.length; index++) {
  8666. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  8667. }
  8668. return newPromise;
  8669. };
  8670. return InternalPromise;
  8671. }());
  8672. /**
  8673. * Helper class that provides a small promise polyfill
  8674. */
  8675. var PromisePolyfill = /** @class */ (function () {
  8676. function PromisePolyfill() {
  8677. }
  8678. /**
  8679. * Static function used to check if the polyfill is required
  8680. * If this is the case then the function will inject the polyfill to window.Promise
  8681. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  8682. */
  8683. PromisePolyfill.Apply = function (force) {
  8684. if (force === void 0) { force = false; }
  8685. if (force || typeof Promise === 'undefined') {
  8686. var root = window;
  8687. root.Promise = InternalPromise;
  8688. }
  8689. };
  8690. return PromisePolyfill;
  8691. }());
  8692. BABYLON.PromisePolyfill = PromisePolyfill;
  8693. })(BABYLON || (BABYLON = {}));
  8694. //# sourceMappingURL=babylon.promise.js.map
  8695. var BABYLON;
  8696. (function (BABYLON) {
  8697. var _AlphaState = /** @class */ (function () {
  8698. /**
  8699. * Initializes the state.
  8700. */
  8701. function _AlphaState() {
  8702. this._isAlphaBlendDirty = false;
  8703. this._isBlendFunctionParametersDirty = false;
  8704. this._isBlendEquationParametersDirty = false;
  8705. this._isBlendConstantsDirty = false;
  8706. this._alphaBlend = false;
  8707. this._blendFunctionParameters = new Array(4);
  8708. this._blendEquationParameters = new Array(2);
  8709. this._blendConstants = new Array(4);
  8710. this.reset();
  8711. }
  8712. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8713. get: function () {
  8714. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8715. },
  8716. enumerable: true,
  8717. configurable: true
  8718. });
  8719. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8720. get: function () {
  8721. return this._alphaBlend;
  8722. },
  8723. set: function (value) {
  8724. if (this._alphaBlend === value) {
  8725. return;
  8726. }
  8727. this._alphaBlend = value;
  8728. this._isAlphaBlendDirty = true;
  8729. },
  8730. enumerable: true,
  8731. configurable: true
  8732. });
  8733. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8734. if (this._blendConstants[0] === r &&
  8735. this._blendConstants[1] === g &&
  8736. this._blendConstants[2] === b &&
  8737. this._blendConstants[3] === a) {
  8738. return;
  8739. }
  8740. this._blendConstants[0] = r;
  8741. this._blendConstants[1] = g;
  8742. this._blendConstants[2] = b;
  8743. this._blendConstants[3] = a;
  8744. this._isBlendConstantsDirty = true;
  8745. };
  8746. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8747. if (this._blendFunctionParameters[0] === value0 &&
  8748. this._blendFunctionParameters[1] === value1 &&
  8749. this._blendFunctionParameters[2] === value2 &&
  8750. this._blendFunctionParameters[3] === value3) {
  8751. return;
  8752. }
  8753. this._blendFunctionParameters[0] = value0;
  8754. this._blendFunctionParameters[1] = value1;
  8755. this._blendFunctionParameters[2] = value2;
  8756. this._blendFunctionParameters[3] = value3;
  8757. this._isBlendFunctionParametersDirty = true;
  8758. };
  8759. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8760. if (this._blendEquationParameters[0] === rgb &&
  8761. this._blendEquationParameters[1] === alpha) {
  8762. return;
  8763. }
  8764. this._blendEquationParameters[0] = rgb;
  8765. this._blendEquationParameters[1] = alpha;
  8766. this._isBlendEquationParametersDirty = true;
  8767. };
  8768. _AlphaState.prototype.reset = function () {
  8769. this._alphaBlend = false;
  8770. this._blendFunctionParameters[0] = null;
  8771. this._blendFunctionParameters[1] = null;
  8772. this._blendFunctionParameters[2] = null;
  8773. this._blendFunctionParameters[3] = null;
  8774. this._blendEquationParameters[0] = null;
  8775. this._blendEquationParameters[1] = null;
  8776. this._blendConstants[0] = null;
  8777. this._blendConstants[1] = null;
  8778. this._blendConstants[2] = null;
  8779. this._blendConstants[3] = null;
  8780. this._isAlphaBlendDirty = true;
  8781. this._isBlendFunctionParametersDirty = false;
  8782. this._isBlendEquationParametersDirty = false;
  8783. this._isBlendConstantsDirty = false;
  8784. };
  8785. _AlphaState.prototype.apply = function (gl) {
  8786. if (!this.isDirty) {
  8787. return;
  8788. }
  8789. // Alpha blend
  8790. if (this._isAlphaBlendDirty) {
  8791. if (this._alphaBlend) {
  8792. gl.enable(gl.BLEND);
  8793. }
  8794. else {
  8795. gl.disable(gl.BLEND);
  8796. }
  8797. this._isAlphaBlendDirty = false;
  8798. }
  8799. // Alpha function
  8800. if (this._isBlendFunctionParametersDirty) {
  8801. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8802. this._isBlendFunctionParametersDirty = false;
  8803. }
  8804. // Alpha equation
  8805. if (this._isBlendEquationParametersDirty) {
  8806. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8807. this._isBlendEquationParametersDirty = false;
  8808. }
  8809. // Constants
  8810. if (this._isBlendConstantsDirty) {
  8811. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8812. this._isBlendConstantsDirty = false;
  8813. }
  8814. };
  8815. return _AlphaState;
  8816. }());
  8817. BABYLON._AlphaState = _AlphaState;
  8818. })(BABYLON || (BABYLON = {}));
  8819. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8820. var BABYLON;
  8821. (function (BABYLON) {
  8822. var _DepthCullingState = /** @class */ (function () {
  8823. /**
  8824. * Initializes the state.
  8825. */
  8826. function _DepthCullingState() {
  8827. this._isDepthTestDirty = false;
  8828. this._isDepthMaskDirty = false;
  8829. this._isDepthFuncDirty = false;
  8830. this._isCullFaceDirty = false;
  8831. this._isCullDirty = false;
  8832. this._isZOffsetDirty = false;
  8833. this._isFrontFaceDirty = false;
  8834. this.reset();
  8835. }
  8836. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8837. get: function () {
  8838. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8839. },
  8840. enumerable: true,
  8841. configurable: true
  8842. });
  8843. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8844. get: function () {
  8845. return this._zOffset;
  8846. },
  8847. set: function (value) {
  8848. if (this._zOffset === value) {
  8849. return;
  8850. }
  8851. this._zOffset = value;
  8852. this._isZOffsetDirty = true;
  8853. },
  8854. enumerable: true,
  8855. configurable: true
  8856. });
  8857. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8858. get: function () {
  8859. return this._cullFace;
  8860. },
  8861. set: function (value) {
  8862. if (this._cullFace === value) {
  8863. return;
  8864. }
  8865. this._cullFace = value;
  8866. this._isCullFaceDirty = true;
  8867. },
  8868. enumerable: true,
  8869. configurable: true
  8870. });
  8871. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8872. get: function () {
  8873. return this._cull;
  8874. },
  8875. set: function (value) {
  8876. if (this._cull === value) {
  8877. return;
  8878. }
  8879. this._cull = value;
  8880. this._isCullDirty = true;
  8881. },
  8882. enumerable: true,
  8883. configurable: true
  8884. });
  8885. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8886. get: function () {
  8887. return this._depthFunc;
  8888. },
  8889. set: function (value) {
  8890. if (this._depthFunc === value) {
  8891. return;
  8892. }
  8893. this._depthFunc = value;
  8894. this._isDepthFuncDirty = true;
  8895. },
  8896. enumerable: true,
  8897. configurable: true
  8898. });
  8899. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8900. get: function () {
  8901. return this._depthMask;
  8902. },
  8903. set: function (value) {
  8904. if (this._depthMask === value) {
  8905. return;
  8906. }
  8907. this._depthMask = value;
  8908. this._isDepthMaskDirty = true;
  8909. },
  8910. enumerable: true,
  8911. configurable: true
  8912. });
  8913. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8914. get: function () {
  8915. return this._depthTest;
  8916. },
  8917. set: function (value) {
  8918. if (this._depthTest === value) {
  8919. return;
  8920. }
  8921. this._depthTest = value;
  8922. this._isDepthTestDirty = true;
  8923. },
  8924. enumerable: true,
  8925. configurable: true
  8926. });
  8927. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8928. get: function () {
  8929. return this._frontFace;
  8930. },
  8931. set: function (value) {
  8932. if (this._frontFace === value) {
  8933. return;
  8934. }
  8935. this._frontFace = value;
  8936. this._isFrontFaceDirty = true;
  8937. },
  8938. enumerable: true,
  8939. configurable: true
  8940. });
  8941. _DepthCullingState.prototype.reset = function () {
  8942. this._depthMask = true;
  8943. this._depthTest = true;
  8944. this._depthFunc = null;
  8945. this._cullFace = null;
  8946. this._cull = null;
  8947. this._zOffset = 0;
  8948. this._frontFace = null;
  8949. this._isDepthTestDirty = true;
  8950. this._isDepthMaskDirty = true;
  8951. this._isDepthFuncDirty = false;
  8952. this._isCullFaceDirty = false;
  8953. this._isCullDirty = false;
  8954. this._isZOffsetDirty = false;
  8955. this._isFrontFaceDirty = false;
  8956. };
  8957. _DepthCullingState.prototype.apply = function (gl) {
  8958. if (!this.isDirty) {
  8959. return;
  8960. }
  8961. // Cull
  8962. if (this._isCullDirty) {
  8963. if (this.cull) {
  8964. gl.enable(gl.CULL_FACE);
  8965. }
  8966. else {
  8967. gl.disable(gl.CULL_FACE);
  8968. }
  8969. this._isCullDirty = false;
  8970. }
  8971. // Cull face
  8972. if (this._isCullFaceDirty) {
  8973. gl.cullFace(this.cullFace);
  8974. this._isCullFaceDirty = false;
  8975. }
  8976. // Depth mask
  8977. if (this._isDepthMaskDirty) {
  8978. gl.depthMask(this.depthMask);
  8979. this._isDepthMaskDirty = false;
  8980. }
  8981. // Depth test
  8982. if (this._isDepthTestDirty) {
  8983. if (this.depthTest) {
  8984. gl.enable(gl.DEPTH_TEST);
  8985. }
  8986. else {
  8987. gl.disable(gl.DEPTH_TEST);
  8988. }
  8989. this._isDepthTestDirty = false;
  8990. }
  8991. // Depth func
  8992. if (this._isDepthFuncDirty) {
  8993. gl.depthFunc(this.depthFunc);
  8994. this._isDepthFuncDirty = false;
  8995. }
  8996. // zOffset
  8997. if (this._isZOffsetDirty) {
  8998. if (this.zOffset) {
  8999. gl.enable(gl.POLYGON_OFFSET_FILL);
  9000. gl.polygonOffset(this.zOffset, 0);
  9001. }
  9002. else {
  9003. gl.disable(gl.POLYGON_OFFSET_FILL);
  9004. }
  9005. this._isZOffsetDirty = false;
  9006. }
  9007. // Front face
  9008. if (this._isFrontFaceDirty) {
  9009. gl.frontFace(this.frontFace);
  9010. this._isFrontFaceDirty = false;
  9011. }
  9012. };
  9013. return _DepthCullingState;
  9014. }());
  9015. BABYLON._DepthCullingState = _DepthCullingState;
  9016. })(BABYLON || (BABYLON = {}));
  9017. //# sourceMappingURL=babylon.depthCullingState.js.map
  9018. var BABYLON;
  9019. (function (BABYLON) {
  9020. var _StencilState = /** @class */ (function () {
  9021. function _StencilState() {
  9022. this._isStencilTestDirty = false;
  9023. this._isStencilMaskDirty = false;
  9024. this._isStencilFuncDirty = false;
  9025. this._isStencilOpDirty = false;
  9026. this.reset();
  9027. }
  9028. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9029. get: function () {
  9030. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9031. },
  9032. enumerable: true,
  9033. configurable: true
  9034. });
  9035. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9036. get: function () {
  9037. return this._stencilFunc;
  9038. },
  9039. set: function (value) {
  9040. if (this._stencilFunc === value) {
  9041. return;
  9042. }
  9043. this._stencilFunc = value;
  9044. this._isStencilFuncDirty = true;
  9045. },
  9046. enumerable: true,
  9047. configurable: true
  9048. });
  9049. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9050. get: function () {
  9051. return this._stencilFuncRef;
  9052. },
  9053. set: function (value) {
  9054. if (this._stencilFuncRef === value) {
  9055. return;
  9056. }
  9057. this._stencilFuncRef = value;
  9058. this._isStencilFuncDirty = true;
  9059. },
  9060. enumerable: true,
  9061. configurable: true
  9062. });
  9063. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9064. get: function () {
  9065. return this._stencilFuncMask;
  9066. },
  9067. set: function (value) {
  9068. if (this._stencilFuncMask === value) {
  9069. return;
  9070. }
  9071. this._stencilFuncMask = value;
  9072. this._isStencilFuncDirty = true;
  9073. },
  9074. enumerable: true,
  9075. configurable: true
  9076. });
  9077. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9078. get: function () {
  9079. return this._stencilOpStencilFail;
  9080. },
  9081. set: function (value) {
  9082. if (this._stencilOpStencilFail === value) {
  9083. return;
  9084. }
  9085. this._stencilOpStencilFail = value;
  9086. this._isStencilOpDirty = true;
  9087. },
  9088. enumerable: true,
  9089. configurable: true
  9090. });
  9091. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9092. get: function () {
  9093. return this._stencilOpDepthFail;
  9094. },
  9095. set: function (value) {
  9096. if (this._stencilOpDepthFail === value) {
  9097. return;
  9098. }
  9099. this._stencilOpDepthFail = value;
  9100. this._isStencilOpDirty = true;
  9101. },
  9102. enumerable: true,
  9103. configurable: true
  9104. });
  9105. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9106. get: function () {
  9107. return this._stencilOpStencilDepthPass;
  9108. },
  9109. set: function (value) {
  9110. if (this._stencilOpStencilDepthPass === value) {
  9111. return;
  9112. }
  9113. this._stencilOpStencilDepthPass = value;
  9114. this._isStencilOpDirty = true;
  9115. },
  9116. enumerable: true,
  9117. configurable: true
  9118. });
  9119. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9120. get: function () {
  9121. return this._stencilMask;
  9122. },
  9123. set: function (value) {
  9124. if (this._stencilMask === value) {
  9125. return;
  9126. }
  9127. this._stencilMask = value;
  9128. this._isStencilMaskDirty = true;
  9129. },
  9130. enumerable: true,
  9131. configurable: true
  9132. });
  9133. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9134. get: function () {
  9135. return this._stencilTest;
  9136. },
  9137. set: function (value) {
  9138. if (this._stencilTest === value) {
  9139. return;
  9140. }
  9141. this._stencilTest = value;
  9142. this._isStencilTestDirty = true;
  9143. },
  9144. enumerable: true,
  9145. configurable: true
  9146. });
  9147. _StencilState.prototype.reset = function () {
  9148. this._stencilTest = false;
  9149. this._stencilMask = 0xFF;
  9150. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9151. this._stencilFuncRef = 1;
  9152. this._stencilFuncMask = 0xFF;
  9153. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9154. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9155. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9156. this._isStencilTestDirty = true;
  9157. this._isStencilMaskDirty = true;
  9158. this._isStencilFuncDirty = true;
  9159. this._isStencilOpDirty = true;
  9160. };
  9161. _StencilState.prototype.apply = function (gl) {
  9162. if (!this.isDirty) {
  9163. return;
  9164. }
  9165. // Stencil test
  9166. if (this._isStencilTestDirty) {
  9167. if (this.stencilTest) {
  9168. gl.enable(gl.STENCIL_TEST);
  9169. }
  9170. else {
  9171. gl.disable(gl.STENCIL_TEST);
  9172. }
  9173. this._isStencilTestDirty = false;
  9174. }
  9175. // Stencil mask
  9176. if (this._isStencilMaskDirty) {
  9177. gl.stencilMask(this.stencilMask);
  9178. this._isStencilMaskDirty = false;
  9179. }
  9180. // Stencil func
  9181. if (this._isStencilFuncDirty) {
  9182. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9183. this._isStencilFuncDirty = false;
  9184. }
  9185. // Stencil op
  9186. if (this._isStencilOpDirty) {
  9187. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9188. this._isStencilOpDirty = false;
  9189. }
  9190. };
  9191. return _StencilState;
  9192. }());
  9193. BABYLON._StencilState = _StencilState;
  9194. })(BABYLON || (BABYLON = {}));
  9195. //# sourceMappingURL=babylon.stencilState.js.map
  9196. var BABYLON;
  9197. (function (BABYLON) {
  9198. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9199. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9200. };
  9201. var compileRawShader = function (gl, source, type) {
  9202. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9203. gl.shaderSource(shader, source);
  9204. gl.compileShader(shader);
  9205. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9206. var log = gl.getShaderInfoLog(shader);
  9207. if (log) {
  9208. throw new Error(log);
  9209. }
  9210. }
  9211. if (!shader) {
  9212. throw new Error("Something went wrong while compile the shader.");
  9213. }
  9214. return shader;
  9215. };
  9216. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9217. var magFilter = gl.NEAREST;
  9218. var minFilter = gl.NEAREST;
  9219. switch (samplingMode) {
  9220. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9221. magFilter = gl.LINEAR;
  9222. if (generateMipMaps) {
  9223. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9224. }
  9225. else {
  9226. minFilter = gl.LINEAR;
  9227. }
  9228. break;
  9229. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  9230. magFilter = gl.LINEAR;
  9231. if (generateMipMaps) {
  9232. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9233. }
  9234. else {
  9235. minFilter = gl.LINEAR;
  9236. }
  9237. break;
  9238. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  9239. magFilter = gl.NEAREST;
  9240. if (generateMipMaps) {
  9241. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9242. }
  9243. else {
  9244. minFilter = gl.NEAREST;
  9245. }
  9246. break;
  9247. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  9248. magFilter = gl.NEAREST;
  9249. if (generateMipMaps) {
  9250. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9251. }
  9252. else {
  9253. minFilter = gl.NEAREST;
  9254. }
  9255. break;
  9256. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  9257. magFilter = gl.NEAREST;
  9258. if (generateMipMaps) {
  9259. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9260. }
  9261. else {
  9262. minFilter = gl.LINEAR;
  9263. }
  9264. break;
  9265. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  9266. magFilter = gl.NEAREST;
  9267. if (generateMipMaps) {
  9268. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9269. }
  9270. else {
  9271. minFilter = gl.LINEAR;
  9272. }
  9273. break;
  9274. case BABYLON.Texture.NEAREST_LINEAR:
  9275. magFilter = gl.NEAREST;
  9276. minFilter = gl.LINEAR;
  9277. break;
  9278. case BABYLON.Texture.NEAREST_NEAREST:
  9279. magFilter = gl.NEAREST;
  9280. minFilter = gl.NEAREST;
  9281. break;
  9282. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  9283. magFilter = gl.LINEAR;
  9284. if (generateMipMaps) {
  9285. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9286. }
  9287. else {
  9288. minFilter = gl.NEAREST;
  9289. }
  9290. break;
  9291. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  9292. magFilter = gl.LINEAR;
  9293. if (generateMipMaps) {
  9294. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9295. }
  9296. else {
  9297. minFilter = gl.NEAREST;
  9298. }
  9299. break;
  9300. case BABYLON.Texture.LINEAR_LINEAR:
  9301. magFilter = gl.LINEAR;
  9302. minFilter = gl.LINEAR;
  9303. break;
  9304. case BABYLON.Texture.LINEAR_NEAREST:
  9305. magFilter = gl.LINEAR;
  9306. minFilter = gl.NEAREST;
  9307. break;
  9308. }
  9309. return {
  9310. min: minFilter,
  9311. mag: magFilter
  9312. };
  9313. };
  9314. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  9315. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  9316. var img;
  9317. var onload = function () {
  9318. loadedImages[index] = img;
  9319. loadedImages._internalCount++;
  9320. if (scene) {
  9321. scene._removePendingData(img);
  9322. }
  9323. if (loadedImages._internalCount === 6) {
  9324. onfinish(loadedImages);
  9325. }
  9326. };
  9327. var onerror = function (message, exception) {
  9328. if (scene) {
  9329. scene._removePendingData(img);
  9330. }
  9331. if (onErrorCallBack) {
  9332. onErrorCallBack(message, exception);
  9333. }
  9334. };
  9335. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9336. if (scene) {
  9337. scene._addPendingData(img);
  9338. }
  9339. };
  9340. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  9341. if (onError === void 0) { onError = null; }
  9342. var loadedImages = [];
  9343. loadedImages._internalCount = 0;
  9344. for (var index = 0; index < 6; index++) {
  9345. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  9346. }
  9347. };
  9348. var BufferPointer = /** @class */ (function () {
  9349. function BufferPointer() {
  9350. }
  9351. return BufferPointer;
  9352. }());
  9353. var InstancingAttributeInfo = /** @class */ (function () {
  9354. function InstancingAttributeInfo() {
  9355. }
  9356. return InstancingAttributeInfo;
  9357. }());
  9358. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  9359. /**
  9360. * Define options used to create a render target texture
  9361. */
  9362. var RenderTargetCreationOptions = /** @class */ (function () {
  9363. function RenderTargetCreationOptions() {
  9364. }
  9365. return RenderTargetCreationOptions;
  9366. }());
  9367. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  9368. /**
  9369. * Regroup several parameters relative to the browser in use
  9370. */
  9371. var EngineCapabilities = /** @class */ (function () {
  9372. function EngineCapabilities() {
  9373. }
  9374. return EngineCapabilities;
  9375. }());
  9376. BABYLON.EngineCapabilities = EngineCapabilities;
  9377. /**
  9378. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  9379. */
  9380. var Engine = /** @class */ (function () {
  9381. /**
  9382. * @constructor
  9383. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  9384. * @param antialias defines enable antialiasing (default: false)
  9385. * @param options defines further options to be sent to the getContext() function
  9386. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  9387. */
  9388. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  9389. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  9390. var _this = this;
  9391. // Public members
  9392. this.forcePOTTextures = false;
  9393. this.isFullscreen = false;
  9394. this.isPointerLock = false;
  9395. this.cullBackFaces = true;
  9396. this.renderEvenInBackground = true;
  9397. this.preventCacheWipeBetweenFrames = false;
  9398. // To enable/disable IDB support and avoid XHR on .manifest
  9399. this.enableOfflineSupport = false;
  9400. this.scenes = new Array();
  9401. this.postProcesses = new Array();
  9402. // Observables
  9403. /**
  9404. * Observable event triggered each time the rendering canvas is resized
  9405. */
  9406. this.onResizeObservable = new BABYLON.Observable();
  9407. /**
  9408. * Observable event triggered each time the canvas loses focus
  9409. */
  9410. this.onCanvasBlurObservable = new BABYLON.Observable();
  9411. /**
  9412. * Observable event triggered each time the canvas gains focus
  9413. */
  9414. this.onCanvasFocusObservable = new BABYLON.Observable();
  9415. /**
  9416. * Observable event triggered each time the canvas receives pointerout event
  9417. */
  9418. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  9419. /**
  9420. * Observable event triggered before each texture is initialized
  9421. */
  9422. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  9423. //WebVR
  9424. this._vrDisplay = undefined;
  9425. this._vrSupported = false;
  9426. this._vrExclusivePointerMode = false;
  9427. // Uniform buffers list
  9428. this.disableUniformBuffers = false;
  9429. this._uniformBuffers = new Array();
  9430. // Observables
  9431. /**
  9432. * Observable raised when the engine begins a new frame
  9433. */
  9434. this.onBeginFrameObservable = new BABYLON.Observable();
  9435. /**
  9436. * Observable raised when the engine ends the current frame
  9437. */
  9438. this.onEndFrameObservable = new BABYLON.Observable();
  9439. /**
  9440. * Observable raised when the engine is about to compile a shader
  9441. */
  9442. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  9443. /**
  9444. * Observable raised when the engine has jsut compiled a shader
  9445. */
  9446. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  9447. this._windowIsBackground = false;
  9448. this._webGLVersion = 1.0;
  9449. this._badOS = false;
  9450. this._badDesktopOS = false;
  9451. /**
  9452. * Gets or sets a value indicating if we want to disable texture binding optmization.
  9453. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  9454. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  9455. */
  9456. this.disableTextureBindingOptimization = false;
  9457. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  9458. this.onVRRequestPresentComplete = new BABYLON.Observable();
  9459. this.onVRRequestPresentStart = new BABYLON.Observable();
  9460. this._colorWrite = true;
  9461. this._drawCalls = new BABYLON.PerfCounter();
  9462. this._textureCollisions = new BABYLON.PerfCounter();
  9463. this._renderingQueueLaunched = false;
  9464. this._activeRenderLoops = new Array();
  9465. // Deterministic lockstepMaxSteps
  9466. this._deterministicLockstep = false;
  9467. this._lockstepMaxSteps = 4;
  9468. // Lost context
  9469. this.onContextLostObservable = new BABYLON.Observable();
  9470. this.onContextRestoredObservable = new BABYLON.Observable();
  9471. this._contextWasLost = false;
  9472. this._doNotHandleContextLost = false;
  9473. // FPS
  9474. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9475. this._fps = 60;
  9476. this._deltaTime = 0;
  9477. /**
  9478. * Turn this value on if you want to pause FPS computation when in background
  9479. */
  9480. this.disablePerformanceMonitorInBackground = false;
  9481. // States
  9482. this._depthCullingState = new BABYLON._DepthCullingState();
  9483. this._stencilState = new BABYLON._StencilState();
  9484. this._alphaState = new BABYLON._AlphaState();
  9485. this._alphaMode = Engine.ALPHA_DISABLE;
  9486. // Cache
  9487. this._internalTexturesCache = new Array();
  9488. this._activeChannel = 0;
  9489. this._currentTextureChannel = -1;
  9490. this._boundTexturesCache = {};
  9491. this._compiledEffects = {};
  9492. this._vertexAttribArraysEnabled = [];
  9493. this._uintIndicesCurrentlySet = false;
  9494. this._currentBoundBuffer = new Array();
  9495. this._currentBufferPointers = new Array();
  9496. this._currentInstanceLocations = new Array();
  9497. this._currentInstanceBuffers = new Array();
  9498. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9499. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9500. this._vaoRecordInProgress = false;
  9501. this._mustWipeVertexAttributes = false;
  9502. this._nextFreeTextureSlots = new Array();
  9503. this._maxSimultaneousTextures = 0;
  9504. this._activeRequests = new Array();
  9505. // Hardware supported Compressed Textures
  9506. this._texturesSupported = new Array();
  9507. this._onVRFullScreenTriggered = function () {
  9508. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9509. //get the old size before we change
  9510. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9511. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9512. //get the width and height, change the render size
  9513. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9514. _this.setHardwareScalingLevel(1);
  9515. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9516. }
  9517. else {
  9518. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9519. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9520. }
  9521. };
  9522. this._boundUniforms = {};
  9523. // Register promises
  9524. BABYLON.PromisePolyfill.Apply();
  9525. var canvas = null;
  9526. Engine.Instances.push(this);
  9527. if (!canvasOrContext) {
  9528. return;
  9529. }
  9530. options = options || {};
  9531. if (canvasOrContext.getContext) {
  9532. canvas = canvasOrContext;
  9533. this._renderingCanvas = canvas;
  9534. if (antialias != null) {
  9535. options.antialias = antialias;
  9536. }
  9537. if (options.deterministicLockstep === undefined) {
  9538. options.deterministicLockstep = false;
  9539. }
  9540. if (options.lockstepMaxSteps === undefined) {
  9541. options.lockstepMaxSteps = 4;
  9542. }
  9543. if (options.preserveDrawingBuffer === undefined) {
  9544. options.preserveDrawingBuffer = false;
  9545. }
  9546. if (options.audioEngine === undefined) {
  9547. options.audioEngine = true;
  9548. }
  9549. if (options.stencil === undefined) {
  9550. options.stencil = true;
  9551. }
  9552. this._deterministicLockstep = options.deterministicLockstep;
  9553. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9554. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9555. // Exceptions
  9556. if (navigator && navigator.userAgent) {
  9557. var ua = navigator.userAgent;
  9558. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9559. var exception = _a[_i];
  9560. var key = exception.key;
  9561. var targets = exception.targets;
  9562. if (ua.indexOf(key) > -1) {
  9563. if (exception.capture && exception.captureConstraint) {
  9564. var capture = exception.capture;
  9565. var constraint = exception.captureConstraint;
  9566. var regex = new RegExp(capture);
  9567. var matches = regex.exec(ua);
  9568. if (matches && matches.length > 0) {
  9569. var capturedValue = parseInt(matches[matches.length - 1]);
  9570. if (capturedValue >= constraint) {
  9571. continue;
  9572. }
  9573. }
  9574. }
  9575. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9576. var target = targets_1[_b];
  9577. switch (target) {
  9578. case "uniformBuffer":
  9579. this.disableUniformBuffers = true;
  9580. break;
  9581. case "textureBindingOptimization":
  9582. this.disableTextureBindingOptimization = true;
  9583. break;
  9584. }
  9585. }
  9586. break;
  9587. }
  9588. }
  9589. }
  9590. // GL
  9591. if (!options.disableWebGL2Support) {
  9592. try {
  9593. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9594. if (this._gl) {
  9595. this._webGLVersion = 2.0;
  9596. }
  9597. }
  9598. catch (e) {
  9599. // Do nothing
  9600. }
  9601. }
  9602. if (!this._gl) {
  9603. if (!canvas) {
  9604. throw new Error("The provided canvas is null or undefined.");
  9605. }
  9606. try {
  9607. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9608. }
  9609. catch (e) {
  9610. throw new Error("WebGL not supported");
  9611. }
  9612. }
  9613. if (!this._gl) {
  9614. throw new Error("WebGL not supported");
  9615. }
  9616. this._onCanvasFocus = function () {
  9617. _this.onCanvasFocusObservable.notifyObservers(_this);
  9618. };
  9619. this._onCanvasBlur = function () {
  9620. _this.onCanvasBlurObservable.notifyObservers(_this);
  9621. };
  9622. canvas.addEventListener("focus", this._onCanvasFocus);
  9623. canvas.addEventListener("blur", this._onCanvasBlur);
  9624. this._onBlur = function () {
  9625. if (_this.disablePerformanceMonitorInBackground) {
  9626. _this._performanceMonitor.disable();
  9627. }
  9628. _this._windowIsBackground = true;
  9629. };
  9630. this._onFocus = function () {
  9631. if (_this.disablePerformanceMonitorInBackground) {
  9632. _this._performanceMonitor.enable();
  9633. }
  9634. _this._windowIsBackground = false;
  9635. };
  9636. this._onCanvasPointerOut = function () {
  9637. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9638. };
  9639. window.addEventListener("blur", this._onBlur);
  9640. window.addEventListener("focus", this._onFocus);
  9641. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9642. // Context lost
  9643. if (!this._doNotHandleContextLost) {
  9644. this._onContextLost = function (evt) {
  9645. evt.preventDefault();
  9646. _this._contextWasLost = true;
  9647. BABYLON.Tools.Warn("WebGL context lost.");
  9648. _this.onContextLostObservable.notifyObservers(_this);
  9649. };
  9650. this._onContextRestored = function (evt) {
  9651. // Adding a timeout to avoid race condition at browser level
  9652. setTimeout(function () {
  9653. // Rebuild gl context
  9654. _this._initGLContext();
  9655. // Rebuild effects
  9656. _this._rebuildEffects();
  9657. // Rebuild textures
  9658. _this._rebuildInternalTextures();
  9659. // Rebuild buffers
  9660. _this._rebuildBuffers();
  9661. // Cache
  9662. _this.wipeCaches(true);
  9663. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9664. _this.onContextRestoredObservable.notifyObservers(_this);
  9665. _this._contextWasLost = false;
  9666. }, 0);
  9667. };
  9668. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9669. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9670. }
  9671. }
  9672. else {
  9673. this._gl = canvasOrContext;
  9674. this._renderingCanvas = this._gl.canvas;
  9675. if (this._gl.renderbufferStorageMultisample) {
  9676. this._webGLVersion = 2.0;
  9677. }
  9678. options.stencil = this._gl.getContextAttributes().stencil;
  9679. }
  9680. // Viewport
  9681. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9682. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9683. this.resize();
  9684. this._isStencilEnable = options.stencil ? true : false;
  9685. this._initGLContext();
  9686. if (canvas) {
  9687. // Fullscreen
  9688. this._onFullscreenChange = function () {
  9689. if (document.fullscreen !== undefined) {
  9690. _this.isFullscreen = document.fullscreen;
  9691. }
  9692. else if (document.mozFullScreen !== undefined) {
  9693. _this.isFullscreen = document.mozFullScreen;
  9694. }
  9695. else if (document.webkitIsFullScreen !== undefined) {
  9696. _this.isFullscreen = document.webkitIsFullScreen;
  9697. }
  9698. else if (document.msIsFullScreen !== undefined) {
  9699. _this.isFullscreen = document.msIsFullScreen;
  9700. }
  9701. // Pointer lock
  9702. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9703. canvas.requestPointerLock = canvas.requestPointerLock ||
  9704. canvas.msRequestPointerLock ||
  9705. canvas.mozRequestPointerLock ||
  9706. canvas.webkitRequestPointerLock;
  9707. if (canvas.requestPointerLock) {
  9708. canvas.requestPointerLock();
  9709. }
  9710. }
  9711. };
  9712. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9713. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9714. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9715. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9716. // Pointer lock
  9717. this._onPointerLockChange = function () {
  9718. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9719. document.webkitPointerLockElement === canvas ||
  9720. document.msPointerLockElement === canvas ||
  9721. document.pointerLockElement === canvas);
  9722. };
  9723. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9724. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9725. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9726. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9727. this._onVRDisplayPointerRestricted = function () {
  9728. if (canvas) {
  9729. canvas.requestPointerLock();
  9730. }
  9731. };
  9732. this._onVRDisplayPointerUnrestricted = function () {
  9733. document.exitPointerLock();
  9734. };
  9735. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9736. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9737. }
  9738. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9739. Engine.audioEngine = new BABYLON.AudioEngine();
  9740. }
  9741. // Prepare buffer pointers
  9742. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9743. this._currentBufferPointers[i] = new BufferPointer();
  9744. }
  9745. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9746. // Load WebVR Devices
  9747. if (options.autoEnableWebVR) {
  9748. this.initWebVR();
  9749. }
  9750. // Detect if we are running on a faulty buggy OS.
  9751. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9752. // Detect if we are running on a faulty buggy desktop OS.
  9753. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9754. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9755. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9756. }
  9757. Object.defineProperty(Engine, "LastCreatedEngine", {
  9758. get: function () {
  9759. if (Engine.Instances.length === 0) {
  9760. return null;
  9761. }
  9762. return Engine.Instances[Engine.Instances.length - 1];
  9763. },
  9764. enumerable: true,
  9765. configurable: true
  9766. });
  9767. Object.defineProperty(Engine, "LastCreatedScene", {
  9768. get: function () {
  9769. var lastCreatedEngine = Engine.LastCreatedEngine;
  9770. if (!lastCreatedEngine) {
  9771. return null;
  9772. }
  9773. if (lastCreatedEngine.scenes.length === 0) {
  9774. return null;
  9775. }
  9776. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9777. },
  9778. enumerable: true,
  9779. configurable: true
  9780. });
  9781. /**
  9782. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9783. */
  9784. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9785. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9786. var engine = Engine.Instances[engineIndex];
  9787. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9788. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9789. }
  9790. }
  9791. };
  9792. Object.defineProperty(Engine, "NEVER", {
  9793. get: function () {
  9794. return Engine._NEVER;
  9795. },
  9796. enumerable: true,
  9797. configurable: true
  9798. });
  9799. Object.defineProperty(Engine, "ALWAYS", {
  9800. get: function () {
  9801. return Engine._ALWAYS;
  9802. },
  9803. enumerable: true,
  9804. configurable: true
  9805. });
  9806. Object.defineProperty(Engine, "LESS", {
  9807. get: function () {
  9808. return Engine._LESS;
  9809. },
  9810. enumerable: true,
  9811. configurable: true
  9812. });
  9813. Object.defineProperty(Engine, "EQUAL", {
  9814. get: function () {
  9815. return Engine._EQUAL;
  9816. },
  9817. enumerable: true,
  9818. configurable: true
  9819. });
  9820. Object.defineProperty(Engine, "LEQUAL", {
  9821. get: function () {
  9822. return Engine._LEQUAL;
  9823. },
  9824. enumerable: true,
  9825. configurable: true
  9826. });
  9827. Object.defineProperty(Engine, "GREATER", {
  9828. get: function () {
  9829. return Engine._GREATER;
  9830. },
  9831. enumerable: true,
  9832. configurable: true
  9833. });
  9834. Object.defineProperty(Engine, "GEQUAL", {
  9835. get: function () {
  9836. return Engine._GEQUAL;
  9837. },
  9838. enumerable: true,
  9839. configurable: true
  9840. });
  9841. Object.defineProperty(Engine, "NOTEQUAL", {
  9842. get: function () {
  9843. return Engine._NOTEQUAL;
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. Object.defineProperty(Engine, "KEEP", {
  9849. get: function () {
  9850. return Engine._KEEP;
  9851. },
  9852. enumerable: true,
  9853. configurable: true
  9854. });
  9855. Object.defineProperty(Engine, "REPLACE", {
  9856. get: function () {
  9857. return Engine._REPLACE;
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. Object.defineProperty(Engine, "INCR", {
  9863. get: function () {
  9864. return Engine._INCR;
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. Object.defineProperty(Engine, "DECR", {
  9870. get: function () {
  9871. return Engine._DECR;
  9872. },
  9873. enumerable: true,
  9874. configurable: true
  9875. });
  9876. Object.defineProperty(Engine, "INVERT", {
  9877. get: function () {
  9878. return Engine._INVERT;
  9879. },
  9880. enumerable: true,
  9881. configurable: true
  9882. });
  9883. Object.defineProperty(Engine, "INCR_WRAP", {
  9884. get: function () {
  9885. return Engine._INCR_WRAP;
  9886. },
  9887. enumerable: true,
  9888. configurable: true
  9889. });
  9890. Object.defineProperty(Engine, "DECR_WRAP", {
  9891. get: function () {
  9892. return Engine._DECR_WRAP;
  9893. },
  9894. enumerable: true,
  9895. configurable: true
  9896. });
  9897. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9898. get: function () {
  9899. return Engine._ALPHA_DISABLE;
  9900. },
  9901. enumerable: true,
  9902. configurable: true
  9903. });
  9904. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9905. get: function () {
  9906. return Engine._ALPHA_ONEONE;
  9907. },
  9908. enumerable: true,
  9909. configurable: true
  9910. });
  9911. Object.defineProperty(Engine, "ALPHA_ADD", {
  9912. get: function () {
  9913. return Engine._ALPHA_ADD;
  9914. },
  9915. enumerable: true,
  9916. configurable: true
  9917. });
  9918. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9919. get: function () {
  9920. return Engine._ALPHA_COMBINE;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9926. get: function () {
  9927. return Engine._ALPHA_SUBTRACT;
  9928. },
  9929. enumerable: true,
  9930. configurable: true
  9931. });
  9932. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9933. get: function () {
  9934. return Engine._ALPHA_MULTIPLY;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9940. get: function () {
  9941. return Engine._ALPHA_MAXIMIZED;
  9942. },
  9943. enumerable: true,
  9944. configurable: true
  9945. });
  9946. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9947. get: function () {
  9948. return Engine._ALPHA_PREMULTIPLIED;
  9949. },
  9950. enumerable: true,
  9951. configurable: true
  9952. });
  9953. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9954. get: function () {
  9955. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9956. },
  9957. enumerable: true,
  9958. configurable: true
  9959. });
  9960. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9961. get: function () {
  9962. return Engine._ALPHA_INTERPOLATE;
  9963. },
  9964. enumerable: true,
  9965. configurable: true
  9966. });
  9967. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9968. get: function () {
  9969. return Engine._ALPHA_SCREENMODE;
  9970. },
  9971. enumerable: true,
  9972. configurable: true
  9973. });
  9974. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9975. get: function () {
  9976. return Engine._DELAYLOADSTATE_NONE;
  9977. },
  9978. enumerable: true,
  9979. configurable: true
  9980. });
  9981. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9982. get: function () {
  9983. return Engine._DELAYLOADSTATE_LOADED;
  9984. },
  9985. enumerable: true,
  9986. configurable: true
  9987. });
  9988. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9989. get: function () {
  9990. return Engine._DELAYLOADSTATE_LOADING;
  9991. },
  9992. enumerable: true,
  9993. configurable: true
  9994. });
  9995. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9996. get: function () {
  9997. return Engine._DELAYLOADSTATE_NOTLOADED;
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10003. get: function () {
  10004. return Engine._TEXTUREFORMAT_ALPHA;
  10005. },
  10006. enumerable: true,
  10007. configurable: true
  10008. });
  10009. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10010. get: function () {
  10011. return Engine._TEXTUREFORMAT_LUMINANCE;
  10012. },
  10013. enumerable: true,
  10014. configurable: true
  10015. });
  10016. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10017. get: function () {
  10018. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10019. },
  10020. enumerable: true,
  10021. configurable: true
  10022. });
  10023. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10024. get: function () {
  10025. return Engine._TEXTUREFORMAT_RGB;
  10026. },
  10027. enumerable: true,
  10028. configurable: true
  10029. });
  10030. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10031. get: function () {
  10032. return Engine._TEXTUREFORMAT_RGBA;
  10033. },
  10034. enumerable: true,
  10035. configurable: true
  10036. });
  10037. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10038. get: function () {
  10039. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10040. },
  10041. enumerable: true,
  10042. configurable: true
  10043. });
  10044. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10045. get: function () {
  10046. return Engine._TEXTURETYPE_FLOAT;
  10047. },
  10048. enumerable: true,
  10049. configurable: true
  10050. });
  10051. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10052. get: function () {
  10053. return Engine._TEXTURETYPE_HALF_FLOAT;
  10054. },
  10055. enumerable: true,
  10056. configurable: true
  10057. });
  10058. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10059. get: function () {
  10060. return Engine._SCALEMODE_FLOOR;
  10061. },
  10062. enumerable: true,
  10063. configurable: true
  10064. });
  10065. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10066. get: function () {
  10067. return Engine._SCALEMODE_NEAREST;
  10068. },
  10069. enumerable: true,
  10070. configurable: true
  10071. });
  10072. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10073. get: function () {
  10074. return Engine._SCALEMODE_CEILING;
  10075. },
  10076. enumerable: true,
  10077. configurable: true
  10078. });
  10079. Object.defineProperty(Engine, "Version", {
  10080. get: function () {
  10081. return "3.2.0-alpha6";
  10082. },
  10083. enumerable: true,
  10084. configurable: true
  10085. });
  10086. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10087. get: function () {
  10088. return this._vrExclusivePointerMode;
  10089. },
  10090. enumerable: true,
  10091. configurable: true
  10092. });
  10093. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10094. get: function () {
  10095. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10096. },
  10097. enumerable: true,
  10098. configurable: true
  10099. });
  10100. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10101. get: function () {
  10102. return this._webGLVersion < 2 || this.forcePOTTextures;
  10103. },
  10104. enumerable: true,
  10105. configurable: true
  10106. });
  10107. Object.defineProperty(Engine.prototype, "badOS", {
  10108. get: function () {
  10109. return this._badOS;
  10110. },
  10111. enumerable: true,
  10112. configurable: true
  10113. });
  10114. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10115. get: function () {
  10116. return this._badDesktopOS;
  10117. },
  10118. enumerable: true,
  10119. configurable: true
  10120. });
  10121. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10122. get: function () {
  10123. return this._performanceMonitor;
  10124. },
  10125. enumerable: true,
  10126. configurable: true
  10127. });
  10128. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10129. get: function () {
  10130. return this._texturesSupported;
  10131. },
  10132. enumerable: true,
  10133. configurable: true
  10134. });
  10135. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10136. get: function () {
  10137. return this._textureFormatInUse;
  10138. },
  10139. enumerable: true,
  10140. configurable: true
  10141. });
  10142. Object.defineProperty(Engine.prototype, "currentViewport", {
  10143. get: function () {
  10144. return this._cachedViewport;
  10145. },
  10146. enumerable: true,
  10147. configurable: true
  10148. });
  10149. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10150. // Empty texture
  10151. get: function () {
  10152. if (!this._emptyTexture) {
  10153. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10154. }
  10155. return this._emptyTexture;
  10156. },
  10157. enumerable: true,
  10158. configurable: true
  10159. });
  10160. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10161. get: function () {
  10162. if (!this._emptyTexture3D) {
  10163. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10164. }
  10165. return this._emptyTexture3D;
  10166. },
  10167. enumerable: true,
  10168. configurable: true
  10169. });
  10170. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10171. get: function () {
  10172. if (!this._emptyCubeTexture) {
  10173. var faceData = new Uint8Array(4);
  10174. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10175. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10176. }
  10177. return this._emptyCubeTexture;
  10178. },
  10179. enumerable: true,
  10180. configurable: true
  10181. });
  10182. Engine.prototype._rebuildInternalTextures = function () {
  10183. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10184. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10185. var internalTexture = currentState_1[_i];
  10186. internalTexture._rebuild();
  10187. }
  10188. };
  10189. Engine.prototype._rebuildEffects = function () {
  10190. for (var key in this._compiledEffects) {
  10191. var effect = this._compiledEffects[key];
  10192. effect._prepareEffect();
  10193. }
  10194. BABYLON.Effect.ResetCache();
  10195. };
  10196. Engine.prototype._rebuildBuffers = function () {
  10197. // Index / Vertex
  10198. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10199. var scene = _a[_i];
  10200. scene.resetCachedMaterial();
  10201. scene._rebuildGeometries();
  10202. scene._rebuildTextures();
  10203. }
  10204. // Uniforms
  10205. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10206. var uniformBuffer = _c[_b];
  10207. uniformBuffer._rebuild();
  10208. }
  10209. };
  10210. Engine.prototype._initGLContext = function () {
  10211. // Caps
  10212. this._caps = new EngineCapabilities();
  10213. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10214. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10215. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10216. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10217. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10218. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10219. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10220. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10221. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10222. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10223. // Infos
  10224. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10225. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10226. if (rendererInfo != null) {
  10227. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10228. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  10229. }
  10230. if (!this._glVendor) {
  10231. this._glVendor = "Unknown vendor";
  10232. }
  10233. if (!this._glRenderer) {
  10234. this._glRenderer = "Unknown renderer";
  10235. }
  10236. // Constants
  10237. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10238. if (this._gl.RGBA16F !== 0x881A) {
  10239. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10240. }
  10241. if (this._gl.RGBA32F !== 0x8814) {
  10242. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10243. }
  10244. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10245. this._gl.DEPTH24_STENCIL8 = 35056;
  10246. }
  10247. // Extensions
  10248. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  10249. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  10250. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10251. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10252. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  10253. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  10254. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  10255. 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');
  10256. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  10257. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  10258. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  10259. this._caps.highPrecisionShaderSupported = true;
  10260. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  10261. if (this._caps.timerQuery) {
  10262. if (this._webGLVersion === 1) {
  10263. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  10264. }
  10265. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  10266. }
  10267. // Checks if some of the format renders first to allow the use of webgl inspector.
  10268. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  10269. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  10270. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  10271. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  10272. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  10273. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  10274. if (this._webGLVersion > 1) {
  10275. this._gl.HALF_FLOAT_OES = 0x140B;
  10276. }
  10277. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  10278. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  10279. // Draw buffers
  10280. if (this._webGLVersion > 1) {
  10281. this._caps.drawBuffersExtension = true;
  10282. }
  10283. else {
  10284. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  10285. if (drawBuffersExtension !== null) {
  10286. this._caps.drawBuffersExtension = true;
  10287. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  10288. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  10289. for (var i = 0; i < 16; i++) {
  10290. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  10291. }
  10292. }
  10293. else {
  10294. this._caps.drawBuffersExtension = false;
  10295. }
  10296. }
  10297. // Depth Texture
  10298. if (this._webGLVersion > 1) {
  10299. this._caps.depthTextureExtension = true;
  10300. }
  10301. else {
  10302. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  10303. if (depthTextureExtension != null) {
  10304. this._caps.depthTextureExtension = true;
  10305. }
  10306. }
  10307. // Vertex array object
  10308. if (this._webGLVersion > 1) {
  10309. this._caps.vertexArrayObject = true;
  10310. }
  10311. else {
  10312. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  10313. if (vertexArrayObjectExtension != null) {
  10314. this._caps.vertexArrayObject = true;
  10315. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  10316. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  10317. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  10318. }
  10319. else {
  10320. this._caps.vertexArrayObject = false;
  10321. }
  10322. }
  10323. // Instances count
  10324. if (this._webGLVersion > 1) {
  10325. this._caps.instancedArrays = true;
  10326. }
  10327. else {
  10328. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  10329. if (instanceExtension != null) {
  10330. this._caps.instancedArrays = true;
  10331. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  10332. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  10333. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  10334. }
  10335. else {
  10336. this._caps.instancedArrays = false;
  10337. }
  10338. }
  10339. // Intelligently add supported compressed formats in order to check for.
  10340. // Check for ASTC support first as it is most powerful and to be very cross platform.
  10341. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  10342. // Likely no hardware which supports both PVR & DXT, so order matters little.
  10343. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  10344. if (this._caps.astc)
  10345. this.texturesSupported.push('-astc.ktx');
  10346. if (this._caps.s3tc)
  10347. this.texturesSupported.push('-dxt.ktx');
  10348. if (this._caps.pvrtc)
  10349. this.texturesSupported.push('-pvrtc.ktx');
  10350. if (this._caps.etc2)
  10351. this.texturesSupported.push('-etc2.ktx');
  10352. if (this._caps.etc1)
  10353. this.texturesSupported.push('-etc1.ktx');
  10354. if (this._gl.getShaderPrecisionFormat) {
  10355. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  10356. if (highp) {
  10357. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  10358. }
  10359. }
  10360. // Depth buffer
  10361. this.setDepthBuffer(true);
  10362. this.setDepthFunctionToLessOrEqual();
  10363. this.setDepthWrite(true);
  10364. // Texture maps
  10365. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  10366. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10367. this._nextFreeTextureSlots.push(slot);
  10368. }
  10369. };
  10370. Object.defineProperty(Engine.prototype, "webGLVersion", {
  10371. get: function () {
  10372. return this._webGLVersion;
  10373. },
  10374. enumerable: true,
  10375. configurable: true
  10376. });
  10377. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  10378. /**
  10379. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  10380. */
  10381. get: function () {
  10382. return this._isStencilEnable;
  10383. },
  10384. enumerable: true,
  10385. configurable: true
  10386. });
  10387. Engine.prototype._prepareWorkingCanvas = function () {
  10388. if (this._workingCanvas) {
  10389. return;
  10390. }
  10391. this._workingCanvas = document.createElement("canvas");
  10392. var context = this._workingCanvas.getContext("2d");
  10393. if (context) {
  10394. this._workingContext = context;
  10395. }
  10396. };
  10397. Engine.prototype.resetTextureCache = function () {
  10398. for (var key in this._boundTexturesCache) {
  10399. var boundTexture = this._boundTexturesCache[key];
  10400. if (boundTexture) {
  10401. this._removeDesignatedSlot(boundTexture);
  10402. }
  10403. this._boundTexturesCache[key] = null;
  10404. }
  10405. this._nextFreeTextureSlots = [];
  10406. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10407. this._nextFreeTextureSlots.push(slot);
  10408. }
  10409. this._currentTextureChannel = -1;
  10410. };
  10411. Engine.prototype.isDeterministicLockStep = function () {
  10412. return this._deterministicLockstep;
  10413. };
  10414. Engine.prototype.getLockstepMaxSteps = function () {
  10415. return this._lockstepMaxSteps;
  10416. };
  10417. Engine.prototype.getGlInfo = function () {
  10418. return {
  10419. vendor: this._glVendor,
  10420. renderer: this._glRenderer,
  10421. version: this._glVersion
  10422. };
  10423. };
  10424. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  10425. if (useScreen === void 0) { useScreen = false; }
  10426. var viewport = camera.viewport;
  10427. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  10428. };
  10429. Engine.prototype.getRenderWidth = function (useScreen) {
  10430. if (useScreen === void 0) { useScreen = false; }
  10431. if (!useScreen && this._currentRenderTarget) {
  10432. return this._currentRenderTarget.width;
  10433. }
  10434. return this._gl.drawingBufferWidth;
  10435. };
  10436. Engine.prototype.getRenderHeight = function (useScreen) {
  10437. if (useScreen === void 0) { useScreen = false; }
  10438. if (!useScreen && this._currentRenderTarget) {
  10439. return this._currentRenderTarget.height;
  10440. }
  10441. return this._gl.drawingBufferHeight;
  10442. };
  10443. Engine.prototype.getRenderingCanvas = function () {
  10444. return this._renderingCanvas;
  10445. };
  10446. Engine.prototype.getRenderingCanvasClientRect = function () {
  10447. if (!this._renderingCanvas) {
  10448. return null;
  10449. }
  10450. return this._renderingCanvas.getBoundingClientRect();
  10451. };
  10452. Engine.prototype.setHardwareScalingLevel = function (level) {
  10453. this._hardwareScalingLevel = level;
  10454. this.resize();
  10455. };
  10456. Engine.prototype.getHardwareScalingLevel = function () {
  10457. return this._hardwareScalingLevel;
  10458. };
  10459. Engine.prototype.getLoadedTexturesCache = function () {
  10460. return this._internalTexturesCache;
  10461. };
  10462. Engine.prototype.getCaps = function () {
  10463. return this._caps;
  10464. };
  10465. Object.defineProperty(Engine.prototype, "drawCalls", {
  10466. /** The number of draw calls submitted last frame */
  10467. get: function () {
  10468. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  10469. return 0;
  10470. },
  10471. enumerable: true,
  10472. configurable: true
  10473. });
  10474. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  10475. get: function () {
  10476. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10477. return null;
  10478. },
  10479. enumerable: true,
  10480. configurable: true
  10481. });
  10482. Engine.prototype.getDepthFunction = function () {
  10483. return this._depthCullingState.depthFunc;
  10484. };
  10485. Engine.prototype.setDepthFunction = function (depthFunc) {
  10486. this._depthCullingState.depthFunc = depthFunc;
  10487. };
  10488. Engine.prototype.setDepthFunctionToGreater = function () {
  10489. this._depthCullingState.depthFunc = this._gl.GREATER;
  10490. };
  10491. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10492. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10493. };
  10494. Engine.prototype.setDepthFunctionToLess = function () {
  10495. this._depthCullingState.depthFunc = this._gl.LESS;
  10496. };
  10497. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10498. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10499. };
  10500. Engine.prototype.getStencilBuffer = function () {
  10501. return this._stencilState.stencilTest;
  10502. };
  10503. Engine.prototype.setStencilBuffer = function (enable) {
  10504. this._stencilState.stencilTest = enable;
  10505. };
  10506. Engine.prototype.getStencilMask = function () {
  10507. return this._stencilState.stencilMask;
  10508. };
  10509. Engine.prototype.setStencilMask = function (mask) {
  10510. this._stencilState.stencilMask = mask;
  10511. };
  10512. Engine.prototype.getStencilFunction = function () {
  10513. return this._stencilState.stencilFunc;
  10514. };
  10515. Engine.prototype.getStencilFunctionReference = function () {
  10516. return this._stencilState.stencilFuncRef;
  10517. };
  10518. Engine.prototype.getStencilFunctionMask = function () {
  10519. return this._stencilState.stencilFuncMask;
  10520. };
  10521. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10522. this._stencilState.stencilFunc = stencilFunc;
  10523. };
  10524. Engine.prototype.setStencilFunctionReference = function (reference) {
  10525. this._stencilState.stencilFuncRef = reference;
  10526. };
  10527. Engine.prototype.setStencilFunctionMask = function (mask) {
  10528. this._stencilState.stencilFuncMask = mask;
  10529. };
  10530. Engine.prototype.getStencilOperationFail = function () {
  10531. return this._stencilState.stencilOpStencilFail;
  10532. };
  10533. Engine.prototype.getStencilOperationDepthFail = function () {
  10534. return this._stencilState.stencilOpDepthFail;
  10535. };
  10536. Engine.prototype.getStencilOperationPass = function () {
  10537. return this._stencilState.stencilOpStencilDepthPass;
  10538. };
  10539. Engine.prototype.setStencilOperationFail = function (operation) {
  10540. this._stencilState.stencilOpStencilFail = operation;
  10541. };
  10542. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10543. this._stencilState.stencilOpDepthFail = operation;
  10544. };
  10545. Engine.prototype.setStencilOperationPass = function (operation) {
  10546. this._stencilState.stencilOpStencilDepthPass = operation;
  10547. };
  10548. Engine.prototype.setDitheringState = function (value) {
  10549. if (value) {
  10550. this._gl.enable(this._gl.DITHER);
  10551. }
  10552. else {
  10553. this._gl.disable(this._gl.DITHER);
  10554. }
  10555. };
  10556. Engine.prototype.setRasterizerState = function (value) {
  10557. if (value) {
  10558. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10559. }
  10560. else {
  10561. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10562. }
  10563. };
  10564. /**
  10565. * stop executing a render loop function and remove it from the execution array
  10566. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10567. */
  10568. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10569. if (!renderFunction) {
  10570. this._activeRenderLoops = [];
  10571. return;
  10572. }
  10573. var index = this._activeRenderLoops.indexOf(renderFunction);
  10574. if (index >= 0) {
  10575. this._activeRenderLoops.splice(index, 1);
  10576. }
  10577. };
  10578. Engine.prototype._renderLoop = function () {
  10579. if (!this._contextWasLost) {
  10580. var shouldRender = true;
  10581. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10582. shouldRender = false;
  10583. }
  10584. if (shouldRender) {
  10585. // Start new frame
  10586. this.beginFrame();
  10587. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10588. var renderFunction = this._activeRenderLoops[index];
  10589. renderFunction();
  10590. }
  10591. // Present
  10592. this.endFrame();
  10593. }
  10594. }
  10595. if (this._activeRenderLoops.length > 0) {
  10596. // Register new frame
  10597. var requester = null;
  10598. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10599. requester = this._vrDisplay;
  10600. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10601. }
  10602. else {
  10603. this._renderingQueueLaunched = false;
  10604. }
  10605. };
  10606. /**
  10607. * Register and execute a render loop. The engine can have more than one render function.
  10608. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10609. * @example
  10610. * engine.runRenderLoop(function () {
  10611. * scene.render()
  10612. * })
  10613. */
  10614. Engine.prototype.runRenderLoop = function (renderFunction) {
  10615. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10616. return;
  10617. }
  10618. this._activeRenderLoops.push(renderFunction);
  10619. if (!this._renderingQueueLaunched) {
  10620. this._renderingQueueLaunched = true;
  10621. this._bindedRenderFunction = this._renderLoop.bind(this);
  10622. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10623. }
  10624. };
  10625. /**
  10626. * Toggle full screen mode.
  10627. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10628. * @param {any} options - an options object to be sent to the requestFullscreen function
  10629. */
  10630. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10631. if (this.isFullscreen) {
  10632. BABYLON.Tools.ExitFullscreen();
  10633. }
  10634. else {
  10635. this._pointerLockRequested = requestPointerLock;
  10636. if (this._renderingCanvas) {
  10637. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10638. }
  10639. }
  10640. };
  10641. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10642. if (stencil === void 0) { stencil = false; }
  10643. this.applyStates();
  10644. var mode = 0;
  10645. if (backBuffer && color) {
  10646. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10647. mode |= this._gl.COLOR_BUFFER_BIT;
  10648. }
  10649. if (depth) {
  10650. this._gl.clearDepth(1.0);
  10651. mode |= this._gl.DEPTH_BUFFER_BIT;
  10652. }
  10653. if (stencil) {
  10654. this._gl.clearStencil(0);
  10655. mode |= this._gl.STENCIL_BUFFER_BIT;
  10656. }
  10657. this._gl.clear(mode);
  10658. };
  10659. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10660. var gl = this._gl;
  10661. // Save state
  10662. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10663. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10664. // Change state
  10665. gl.enable(gl.SCISSOR_TEST);
  10666. gl.scissor(x, y, width, height);
  10667. // Clear
  10668. this.clear(clearColor, true, true, true);
  10669. // Restore state
  10670. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10671. if (curScissor === true) {
  10672. gl.enable(gl.SCISSOR_TEST);
  10673. }
  10674. else {
  10675. gl.disable(gl.SCISSOR_TEST);
  10676. }
  10677. };
  10678. /**
  10679. * Set the WebGL's viewport
  10680. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10681. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10682. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10683. */
  10684. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10685. var width = requiredWidth || this.getRenderWidth();
  10686. var height = requiredHeight || this.getRenderHeight();
  10687. var x = viewport.x || 0;
  10688. var y = viewport.y || 0;
  10689. this._cachedViewport = viewport;
  10690. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10691. };
  10692. /**
  10693. * Directly set the WebGL Viewport
  10694. * The x, y, width & height are directly passed to the WebGL call
  10695. * @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.
  10696. */
  10697. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10698. var currentViewport = this._cachedViewport;
  10699. this._cachedViewport = null;
  10700. this._gl.viewport(x, y, width, height);
  10701. return currentViewport;
  10702. };
  10703. Engine.prototype.beginFrame = function () {
  10704. this.onBeginFrameObservable.notifyObservers(this);
  10705. this._measureFps();
  10706. };
  10707. Engine.prototype.endFrame = function () {
  10708. //force a flush in case we are using a bad OS.
  10709. if (this._badOS) {
  10710. this.flushFramebuffer();
  10711. }
  10712. //submit frame to the vr device, if enabled
  10713. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10714. // TODO: We should only submit the frame if we read frameData successfully.
  10715. this._vrDisplay.submitFrame();
  10716. }
  10717. this.onEndFrameObservable.notifyObservers(this);
  10718. };
  10719. /**
  10720. * resize the view according to the canvas' size.
  10721. * @example
  10722. * window.addEventListener("resize", function () {
  10723. * engine.resize();
  10724. * });
  10725. */
  10726. Engine.prototype.resize = function () {
  10727. // We're not resizing the size of the canvas while in VR mode & presenting
  10728. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10729. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10730. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10731. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10732. }
  10733. };
  10734. /**
  10735. * force a specific size of the canvas
  10736. * @param {number} width - the new canvas' width
  10737. * @param {number} height - the new canvas' height
  10738. */
  10739. Engine.prototype.setSize = function (width, height) {
  10740. if (!this._renderingCanvas) {
  10741. return;
  10742. }
  10743. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10744. return;
  10745. }
  10746. this._renderingCanvas.width = width;
  10747. this._renderingCanvas.height = height;
  10748. for (var index = 0; index < this.scenes.length; index++) {
  10749. var scene = this.scenes[index];
  10750. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10751. var cam = scene.cameras[camIndex];
  10752. cam._currentRenderId = 0;
  10753. }
  10754. }
  10755. if (this.onResizeObservable.hasObservers) {
  10756. this.onResizeObservable.notifyObservers(this);
  10757. }
  10758. };
  10759. // WebVR functions
  10760. Engine.prototype.isVRDevicePresent = function () {
  10761. return !!this._vrDisplay;
  10762. };
  10763. Engine.prototype.getVRDevice = function () {
  10764. return this._vrDisplay;
  10765. };
  10766. Engine.prototype.initWebVR = function () {
  10767. var _this = this;
  10768. var notifyObservers = function () {
  10769. var eventArgs = {
  10770. vrDisplay: _this._vrDisplay,
  10771. vrSupported: _this._vrSupported
  10772. };
  10773. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10774. };
  10775. if (!this._onVrDisplayConnect) {
  10776. this._onVrDisplayConnect = function (event) {
  10777. _this._vrDisplay = event.display;
  10778. notifyObservers();
  10779. };
  10780. this._onVrDisplayDisconnect = function () {
  10781. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10782. _this._vrDisplay = undefined;
  10783. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10784. notifyObservers();
  10785. };
  10786. this._onVrDisplayPresentChange = function () {
  10787. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10788. };
  10789. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10790. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10791. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10792. }
  10793. this._getVRDisplays(notifyObservers);
  10794. return this.onVRDisplayChangedObservable;
  10795. };
  10796. Engine.prototype.enableVR = function () {
  10797. var _this = this;
  10798. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10799. var onResolved = function () {
  10800. _this.onVRRequestPresentComplete.notifyObservers(true);
  10801. _this._onVRFullScreenTriggered();
  10802. };
  10803. var onRejected = function () {
  10804. _this.onVRRequestPresentComplete.notifyObservers(false);
  10805. };
  10806. this.onVRRequestPresentStart.notifyObservers(this);
  10807. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10808. }
  10809. };
  10810. Engine.prototype.disableVR = function () {
  10811. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10812. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10813. }
  10814. };
  10815. Engine.prototype._getVRDisplays = function (callback) {
  10816. var _this = this;
  10817. var getWebVRDevices = function (devices) {
  10818. _this._vrSupported = true;
  10819. // note that devices may actually be an empty array. This is fine;
  10820. // we expect this._vrDisplay to be undefined in this case.
  10821. return _this._vrDisplay = devices[0];
  10822. };
  10823. if (navigator.getVRDisplays) {
  10824. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10825. // TODO: System CANNOT support WebVR, despite API presence.
  10826. _this._vrSupported = false;
  10827. callback();
  10828. });
  10829. }
  10830. else {
  10831. // TODO: Browser does not support WebVR
  10832. this._vrDisplay = undefined;
  10833. this._vrSupported = false;
  10834. callback();
  10835. }
  10836. };
  10837. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10838. if (this._currentRenderTarget) {
  10839. this.unBindFramebuffer(this._currentRenderTarget);
  10840. }
  10841. this._currentRenderTarget = texture;
  10842. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10843. var gl = this._gl;
  10844. if (texture.isCube) {
  10845. if (faceIndex === undefined) {
  10846. faceIndex = 0;
  10847. }
  10848. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10849. }
  10850. if (this._cachedViewport && !forceFullscreenViewport) {
  10851. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10852. }
  10853. else {
  10854. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10855. }
  10856. this.wipeCaches();
  10857. };
  10858. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10859. if (this._currentFramebuffer !== framebuffer) {
  10860. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10861. this._currentFramebuffer = framebuffer;
  10862. }
  10863. };
  10864. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10865. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10866. this._currentRenderTarget = null;
  10867. // If MSAA, we need to bitblt back to main texture
  10868. var gl = this._gl;
  10869. if (texture._MSAAFramebuffer) {
  10870. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10871. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10872. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10873. }
  10874. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10875. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10876. gl.generateMipmap(gl.TEXTURE_2D);
  10877. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10878. }
  10879. if (onBeforeUnbind) {
  10880. if (texture._MSAAFramebuffer) {
  10881. // Bind the correct framebuffer
  10882. this.bindUnboundFramebuffer(texture._framebuffer);
  10883. }
  10884. onBeforeUnbind();
  10885. }
  10886. this.bindUnboundFramebuffer(null);
  10887. };
  10888. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10889. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10890. this._currentRenderTarget = null;
  10891. // If MSAA, we need to bitblt back to main texture
  10892. var gl = this._gl;
  10893. if (textures[0]._MSAAFramebuffer) {
  10894. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10895. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10896. var attachments = textures[0]._attachments;
  10897. if (!attachments) {
  10898. attachments = new Array(textures.length);
  10899. textures[0]._attachments = attachments;
  10900. }
  10901. for (var i = 0; i < textures.length; i++) {
  10902. var texture = textures[i];
  10903. for (var j = 0; j < attachments.length; j++) {
  10904. attachments[j] = gl.NONE;
  10905. }
  10906. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10907. gl.readBuffer(attachments[i]);
  10908. gl.drawBuffers(attachments);
  10909. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10910. }
  10911. for (var i = 0; i < attachments.length; i++) {
  10912. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10913. }
  10914. gl.drawBuffers(attachments);
  10915. }
  10916. for (var i = 0; i < textures.length; i++) {
  10917. var texture = textures[i];
  10918. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10919. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10920. gl.generateMipmap(gl.TEXTURE_2D);
  10921. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10922. }
  10923. }
  10924. if (onBeforeUnbind) {
  10925. if (textures[0]._MSAAFramebuffer) {
  10926. // Bind the correct framebuffer
  10927. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10928. }
  10929. onBeforeUnbind();
  10930. }
  10931. this.bindUnboundFramebuffer(null);
  10932. };
  10933. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10934. if (texture.generateMipMaps) {
  10935. var gl = this._gl;
  10936. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10937. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10938. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10939. }
  10940. };
  10941. Engine.prototype.flushFramebuffer = function () {
  10942. this._gl.flush();
  10943. };
  10944. Engine.prototype.restoreDefaultFramebuffer = function () {
  10945. if (this._currentRenderTarget) {
  10946. this.unBindFramebuffer(this._currentRenderTarget);
  10947. }
  10948. else {
  10949. this.bindUnboundFramebuffer(null);
  10950. }
  10951. if (this._cachedViewport) {
  10952. this.setViewport(this._cachedViewport);
  10953. }
  10954. this.wipeCaches();
  10955. };
  10956. // UBOs
  10957. Engine.prototype.createUniformBuffer = function (elements) {
  10958. var ubo = this._gl.createBuffer();
  10959. if (!ubo) {
  10960. throw new Error("Unable to create uniform buffer");
  10961. }
  10962. this.bindUniformBuffer(ubo);
  10963. if (elements instanceof Float32Array) {
  10964. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10965. }
  10966. else {
  10967. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10968. }
  10969. this.bindUniformBuffer(null);
  10970. ubo.references = 1;
  10971. return ubo;
  10972. };
  10973. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10974. var ubo = this._gl.createBuffer();
  10975. if (!ubo) {
  10976. throw new Error("Unable to create dynamic uniform buffer");
  10977. }
  10978. this.bindUniformBuffer(ubo);
  10979. if (elements instanceof Float32Array) {
  10980. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10981. }
  10982. else {
  10983. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10984. }
  10985. this.bindUniformBuffer(null);
  10986. ubo.references = 1;
  10987. return ubo;
  10988. };
  10989. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10990. this.bindUniformBuffer(uniformBuffer);
  10991. if (offset === undefined) {
  10992. offset = 0;
  10993. }
  10994. if (count === undefined) {
  10995. if (elements instanceof Float32Array) {
  10996. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10997. }
  10998. else {
  10999. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11000. }
  11001. }
  11002. else {
  11003. if (elements instanceof Float32Array) {
  11004. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11005. }
  11006. else {
  11007. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11008. }
  11009. }
  11010. this.bindUniformBuffer(null);
  11011. };
  11012. // VBOs
  11013. Engine.prototype._resetVertexBufferBinding = function () {
  11014. this.bindArrayBuffer(null);
  11015. this._cachedVertexBuffers = null;
  11016. };
  11017. Engine.prototype.createVertexBuffer = function (vertices) {
  11018. var vbo = this._gl.createBuffer();
  11019. if (!vbo) {
  11020. throw new Error("Unable to create vertex buffer");
  11021. }
  11022. this.bindArrayBuffer(vbo);
  11023. if (vertices instanceof Float32Array) {
  11024. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11025. }
  11026. else {
  11027. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11028. }
  11029. this._resetVertexBufferBinding();
  11030. vbo.references = 1;
  11031. return vbo;
  11032. };
  11033. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11034. var vbo = this._gl.createBuffer();
  11035. if (!vbo) {
  11036. throw new Error("Unable to create dynamic vertex buffer");
  11037. }
  11038. this.bindArrayBuffer(vbo);
  11039. if (vertices instanceof Float32Array) {
  11040. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11041. }
  11042. else {
  11043. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11044. }
  11045. this._resetVertexBufferBinding();
  11046. vbo.references = 1;
  11047. return vbo;
  11048. };
  11049. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11050. if (offset === void 0) { offset = 0; }
  11051. // Force cache update
  11052. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11053. this.bindIndexBuffer(indexBuffer);
  11054. var arrayBuffer;
  11055. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11056. arrayBuffer = indices;
  11057. }
  11058. else {
  11059. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11060. }
  11061. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11062. this._resetIndexBufferBinding();
  11063. };
  11064. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11065. this.bindArrayBuffer(vertexBuffer);
  11066. if (offset === undefined) {
  11067. offset = 0;
  11068. }
  11069. if (count === undefined) {
  11070. if (vertices instanceof Float32Array) {
  11071. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11072. }
  11073. else {
  11074. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11075. }
  11076. }
  11077. else {
  11078. if (vertices instanceof Float32Array) {
  11079. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11080. }
  11081. else {
  11082. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11083. }
  11084. }
  11085. this._resetVertexBufferBinding();
  11086. };
  11087. Engine.prototype._resetIndexBufferBinding = function () {
  11088. this.bindIndexBuffer(null);
  11089. this._cachedIndexBuffer = null;
  11090. };
  11091. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11092. var vbo = this._gl.createBuffer();
  11093. if (!vbo) {
  11094. throw new Error("Unable to create index buffer");
  11095. }
  11096. this.bindIndexBuffer(vbo);
  11097. // Check for 32 bits indices
  11098. var arrayBuffer;
  11099. var need32Bits = false;
  11100. if (indices instanceof Uint16Array) {
  11101. arrayBuffer = indices;
  11102. }
  11103. else {
  11104. //check 32 bit support
  11105. if (this._caps.uintIndices) {
  11106. if (indices instanceof Uint32Array) {
  11107. arrayBuffer = indices;
  11108. need32Bits = true;
  11109. }
  11110. else {
  11111. //number[] or Int32Array, check if 32 bit is necessary
  11112. for (var index = 0; index < indices.length; index++) {
  11113. if (indices[index] > 65535) {
  11114. need32Bits = true;
  11115. break;
  11116. }
  11117. }
  11118. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11119. }
  11120. }
  11121. else {
  11122. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11123. arrayBuffer = new Uint16Array(indices);
  11124. }
  11125. }
  11126. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11127. this._resetIndexBufferBinding();
  11128. vbo.references = 1;
  11129. vbo.is32Bits = need32Bits;
  11130. return vbo;
  11131. };
  11132. Engine.prototype.bindArrayBuffer = function (buffer) {
  11133. if (!this._vaoRecordInProgress) {
  11134. this._unbindVertexArrayObject();
  11135. }
  11136. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11137. };
  11138. Engine.prototype.bindUniformBuffer = function (buffer) {
  11139. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11140. };
  11141. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11142. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11143. };
  11144. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11145. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11146. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11147. };
  11148. ;
  11149. Engine.prototype.bindIndexBuffer = function (buffer) {
  11150. if (!this._vaoRecordInProgress) {
  11151. this._unbindVertexArrayObject();
  11152. }
  11153. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11154. };
  11155. Engine.prototype.bindBuffer = function (buffer, target) {
  11156. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11157. this._gl.bindBuffer(target, buffer);
  11158. this._currentBoundBuffer[target] = buffer;
  11159. }
  11160. };
  11161. Engine.prototype.updateArrayBuffer = function (data) {
  11162. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11163. };
  11164. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11165. var pointer = this._currentBufferPointers[indx];
  11166. var changed = false;
  11167. if (!pointer.active) {
  11168. changed = true;
  11169. pointer.active = true;
  11170. pointer.index = indx;
  11171. pointer.size = size;
  11172. pointer.type = type;
  11173. pointer.normalized = normalized;
  11174. pointer.stride = stride;
  11175. pointer.offset = offset;
  11176. pointer.buffer = buffer;
  11177. }
  11178. else {
  11179. if (pointer.buffer !== buffer) {
  11180. pointer.buffer = buffer;
  11181. changed = true;
  11182. }
  11183. if (pointer.size !== size) {
  11184. pointer.size = size;
  11185. changed = true;
  11186. }
  11187. if (pointer.type !== type) {
  11188. pointer.type = type;
  11189. changed = true;
  11190. }
  11191. if (pointer.normalized !== normalized) {
  11192. pointer.normalized = normalized;
  11193. changed = true;
  11194. }
  11195. if (pointer.stride !== stride) {
  11196. pointer.stride = stride;
  11197. changed = true;
  11198. }
  11199. if (pointer.offset !== offset) {
  11200. pointer.offset = offset;
  11201. changed = true;
  11202. }
  11203. }
  11204. if (changed || this._vaoRecordInProgress) {
  11205. this.bindArrayBuffer(buffer);
  11206. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11207. }
  11208. };
  11209. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11210. if (indexBuffer == null) {
  11211. return;
  11212. }
  11213. if (this._cachedIndexBuffer !== indexBuffer) {
  11214. this._cachedIndexBuffer = indexBuffer;
  11215. this.bindIndexBuffer(indexBuffer);
  11216. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11217. }
  11218. };
  11219. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11220. var attributes = effect.getAttributesNames();
  11221. if (!this._vaoRecordInProgress) {
  11222. this._unbindVertexArrayObject();
  11223. }
  11224. this.unbindAllAttributes();
  11225. for (var index = 0; index < attributes.length; index++) {
  11226. var order = effect.getAttributeLocation(index);
  11227. if (order >= 0) {
  11228. var vertexBuffer = vertexBuffers[attributes[index]];
  11229. if (!vertexBuffer) {
  11230. continue;
  11231. }
  11232. this._gl.enableVertexAttribArray(order);
  11233. if (!this._vaoRecordInProgress) {
  11234. this._vertexAttribArraysEnabled[order] = true;
  11235. }
  11236. var buffer = vertexBuffer.getBuffer();
  11237. if (buffer) {
  11238. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  11239. if (vertexBuffer.getIsInstanced()) {
  11240. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  11241. if (!this._vaoRecordInProgress) {
  11242. this._currentInstanceLocations.push(order);
  11243. this._currentInstanceBuffers.push(buffer);
  11244. }
  11245. }
  11246. }
  11247. }
  11248. }
  11249. };
  11250. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  11251. var vao = this._gl.createVertexArray();
  11252. this._vaoRecordInProgress = true;
  11253. this._gl.bindVertexArray(vao);
  11254. this._mustWipeVertexAttributes = true;
  11255. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11256. this.bindIndexBuffer(indexBuffer);
  11257. this._vaoRecordInProgress = false;
  11258. this._gl.bindVertexArray(null);
  11259. return vao;
  11260. };
  11261. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  11262. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  11263. this._cachedVertexArrayObject = vertexArrayObject;
  11264. this._gl.bindVertexArray(vertexArrayObject);
  11265. this._cachedVertexBuffers = null;
  11266. this._cachedIndexBuffer = null;
  11267. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  11268. this._mustWipeVertexAttributes = true;
  11269. }
  11270. };
  11271. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  11272. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  11273. this._cachedVertexBuffers = vertexBuffer;
  11274. this._cachedEffectForVertexBuffers = effect;
  11275. var attributesCount = effect.getAttributesCount();
  11276. this._unbindVertexArrayObject();
  11277. this.unbindAllAttributes();
  11278. var offset = 0;
  11279. for (var index = 0; index < attributesCount; index++) {
  11280. if (index < vertexDeclaration.length) {
  11281. var order = effect.getAttributeLocation(index);
  11282. if (order >= 0) {
  11283. this._gl.enableVertexAttribArray(order);
  11284. this._vertexAttribArraysEnabled[order] = true;
  11285. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  11286. }
  11287. offset += vertexDeclaration[index] * 4;
  11288. }
  11289. }
  11290. }
  11291. this._bindIndexBufferWithCache(indexBuffer);
  11292. };
  11293. Engine.prototype._unbindVertexArrayObject = function () {
  11294. if (!this._cachedVertexArrayObject) {
  11295. return;
  11296. }
  11297. this._cachedVertexArrayObject = null;
  11298. this._gl.bindVertexArray(null);
  11299. };
  11300. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  11301. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  11302. this._cachedVertexBuffers = vertexBuffers;
  11303. this._cachedEffectForVertexBuffers = effect;
  11304. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11305. }
  11306. this._bindIndexBufferWithCache(indexBuffer);
  11307. };
  11308. Engine.prototype.unbindInstanceAttributes = function () {
  11309. var boundBuffer;
  11310. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  11311. var instancesBuffer = this._currentInstanceBuffers[i];
  11312. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  11313. boundBuffer = instancesBuffer;
  11314. this.bindArrayBuffer(instancesBuffer);
  11315. }
  11316. var offsetLocation = this._currentInstanceLocations[i];
  11317. this._gl.vertexAttribDivisor(offsetLocation, 0);
  11318. }
  11319. this._currentInstanceBuffers.length = 0;
  11320. this._currentInstanceLocations.length = 0;
  11321. };
  11322. Engine.prototype.releaseVertexArrayObject = function (vao) {
  11323. this._gl.deleteVertexArray(vao);
  11324. };
  11325. Engine.prototype._releaseBuffer = function (buffer) {
  11326. buffer.references--;
  11327. if (buffer.references === 0) {
  11328. this._gl.deleteBuffer(buffer);
  11329. return true;
  11330. }
  11331. return false;
  11332. };
  11333. Engine.prototype.createInstancesBuffer = function (capacity) {
  11334. var buffer = this._gl.createBuffer();
  11335. if (!buffer) {
  11336. throw new Error("Unable to create instance buffer");
  11337. }
  11338. buffer.capacity = capacity;
  11339. this.bindArrayBuffer(buffer);
  11340. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  11341. return buffer;
  11342. };
  11343. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  11344. this._gl.deleteBuffer(buffer);
  11345. };
  11346. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  11347. this.bindArrayBuffer(instancesBuffer);
  11348. if (data) {
  11349. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11350. }
  11351. if (offsetLocations[0].index !== undefined) {
  11352. var stride = 0;
  11353. for (var i = 0; i < offsetLocations.length; i++) {
  11354. var ai = offsetLocations[i];
  11355. stride += ai.attributeSize * 4;
  11356. }
  11357. for (var i = 0; i < offsetLocations.length; i++) {
  11358. var ai = offsetLocations[i];
  11359. if (!this._vertexAttribArraysEnabled[ai.index]) {
  11360. this._gl.enableVertexAttribArray(ai.index);
  11361. this._vertexAttribArraysEnabled[ai.index] = true;
  11362. }
  11363. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  11364. this._gl.vertexAttribDivisor(ai.index, 1);
  11365. this._currentInstanceLocations.push(ai.index);
  11366. this._currentInstanceBuffers.push(instancesBuffer);
  11367. }
  11368. }
  11369. else {
  11370. for (var index = 0; index < 4; index++) {
  11371. var offsetLocation = offsetLocations[index];
  11372. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  11373. this._gl.enableVertexAttribArray(offsetLocation);
  11374. this._vertexAttribArraysEnabled[offsetLocation] = true;
  11375. }
  11376. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  11377. this._gl.vertexAttribDivisor(offsetLocation, 1);
  11378. this._currentInstanceLocations.push(offsetLocation);
  11379. this._currentInstanceBuffers.push(instancesBuffer);
  11380. }
  11381. }
  11382. };
  11383. Engine.prototype.applyStates = function () {
  11384. this._depthCullingState.apply(this._gl);
  11385. this._stencilState.apply(this._gl);
  11386. this._alphaState.apply(this._gl);
  11387. };
  11388. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  11389. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  11390. };
  11391. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  11392. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  11393. };
  11394. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  11395. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  11396. };
  11397. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  11398. // Apply states
  11399. this.applyStates();
  11400. this._drawCalls.addCount(1, false);
  11401. // Render
  11402. var drawMode = this.DrawMode(fillMode);
  11403. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  11404. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  11405. if (instancesCount) {
  11406. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  11407. }
  11408. else {
  11409. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  11410. }
  11411. };
  11412. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  11413. // Apply states
  11414. this.applyStates();
  11415. this._drawCalls.addCount(1, false);
  11416. var drawMode = this.DrawMode(fillMode);
  11417. if (instancesCount) {
  11418. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  11419. }
  11420. else {
  11421. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  11422. }
  11423. };
  11424. Engine.prototype.DrawMode = function (fillMode) {
  11425. switch (fillMode) {
  11426. // Triangle views
  11427. case BABYLON.Material.TriangleFillMode:
  11428. return this._gl.TRIANGLES;
  11429. case BABYLON.Material.PointFillMode:
  11430. return this._gl.POINTS;
  11431. case BABYLON.Material.WireFrameFillMode:
  11432. return this._gl.LINES;
  11433. // Draw modes
  11434. case BABYLON.Material.PointListDrawMode:
  11435. return this._gl.POINTS;
  11436. case BABYLON.Material.LineListDrawMode:
  11437. return this._gl.LINES;
  11438. case BABYLON.Material.LineLoopDrawMode:
  11439. return this._gl.LINE_LOOP;
  11440. case BABYLON.Material.LineStripDrawMode:
  11441. return this._gl.LINE_STRIP;
  11442. case BABYLON.Material.TriangleStripDrawMode:
  11443. return this._gl.TRIANGLE_STRIP;
  11444. case BABYLON.Material.TriangleFanDrawMode:
  11445. return this._gl.TRIANGLE_FAN;
  11446. default:
  11447. return this._gl.TRIANGLES;
  11448. }
  11449. };
  11450. // Shaders
  11451. Engine.prototype._releaseEffect = function (effect) {
  11452. if (this._compiledEffects[effect._key]) {
  11453. delete this._compiledEffects[effect._key];
  11454. this._deleteProgram(effect.getProgram());
  11455. }
  11456. };
  11457. Engine.prototype._deleteProgram = function (program) {
  11458. if (program) {
  11459. program.__SPECTOR_rebuildProgram = null;
  11460. if (program.transformFeedback) {
  11461. this.deleteTransformFeedback(program.transformFeedback);
  11462. program.transformFeedback = null;
  11463. }
  11464. this._gl.deleteProgram(program);
  11465. }
  11466. };
  11467. /**
  11468. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  11469. * @param samplers An array of string used to represent textures
  11470. */
  11471. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  11472. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  11473. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  11474. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  11475. if (this._compiledEffects[name]) {
  11476. var compiledEffect = this._compiledEffects[name];
  11477. if (onCompiled && compiledEffect.isReady()) {
  11478. onCompiled(compiledEffect);
  11479. }
  11480. return compiledEffect;
  11481. }
  11482. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11483. effect._key = name;
  11484. this._compiledEffects[name] = effect;
  11485. return effect;
  11486. };
  11487. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11488. if (uniformsNames === void 0) { uniformsNames = []; }
  11489. if (samplers === void 0) { samplers = []; }
  11490. if (defines === void 0) { defines = ""; }
  11491. return this.createEffect({
  11492. vertex: "particles",
  11493. fragmentElement: fragmentName
  11494. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11495. };
  11496. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11497. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11498. context = context || this._gl;
  11499. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11500. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11501. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11502. };
  11503. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11504. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11505. context = context || this._gl;
  11506. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11507. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11508. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11509. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11510. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11511. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11512. return program;
  11513. };
  11514. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11515. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11516. var shaderProgram = context.createProgram();
  11517. if (!shaderProgram) {
  11518. throw new Error("Unable to create program");
  11519. }
  11520. context.attachShader(shaderProgram, vertexShader);
  11521. context.attachShader(shaderProgram, fragmentShader);
  11522. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11523. var transformFeedback = this.createTransformFeedback();
  11524. this.bindTransformFeedback(transformFeedback);
  11525. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11526. shaderProgram.transformFeedback = transformFeedback;
  11527. }
  11528. context.linkProgram(shaderProgram);
  11529. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11530. this.bindTransformFeedback(null);
  11531. }
  11532. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11533. if (!linked) {
  11534. context.validateProgram(shaderProgram);
  11535. var error = context.getProgramInfoLog(shaderProgram);
  11536. if (error) {
  11537. throw new Error(error);
  11538. }
  11539. }
  11540. context.deleteShader(vertexShader);
  11541. context.deleteShader(fragmentShader);
  11542. return shaderProgram;
  11543. };
  11544. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11545. var results = new Array();
  11546. for (var index = 0; index < uniformsNames.length; index++) {
  11547. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11548. }
  11549. return results;
  11550. };
  11551. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11552. var results = [];
  11553. for (var index = 0; index < attributesNames.length; index++) {
  11554. try {
  11555. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11556. }
  11557. catch (e) {
  11558. results.push(-1);
  11559. }
  11560. }
  11561. return results;
  11562. };
  11563. Engine.prototype.enableEffect = function (effect) {
  11564. if (!effect) {
  11565. return;
  11566. }
  11567. // Use program
  11568. this.bindSamplers(effect);
  11569. this._currentEffect = effect;
  11570. if (effect.onBind) {
  11571. effect.onBind(effect);
  11572. }
  11573. effect.onBindObservable.notifyObservers(effect);
  11574. };
  11575. Engine.prototype.setIntArray = function (uniform, array) {
  11576. if (!uniform)
  11577. return;
  11578. this._gl.uniform1iv(uniform, array);
  11579. };
  11580. Engine.prototype.setIntArray2 = function (uniform, array) {
  11581. if (!uniform || array.length % 2 !== 0)
  11582. return;
  11583. this._gl.uniform2iv(uniform, array);
  11584. };
  11585. Engine.prototype.setIntArray3 = function (uniform, array) {
  11586. if (!uniform || array.length % 3 !== 0)
  11587. return;
  11588. this._gl.uniform3iv(uniform, array);
  11589. };
  11590. Engine.prototype.setIntArray4 = function (uniform, array) {
  11591. if (!uniform || array.length % 4 !== 0)
  11592. return;
  11593. this._gl.uniform4iv(uniform, array);
  11594. };
  11595. Engine.prototype.setFloatArray = function (uniform, array) {
  11596. if (!uniform)
  11597. return;
  11598. this._gl.uniform1fv(uniform, array);
  11599. };
  11600. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11601. if (!uniform || array.length % 2 !== 0)
  11602. return;
  11603. this._gl.uniform2fv(uniform, array);
  11604. };
  11605. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11606. if (!uniform || array.length % 3 !== 0)
  11607. return;
  11608. this._gl.uniform3fv(uniform, array);
  11609. };
  11610. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11611. if (!uniform || array.length % 4 !== 0)
  11612. return;
  11613. this._gl.uniform4fv(uniform, array);
  11614. };
  11615. Engine.prototype.setArray = function (uniform, array) {
  11616. if (!uniform)
  11617. return;
  11618. this._gl.uniform1fv(uniform, array);
  11619. };
  11620. Engine.prototype.setArray2 = function (uniform, array) {
  11621. if (!uniform || array.length % 2 !== 0)
  11622. return;
  11623. this._gl.uniform2fv(uniform, array);
  11624. };
  11625. Engine.prototype.setArray3 = function (uniform, array) {
  11626. if (!uniform || array.length % 3 !== 0)
  11627. return;
  11628. this._gl.uniform3fv(uniform, array);
  11629. };
  11630. Engine.prototype.setArray4 = function (uniform, array) {
  11631. if (!uniform || array.length % 4 !== 0)
  11632. return;
  11633. this._gl.uniform4fv(uniform, array);
  11634. };
  11635. Engine.prototype.setMatrices = function (uniform, matrices) {
  11636. if (!uniform)
  11637. return;
  11638. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11639. };
  11640. Engine.prototype.setMatrix = function (uniform, matrix) {
  11641. if (!uniform)
  11642. return;
  11643. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11644. };
  11645. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11646. if (!uniform)
  11647. return;
  11648. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11649. };
  11650. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11651. if (!uniform)
  11652. return;
  11653. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11654. };
  11655. Engine.prototype.setInt = function (uniform, value) {
  11656. if (!uniform)
  11657. return;
  11658. this._gl.uniform1i(uniform, value);
  11659. };
  11660. Engine.prototype.setFloat = function (uniform, value) {
  11661. if (!uniform)
  11662. return;
  11663. this._gl.uniform1f(uniform, value);
  11664. };
  11665. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11666. if (!uniform)
  11667. return;
  11668. this._gl.uniform2f(uniform, x, y);
  11669. };
  11670. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11671. if (!uniform)
  11672. return;
  11673. this._gl.uniform3f(uniform, x, y, z);
  11674. };
  11675. Engine.prototype.setBool = function (uniform, bool) {
  11676. if (!uniform)
  11677. return;
  11678. this._gl.uniform1i(uniform, bool);
  11679. };
  11680. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11681. if (!uniform)
  11682. return;
  11683. this._gl.uniform4f(uniform, x, y, z, w);
  11684. };
  11685. Engine.prototype.setColor3 = function (uniform, color3) {
  11686. if (!uniform)
  11687. return;
  11688. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11689. };
  11690. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11691. if (!uniform)
  11692. return;
  11693. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11694. };
  11695. // States
  11696. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11697. if (zOffset === void 0) { zOffset = 0; }
  11698. if (reverseSide === void 0) { reverseSide = false; }
  11699. // Culling
  11700. if (this._depthCullingState.cull !== culling || force) {
  11701. this._depthCullingState.cull = culling;
  11702. }
  11703. // Cull face
  11704. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11705. if (this._depthCullingState.cullFace !== cullFace || force) {
  11706. this._depthCullingState.cullFace = cullFace;
  11707. }
  11708. // Z offset
  11709. this.setZOffset(zOffset);
  11710. // Front face
  11711. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11712. if (this._depthCullingState.frontFace !== frontFace || force) {
  11713. this._depthCullingState.frontFace = frontFace;
  11714. }
  11715. };
  11716. Engine.prototype.setZOffset = function (value) {
  11717. this._depthCullingState.zOffset = value;
  11718. };
  11719. Engine.prototype.getZOffset = function () {
  11720. return this._depthCullingState.zOffset;
  11721. };
  11722. Engine.prototype.setDepthBuffer = function (enable) {
  11723. this._depthCullingState.depthTest = enable;
  11724. };
  11725. Engine.prototype.getDepthWrite = function () {
  11726. return this._depthCullingState.depthMask;
  11727. };
  11728. Engine.prototype.setDepthWrite = function (enable) {
  11729. this._depthCullingState.depthMask = enable;
  11730. };
  11731. Engine.prototype.setColorWrite = function (enable) {
  11732. this._gl.colorMask(enable, enable, enable, enable);
  11733. this._colorWrite = enable;
  11734. };
  11735. Engine.prototype.getColorWrite = function () {
  11736. return this._colorWrite;
  11737. };
  11738. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11739. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11740. };
  11741. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11742. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11743. if (this._alphaMode === mode) {
  11744. return;
  11745. }
  11746. switch (mode) {
  11747. case Engine.ALPHA_DISABLE:
  11748. this._alphaState.alphaBlend = false;
  11749. break;
  11750. case Engine.ALPHA_PREMULTIPLIED:
  11751. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11752. this._alphaState.alphaBlend = true;
  11753. break;
  11754. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11755. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11756. this._alphaState.alphaBlend = true;
  11757. break;
  11758. case Engine.ALPHA_COMBINE:
  11759. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11760. this._alphaState.alphaBlend = true;
  11761. break;
  11762. case Engine.ALPHA_ONEONE:
  11763. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11764. this._alphaState.alphaBlend = true;
  11765. break;
  11766. case Engine.ALPHA_ADD:
  11767. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11768. this._alphaState.alphaBlend = true;
  11769. break;
  11770. case Engine.ALPHA_SUBTRACT:
  11771. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11772. this._alphaState.alphaBlend = true;
  11773. break;
  11774. case Engine.ALPHA_MULTIPLY:
  11775. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11776. this._alphaState.alphaBlend = true;
  11777. break;
  11778. case Engine.ALPHA_MAXIMIZED:
  11779. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11780. this._alphaState.alphaBlend = true;
  11781. break;
  11782. case Engine.ALPHA_INTERPOLATE:
  11783. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11784. this._alphaState.alphaBlend = true;
  11785. break;
  11786. case Engine.ALPHA_SCREENMODE:
  11787. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11788. this._alphaState.alphaBlend = true;
  11789. break;
  11790. }
  11791. if (!noDepthWriteChange) {
  11792. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11793. }
  11794. this._alphaMode = mode;
  11795. };
  11796. Engine.prototype.getAlphaMode = function () {
  11797. return this._alphaMode;
  11798. };
  11799. // Textures
  11800. Engine.prototype.wipeCaches = function (bruteForce) {
  11801. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11802. return;
  11803. }
  11804. this._currentEffect = null;
  11805. // 6/8/2017: deltakosh: Should not be required anymore.
  11806. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11807. if (bruteForce) {
  11808. this.resetTextureCache();
  11809. this._currentProgram = null;
  11810. this._stencilState.reset();
  11811. this._depthCullingState.reset();
  11812. this.setDepthFunctionToLessOrEqual();
  11813. this._alphaState.reset();
  11814. }
  11815. this._resetVertexBufferBinding();
  11816. this._cachedIndexBuffer = null;
  11817. this._cachedEffectForVertexBuffers = null;
  11818. this._unbindVertexArrayObject();
  11819. this.bindIndexBuffer(null);
  11820. };
  11821. /**
  11822. * Set the compressed texture format to use, based on the formats you have, and the formats
  11823. * supported by the hardware / browser.
  11824. *
  11825. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11826. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11827. * to API arguments needed to compressed textures. This puts the burden on the container
  11828. * generator to house the arcane code for determining these for current & future formats.
  11829. *
  11830. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11831. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11832. *
  11833. * Note: The result of this call is not taken into account when a texture is base64.
  11834. *
  11835. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11836. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11837. *
  11838. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11839. * @returns The extension selected.
  11840. */
  11841. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11842. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11843. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11844. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11845. return this._textureFormatInUse = this._texturesSupported[i];
  11846. }
  11847. }
  11848. }
  11849. // actively set format to nothing, to allow this to be called more than once
  11850. // and possibly fail the 2nd time
  11851. this._textureFormatInUse = null;
  11852. return null;
  11853. };
  11854. Engine.prototype._createTexture = function () {
  11855. var texture = this._gl.createTexture();
  11856. if (!texture) {
  11857. throw new Error("Unable to create texture");
  11858. }
  11859. return texture;
  11860. };
  11861. /**
  11862. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11863. * @param {string} urlArg- This contains one of the following:
  11864. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11865. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11866. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11867. *
  11868. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11869. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11870. * @param {Scene} scene- Needed for loading to the correct scene.
  11871. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11872. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11873. * @param {callback} onError- Optional callback to be called upon failure.
  11874. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11875. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11876. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11877. *
  11878. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11879. */
  11880. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11881. var _this = this;
  11882. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11883. if (onLoad === void 0) { onLoad = null; }
  11884. if (onError === void 0) { onError = null; }
  11885. if (buffer === void 0) { buffer = null; }
  11886. if (fallBack === void 0) { fallBack = null; }
  11887. if (format === void 0) { format = null; }
  11888. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11889. var fromData = url.substr(0, 5) === "data:";
  11890. var fromBlob = url.substr(0, 5) === "blob:";
  11891. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11892. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11893. // establish the file extension, if possible
  11894. var lastDot = url.lastIndexOf('.');
  11895. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11896. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  11897. var isTGA = (extension.indexOf(".tga") === 0);
  11898. // determine if a ktx file should be substituted
  11899. var isKTX = false;
  11900. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11901. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11902. isKTX = true;
  11903. }
  11904. if (scene) {
  11905. scene._addPendingData(texture);
  11906. }
  11907. texture.url = url;
  11908. texture.generateMipMaps = !noMipmap;
  11909. texture.samplingMode = samplingMode;
  11910. texture.invertY = invertY;
  11911. if (!this._doNotHandleContextLost) {
  11912. // Keep a link to the buffer only if we plan to handle context lost
  11913. texture._buffer = buffer;
  11914. }
  11915. var onLoadObserver = null;
  11916. if (onLoad && !fallBack) {
  11917. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11918. }
  11919. if (!fallBack)
  11920. this._internalTexturesCache.push(texture);
  11921. var onerror = function (message, exception) {
  11922. if (scene) {
  11923. scene._removePendingData(texture);
  11924. }
  11925. if (onLoadObserver) {
  11926. texture.onLoadedObservable.remove(onLoadObserver);
  11927. }
  11928. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11929. if (isKTX) {
  11930. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11931. }
  11932. else if (BABYLON.Tools.UseFallbackTexture) {
  11933. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11934. }
  11935. if (onError) {
  11936. onError(message || "Unknown error", exception);
  11937. }
  11938. };
  11939. var callback = null;
  11940. // processing for non-image formats
  11941. if (isKTX || isTGA || isDDS) {
  11942. if (isKTX) {
  11943. callback = function (data) {
  11944. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11945. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11946. ktx.uploadLevels(_this._gl, !noMipmap);
  11947. return false;
  11948. }, samplingMode);
  11949. };
  11950. }
  11951. else if (isTGA) {
  11952. callback = function (arrayBuffer) {
  11953. var data = new Uint8Array(arrayBuffer);
  11954. var header = BABYLON.TGATools.GetTGAHeader(data);
  11955. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11956. BABYLON.TGATools.UploadContent(_this._gl, data);
  11957. return false;
  11958. }, samplingMode);
  11959. };
  11960. }
  11961. else if (isDDS) {
  11962. callback = function (data) {
  11963. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11964. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11965. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11966. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11967. return false;
  11968. }, samplingMode);
  11969. };
  11970. }
  11971. if (!buffer) {
  11972. this._loadFile(url, function (data) {
  11973. if (callback) {
  11974. callback(data);
  11975. }
  11976. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11977. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11978. });
  11979. }
  11980. else {
  11981. if (callback) {
  11982. callback(buffer);
  11983. }
  11984. }
  11985. // image format processing
  11986. }
  11987. else {
  11988. var onload = function (img) {
  11989. if (fromBlob && !_this._doNotHandleContextLost) {
  11990. // We need to store the image if we need to rebuild the texture
  11991. // in case of a webgl context lost
  11992. texture._buffer = img;
  11993. }
  11994. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11995. var gl = _this._gl;
  11996. var isPot = (img.width === potWidth && img.height === potHeight);
  11997. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11998. if (isPot) {
  11999. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12000. return false;
  12001. }
  12002. // Using shaders to rescale because canvas.drawImage is lossy
  12003. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12004. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12005. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12006. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12007. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12008. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12009. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12010. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12011. _this._releaseTexture(source);
  12012. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12013. continuationCallback();
  12014. });
  12015. return true;
  12016. }, samplingMode);
  12017. };
  12018. if (!fromData || isBase64)
  12019. if (buffer instanceof HTMLImageElement) {
  12020. onload(buffer);
  12021. }
  12022. else {
  12023. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12024. }
  12025. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12026. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12027. else
  12028. onload(buffer);
  12029. }
  12030. return texture;
  12031. };
  12032. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12033. var _this = this;
  12034. var rtt = this.createRenderTargetTexture({
  12035. width: destination.width,
  12036. height: destination.height,
  12037. }, {
  12038. generateMipMaps: false,
  12039. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12040. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12041. generateDepthBuffer: false,
  12042. generateStencilBuffer: false
  12043. });
  12044. if (!this._rescalePostProcess) {
  12045. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12046. }
  12047. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12048. _this._rescalePostProcess.onApply = function (effect) {
  12049. effect._bindTexture("textureSampler", source);
  12050. };
  12051. var hostingScene = scene;
  12052. if (!hostingScene) {
  12053. hostingScene = _this.scenes[_this.scenes.length - 1];
  12054. }
  12055. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12056. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12057. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12058. _this.unBindFramebuffer(rtt);
  12059. _this._releaseTexture(rtt);
  12060. if (onComplete) {
  12061. onComplete();
  12062. }
  12063. });
  12064. };
  12065. Engine.prototype._getInternalFormat = function (format) {
  12066. var internalFormat = this._gl.RGBA;
  12067. switch (format) {
  12068. case Engine.TEXTUREFORMAT_ALPHA:
  12069. internalFormat = this._gl.ALPHA;
  12070. break;
  12071. case Engine.TEXTUREFORMAT_LUMINANCE:
  12072. internalFormat = this._gl.LUMINANCE;
  12073. break;
  12074. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12075. internalFormat = this._gl.LUMINANCE_ALPHA;
  12076. break;
  12077. case Engine.TEXTUREFORMAT_RGB:
  12078. internalFormat = this._gl.RGB;
  12079. break;
  12080. case Engine.TEXTUREFORMAT_RGBA:
  12081. internalFormat = this._gl.RGBA;
  12082. break;
  12083. }
  12084. return internalFormat;
  12085. };
  12086. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12087. if (compression === void 0) { compression = null; }
  12088. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12089. if (!texture) {
  12090. return;
  12091. }
  12092. var internalFormat = this._getInternalFormat(format);
  12093. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12094. var textureType = this._getWebGLTextureType(type);
  12095. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12096. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12097. if (!this._doNotHandleContextLost) {
  12098. texture._bufferView = data;
  12099. texture.format = format;
  12100. texture.type = type;
  12101. texture.invertY = invertY;
  12102. texture._compression = compression;
  12103. }
  12104. if (texture.width % 4 !== 0) {
  12105. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12106. }
  12107. if (compression && data) {
  12108. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12109. }
  12110. else {
  12111. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12112. }
  12113. if (texture.generateMipMaps) {
  12114. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12115. }
  12116. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12117. // this.resetTextureCache();
  12118. texture.isReady = true;
  12119. };
  12120. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12121. if (compression === void 0) { compression = null; }
  12122. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12123. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12124. texture.baseWidth = width;
  12125. texture.baseHeight = height;
  12126. texture.width = width;
  12127. texture.height = height;
  12128. texture.format = format;
  12129. texture.generateMipMaps = generateMipMaps;
  12130. texture.samplingMode = samplingMode;
  12131. texture.invertY = invertY;
  12132. texture._compression = compression;
  12133. texture.type = type;
  12134. if (!this._doNotHandleContextLost) {
  12135. texture._bufferView = data;
  12136. }
  12137. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12138. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12139. // Filters
  12140. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12141. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12142. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12143. if (generateMipMaps) {
  12144. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12145. }
  12146. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12147. this._internalTexturesCache.push(texture);
  12148. return texture;
  12149. };
  12150. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12151. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12152. texture.baseWidth = width;
  12153. texture.baseHeight = height;
  12154. if (generateMipMaps) {
  12155. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12156. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12157. }
  12158. // this.resetTextureCache();
  12159. texture.width = width;
  12160. texture.height = height;
  12161. texture.isReady = false;
  12162. texture.generateMipMaps = generateMipMaps;
  12163. texture.samplingMode = samplingMode;
  12164. this.updateTextureSamplingMode(samplingMode, texture);
  12165. this._internalTexturesCache.push(texture);
  12166. return texture;
  12167. };
  12168. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12169. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12170. if (texture.isCube) {
  12171. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12172. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12173. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12174. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12175. }
  12176. else if (texture.is3D) {
  12177. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12178. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12179. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12180. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12181. }
  12182. else {
  12183. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12184. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12185. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12186. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12187. }
  12188. texture.samplingMode = samplingMode;
  12189. };
  12190. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12191. if (premulAlpha === void 0) { premulAlpha = false; }
  12192. if (!texture) {
  12193. return;
  12194. }
  12195. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12196. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12197. if (premulAlpha) {
  12198. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12199. }
  12200. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12201. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12202. if (texture.generateMipMaps) {
  12203. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12204. }
  12205. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12206. if (premulAlpha) {
  12207. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12208. }
  12209. texture.isReady = true;
  12210. };
  12211. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12212. if (!texture || texture._isDisabled) {
  12213. return;
  12214. }
  12215. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12216. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12217. try {
  12218. // Testing video texture support
  12219. if (this._videoTextureSupported === undefined) {
  12220. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12221. if (this._gl.getError() !== 0) {
  12222. this._videoTextureSupported = false;
  12223. }
  12224. else {
  12225. this._videoTextureSupported = true;
  12226. }
  12227. }
  12228. // Copy video through the current working canvas if video texture is not supported
  12229. if (!this._videoTextureSupported) {
  12230. if (!texture._workingCanvas) {
  12231. texture._workingCanvas = document.createElement("canvas");
  12232. var context = texture._workingCanvas.getContext("2d");
  12233. if (!context) {
  12234. throw new Error("Unable to get 2d context");
  12235. }
  12236. texture._workingContext = context;
  12237. texture._workingCanvas.width = texture.width;
  12238. texture._workingCanvas.height = texture.height;
  12239. }
  12240. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  12241. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  12242. }
  12243. else {
  12244. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12245. }
  12246. if (texture.generateMipMaps) {
  12247. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12248. }
  12249. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12250. // this.resetTextureCache();
  12251. texture.isReady = true;
  12252. }
  12253. catch (ex) {
  12254. // Something unexpected
  12255. // Let's disable the texture
  12256. texture._isDisabled = true;
  12257. }
  12258. };
  12259. Engine.prototype.createRenderTargetTexture = function (size, options) {
  12260. var fullOptions = new RenderTargetCreationOptions();
  12261. if (options !== undefined && typeof options === "object") {
  12262. fullOptions.generateMipMaps = options.generateMipMaps;
  12263. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12264. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  12265. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  12266. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  12267. }
  12268. else {
  12269. fullOptions.generateMipMaps = options;
  12270. fullOptions.generateDepthBuffer = true;
  12271. fullOptions.generateStencilBuffer = false;
  12272. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12273. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12274. }
  12275. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12276. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12277. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12278. }
  12279. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12280. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12281. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12282. }
  12283. var gl = this._gl;
  12284. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12285. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12286. var width = size.width || size;
  12287. var height = size.height || size;
  12288. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  12289. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12290. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12291. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12292. }
  12293. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12294. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12296. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12297. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  12298. // Create the framebuffer
  12299. var framebuffer = gl.createFramebuffer();
  12300. this.bindUnboundFramebuffer(framebuffer);
  12301. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12302. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  12303. if (fullOptions.generateMipMaps) {
  12304. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12305. }
  12306. // Unbind
  12307. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12308. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12309. this.bindUnboundFramebuffer(null);
  12310. texture._framebuffer = framebuffer;
  12311. texture.baseWidth = width;
  12312. texture.baseHeight = height;
  12313. texture.width = width;
  12314. texture.height = height;
  12315. texture.isReady = true;
  12316. texture.samples = 1;
  12317. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  12318. texture.samplingMode = fullOptions.samplingMode;
  12319. texture.type = fullOptions.type;
  12320. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  12321. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  12322. // this.resetTextureCache();
  12323. this._internalTexturesCache.push(texture);
  12324. return texture;
  12325. };
  12326. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  12327. var generateMipMaps = false;
  12328. var generateDepthBuffer = true;
  12329. var generateStencilBuffer = false;
  12330. var generateDepthTexture = false;
  12331. var textureCount = 1;
  12332. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  12333. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12334. var types = [], samplingModes = [];
  12335. if (options !== undefined) {
  12336. generateMipMaps = options.generateMipMaps;
  12337. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12338. generateStencilBuffer = options.generateStencilBuffer;
  12339. generateDepthTexture = options.generateDepthTexture;
  12340. textureCount = options.textureCount || 1;
  12341. if (options.types) {
  12342. types = options.types;
  12343. }
  12344. if (options.samplingModes) {
  12345. samplingModes = options.samplingModes;
  12346. }
  12347. }
  12348. var gl = this._gl;
  12349. // Create the framebuffer
  12350. var framebuffer = gl.createFramebuffer();
  12351. this.bindUnboundFramebuffer(framebuffer);
  12352. var width = size.width || size;
  12353. var height = size.height || size;
  12354. var textures = [];
  12355. var attachments = [];
  12356. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  12357. for (var i = 0; i < textureCount; i++) {
  12358. var samplingMode = samplingModes[i] || defaultSamplingMode;
  12359. var type = types[i] || defaultType;
  12360. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12361. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12362. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12363. }
  12364. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12365. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12366. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12367. }
  12368. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12369. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12370. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12371. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12372. }
  12373. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12374. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12375. textures.push(texture);
  12376. attachments.push(attachment);
  12377. gl.activeTexture(gl["TEXTURE" + i]);
  12378. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  12379. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12380. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12381. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12382. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12383. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12384. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12385. if (generateMipMaps) {
  12386. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12387. }
  12388. // Unbind
  12389. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12390. texture._framebuffer = framebuffer;
  12391. texture._depthStencilBuffer = depthStencilBuffer;
  12392. texture.baseWidth = width;
  12393. texture.baseHeight = height;
  12394. texture.width = width;
  12395. texture.height = height;
  12396. texture.isReady = true;
  12397. texture.samples = 1;
  12398. texture.generateMipMaps = generateMipMaps;
  12399. texture.samplingMode = samplingMode;
  12400. texture.type = type;
  12401. texture._generateDepthBuffer = generateDepthBuffer;
  12402. texture._generateStencilBuffer = generateStencilBuffer;
  12403. texture._attachments = attachments;
  12404. this._internalTexturesCache.push(texture);
  12405. }
  12406. if (generateDepthTexture && this._caps.depthTextureExtension) {
  12407. // Depth texture
  12408. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12409. gl.activeTexture(gl.TEXTURE0);
  12410. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  12411. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12412. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  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.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  12416. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  12417. depthTexture._framebuffer = framebuffer;
  12418. depthTexture.baseWidth = width;
  12419. depthTexture.baseHeight = height;
  12420. depthTexture.width = width;
  12421. depthTexture.height = height;
  12422. depthTexture.isReady = true;
  12423. depthTexture.samples = 1;
  12424. depthTexture.generateMipMaps = generateMipMaps;
  12425. depthTexture.samplingMode = gl.NEAREST;
  12426. depthTexture._generateDepthBuffer = generateDepthBuffer;
  12427. depthTexture._generateStencilBuffer = generateStencilBuffer;
  12428. textures.push(depthTexture);
  12429. this._internalTexturesCache.push(depthTexture);
  12430. }
  12431. gl.drawBuffers(attachments);
  12432. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12433. this.bindUnboundFramebuffer(null);
  12434. this.resetTextureCache();
  12435. return textures;
  12436. };
  12437. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  12438. if (samples === void 0) { samples = 1; }
  12439. var depthStencilBuffer = null;
  12440. var gl = this._gl;
  12441. // Create the depth/stencil buffer
  12442. if (generateStencilBuffer) {
  12443. depthStencilBuffer = gl.createRenderbuffer();
  12444. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12445. if (samples > 1) {
  12446. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  12447. }
  12448. else {
  12449. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  12450. }
  12451. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12452. }
  12453. else if (generateDepthBuffer) {
  12454. depthStencilBuffer = gl.createRenderbuffer();
  12455. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12456. if (samples > 1) {
  12457. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  12458. }
  12459. else {
  12460. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  12461. }
  12462. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12463. }
  12464. return depthStencilBuffer;
  12465. };
  12466. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  12467. if (this.webGLVersion < 2 || !texture) {
  12468. return 1;
  12469. }
  12470. if (texture.samples === samples) {
  12471. return samples;
  12472. }
  12473. var gl = this._gl;
  12474. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12475. // Dispose previous render buffers
  12476. if (texture._depthStencilBuffer) {
  12477. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12478. texture._depthStencilBuffer = null;
  12479. }
  12480. if (texture._MSAAFramebuffer) {
  12481. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12482. texture._MSAAFramebuffer = null;
  12483. }
  12484. if (texture._MSAARenderBuffer) {
  12485. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12486. texture._MSAARenderBuffer = null;
  12487. }
  12488. if (samples > 1) {
  12489. var framebuffer = gl.createFramebuffer();
  12490. if (!framebuffer) {
  12491. throw new Error("Unable to create multi sampled framebuffer");
  12492. }
  12493. texture._MSAAFramebuffer = framebuffer;
  12494. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12495. var colorRenderbuffer = gl.createRenderbuffer();
  12496. if (!colorRenderbuffer) {
  12497. throw new Error("Unable to create multi sampled framebuffer");
  12498. }
  12499. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12500. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12501. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12502. texture._MSAARenderBuffer = colorRenderbuffer;
  12503. }
  12504. else {
  12505. this.bindUnboundFramebuffer(texture._framebuffer);
  12506. }
  12507. texture.samples = samples;
  12508. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12509. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12510. this.bindUnboundFramebuffer(null);
  12511. return samples;
  12512. };
  12513. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12514. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12515. return 1;
  12516. }
  12517. if (textures[0].samples === samples) {
  12518. return samples;
  12519. }
  12520. var gl = this._gl;
  12521. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12522. // Dispose previous render buffers
  12523. if (textures[0]._depthStencilBuffer) {
  12524. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12525. textures[0]._depthStencilBuffer = null;
  12526. }
  12527. if (textures[0]._MSAAFramebuffer) {
  12528. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12529. textures[0]._MSAAFramebuffer = null;
  12530. }
  12531. for (var i = 0; i < textures.length; i++) {
  12532. if (textures[i]._MSAARenderBuffer) {
  12533. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12534. textures[i]._MSAARenderBuffer = null;
  12535. }
  12536. }
  12537. if (samples > 1) {
  12538. var framebuffer = gl.createFramebuffer();
  12539. if (!framebuffer) {
  12540. throw new Error("Unable to create multi sampled framebuffer");
  12541. }
  12542. this.bindUnboundFramebuffer(framebuffer);
  12543. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12544. var attachments = [];
  12545. for (var i = 0; i < textures.length; i++) {
  12546. var texture = textures[i];
  12547. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12548. var colorRenderbuffer = gl.createRenderbuffer();
  12549. if (!colorRenderbuffer) {
  12550. throw new Error("Unable to create multi sampled framebuffer");
  12551. }
  12552. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12553. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12554. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12555. texture._MSAAFramebuffer = framebuffer;
  12556. texture._MSAARenderBuffer = colorRenderbuffer;
  12557. texture.samples = samples;
  12558. texture._depthStencilBuffer = depthStencilBuffer;
  12559. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12560. attachments.push(attachment);
  12561. }
  12562. gl.drawBuffers(attachments);
  12563. }
  12564. else {
  12565. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12566. }
  12567. this.bindUnboundFramebuffer(null);
  12568. return samples;
  12569. };
  12570. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12571. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12572. };
  12573. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12574. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12575. };
  12576. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12577. var gl = this._gl;
  12578. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12579. var generateMipMaps = true;
  12580. var generateDepthBuffer = true;
  12581. var generateStencilBuffer = false;
  12582. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12583. if (options !== undefined) {
  12584. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12585. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12586. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12587. if (options.samplingMode !== undefined) {
  12588. samplingMode = options.samplingMode;
  12589. }
  12590. }
  12591. texture.isCube = true;
  12592. texture.generateMipMaps = generateMipMaps;
  12593. texture.samples = 1;
  12594. texture.samplingMode = samplingMode;
  12595. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12596. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12597. for (var face = 0; face < 6; face++) {
  12598. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12599. }
  12600. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12604. // Create the framebuffer
  12605. var framebuffer = gl.createFramebuffer();
  12606. this.bindUnboundFramebuffer(framebuffer);
  12607. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12608. // Mipmaps
  12609. if (texture.generateMipMaps) {
  12610. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12611. }
  12612. // Unbind
  12613. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12614. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12615. this.bindUnboundFramebuffer(null);
  12616. texture._framebuffer = framebuffer;
  12617. texture.width = size;
  12618. texture.height = size;
  12619. texture.isReady = true;
  12620. //this.resetTextureCache();
  12621. this._internalTexturesCache.push(texture);
  12622. return texture;
  12623. };
  12624. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12625. var _this = this;
  12626. if (onLoad === void 0) { onLoad = null; }
  12627. if (onError === void 0) { onError = null; }
  12628. if (forcedExtension === void 0) { forcedExtension = null; }
  12629. var callback = function (loadData) {
  12630. if (!loadData) {
  12631. if (onLoad) {
  12632. onLoad(null);
  12633. }
  12634. return;
  12635. }
  12636. var texture = loadData.texture;
  12637. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12638. texture._lodGenerationScale = scale;
  12639. texture._lodGenerationOffset = offset;
  12640. if (_this._caps.textureLOD) {
  12641. // Do not add extra process if texture lod is supported.
  12642. if (onLoad) {
  12643. onLoad(texture);
  12644. }
  12645. return;
  12646. }
  12647. var mipSlices = 3;
  12648. var gl = _this._gl;
  12649. var width = loadData.width;
  12650. if (!width) {
  12651. return;
  12652. }
  12653. var textures = [];
  12654. for (var i = 0; i < mipSlices; i++) {
  12655. //compute LOD from even spacing in smoothness (matching shader calculation)
  12656. var smoothness = i / (mipSlices - 1);
  12657. var roughness = 1 - smoothness;
  12658. var minLODIndex = offset; // roughness = 0
  12659. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12660. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12661. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12662. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12663. glTextureFromLod.isCube = true;
  12664. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12665. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12666. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12667. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12668. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12669. if (loadData.isDDS) {
  12670. var info = loadData.info;
  12671. var data = loadData.data;
  12672. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12673. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12674. }
  12675. else {
  12676. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12677. }
  12678. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12679. // Wrap in a base texture for easy binding.
  12680. var lodTexture = new BABYLON.BaseTexture(scene);
  12681. lodTexture.isCube = true;
  12682. lodTexture._texture = glTextureFromLod;
  12683. glTextureFromLod.isReady = true;
  12684. textures.push(lodTexture);
  12685. }
  12686. texture._lodTextureHigh = textures[2];
  12687. texture._lodTextureMid = textures[1];
  12688. texture._lodTextureLow = textures[0];
  12689. if (onLoad) {
  12690. onLoad(texture);
  12691. }
  12692. };
  12693. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12694. };
  12695. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12696. var _this = this;
  12697. if (onLoad === void 0) { onLoad = null; }
  12698. if (onError === void 0) { onError = null; }
  12699. if (forcedExtension === void 0) { forcedExtension = null; }
  12700. var gl = this._gl;
  12701. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12702. texture.isCube = true;
  12703. texture.url = rootUrl;
  12704. texture.generateMipMaps = !noMipmap;
  12705. if (!this._doNotHandleContextLost) {
  12706. texture._extension = forcedExtension;
  12707. texture._files = files;
  12708. }
  12709. var isKTX = false;
  12710. var isDDS = false;
  12711. var lastDot = rootUrl.lastIndexOf('.');
  12712. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12713. if (this._textureFormatInUse) {
  12714. extension = this._textureFormatInUse;
  12715. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12716. isKTX = true;
  12717. }
  12718. else {
  12719. isDDS = (extension === ".dds");
  12720. }
  12721. var onerror = function (request, exception) {
  12722. if (onError && request) {
  12723. onError(request.status + " " + request.statusText, exception);
  12724. }
  12725. };
  12726. if (isKTX) {
  12727. this._loadFile(rootUrl, function (data) {
  12728. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12729. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12730. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12731. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12732. ktx.uploadLevels(_this._gl, !noMipmap);
  12733. _this.setCubeMapTextureParams(gl, loadMipmap);
  12734. texture.width = ktx.pixelWidth;
  12735. texture.height = ktx.pixelHeight;
  12736. texture.isReady = true;
  12737. }, undefined, undefined, true, onerror);
  12738. }
  12739. else if (isDDS) {
  12740. if (files && files.length === 6) {
  12741. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12742. var info;
  12743. var loadMipmap = false;
  12744. var width = 0;
  12745. for (var index = 0; index < imgs.length; index++) {
  12746. var data = imgs[index];
  12747. info = BABYLON.DDSTools.GetDDSInfo(data);
  12748. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12749. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12750. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12751. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12752. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12753. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12754. }
  12755. texture.width = info.width;
  12756. texture.height = info.height;
  12757. texture.type = info.textureType;
  12758. width = info.width;
  12759. }
  12760. _this.setCubeMapTextureParams(gl, loadMipmap);
  12761. texture.isReady = true;
  12762. if (onLoad) {
  12763. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12764. }
  12765. }, files, onError);
  12766. }
  12767. else {
  12768. this._loadFile(rootUrl, function (data) {
  12769. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12770. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12771. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12772. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12773. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12774. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12775. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12776. }
  12777. _this.setCubeMapTextureParams(gl, loadMipmap);
  12778. texture.width = info.width;
  12779. texture.height = info.height;
  12780. texture.isReady = true;
  12781. texture.type = info.textureType;
  12782. if (onLoad) {
  12783. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12784. }
  12785. }, undefined, undefined, true, onerror);
  12786. }
  12787. }
  12788. else {
  12789. if (!files) {
  12790. throw new Error("Cannot load cubemap because files were not defined");
  12791. }
  12792. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12793. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12794. var height = width;
  12795. _this._prepareWorkingCanvas();
  12796. if (!_this._workingCanvas || !_this._workingContext) {
  12797. return;
  12798. }
  12799. _this._workingCanvas.width = width;
  12800. _this._workingCanvas.height = height;
  12801. var faces = [
  12802. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12803. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12804. ];
  12805. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12806. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12807. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12808. for (var index = 0; index < faces.length; index++) {
  12809. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12810. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12811. }
  12812. if (!noMipmap) {
  12813. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12814. }
  12815. _this.setCubeMapTextureParams(gl, !noMipmap);
  12816. texture.width = width;
  12817. texture.height = height;
  12818. texture.isReady = true;
  12819. if (format) {
  12820. texture.format = format;
  12821. }
  12822. texture.onLoadedObservable.notifyObservers(texture);
  12823. texture.onLoadedObservable.clear();
  12824. if (onLoad) {
  12825. onLoad();
  12826. }
  12827. }, files, onError);
  12828. }
  12829. this._internalTexturesCache.push(texture);
  12830. return texture;
  12831. };
  12832. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12833. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12835. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12836. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12837. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12838. // this.resetTextureCache();
  12839. };
  12840. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12841. if (compression === void 0) { compression = null; }
  12842. if (level === void 0) { level = 0; }
  12843. texture._bufferViewArray = data;
  12844. texture.format = format;
  12845. texture.type = type;
  12846. texture.invertY = invertY;
  12847. texture._compression = compression;
  12848. var gl = this._gl;
  12849. var textureType = this._getWebGLTextureType(type);
  12850. var internalFormat = this._getInternalFormat(format);
  12851. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12852. var needConversion = false;
  12853. if (internalFormat === gl.RGB) {
  12854. internalFormat = gl.RGBA;
  12855. needConversion = true;
  12856. }
  12857. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12858. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12859. if (texture.width % 4 !== 0) {
  12860. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12861. }
  12862. // Data are known to be in +X +Y +Z -X -Y -Z
  12863. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12864. var faceData = data[faceIndex];
  12865. if (compression) {
  12866. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12867. }
  12868. else {
  12869. if (needConversion) {
  12870. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12871. }
  12872. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12873. }
  12874. }
  12875. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12876. if (isPot && texture.generateMipMaps && level === 0) {
  12877. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12878. }
  12879. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12880. // this.resetTextureCache();
  12881. texture.isReady = true;
  12882. };
  12883. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12884. if (compression === void 0) { compression = null; }
  12885. var gl = this._gl;
  12886. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12887. texture.isCube = true;
  12888. texture.generateMipMaps = generateMipMaps;
  12889. texture.format = format;
  12890. texture.type = type;
  12891. if (!this._doNotHandleContextLost) {
  12892. texture._bufferViewArray = data;
  12893. }
  12894. var textureType = this._getWebGLTextureType(type);
  12895. var internalFormat = this._getInternalFormat(format);
  12896. if (internalFormat === gl.RGB) {
  12897. internalFormat = gl.RGBA;
  12898. }
  12899. var width = size;
  12900. var height = width;
  12901. texture.width = width;
  12902. texture.height = height;
  12903. // Double check on POT to generate Mips.
  12904. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12905. if (!isPot) {
  12906. generateMipMaps = false;
  12907. }
  12908. // Upload data if needed. The texture won't be ready until then.
  12909. if (data) {
  12910. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12911. }
  12912. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12913. // Filters
  12914. if (data && generateMipMaps) {
  12915. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12916. }
  12917. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12918. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12919. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12920. }
  12921. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12922. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12923. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12924. }
  12925. else {
  12926. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12927. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12929. }
  12930. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12931. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12932. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12933. return texture;
  12934. };
  12935. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12936. var _this = this;
  12937. if (onLoad === void 0) { onLoad = null; }
  12938. if (onError === void 0) { onError = null; }
  12939. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12940. if (invertY === void 0) { invertY = false; }
  12941. var gl = this._gl;
  12942. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12943. scene._addPendingData(texture);
  12944. texture.url = url;
  12945. this._internalTexturesCache.push(texture);
  12946. var onerror = function (request, exception) {
  12947. scene._removePendingData(texture);
  12948. if (onError && request) {
  12949. onError(request.status + " " + request.statusText, exception);
  12950. }
  12951. };
  12952. var internalCallback = function (data) {
  12953. var width = texture.width;
  12954. var faceDataArrays = callback(data);
  12955. if (!faceDataArrays) {
  12956. return;
  12957. }
  12958. if (mipmmapGenerator) {
  12959. var textureType = _this._getWebGLTextureType(type);
  12960. var internalFormat = _this._getInternalFormat(format);
  12961. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12962. var needConversion = false;
  12963. if (internalFormat === gl.RGB) {
  12964. internalFormat = gl.RGBA;
  12965. needConversion = true;
  12966. }
  12967. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12968. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12969. var mipData = mipmmapGenerator(faceDataArrays);
  12970. for (var level = 0; level < mipData.length; level++) {
  12971. var mipSize = width >> level;
  12972. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12973. var mipFaceData = mipData[level][faceIndex];
  12974. if (needConversion) {
  12975. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12976. }
  12977. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12978. }
  12979. }
  12980. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12981. }
  12982. else {
  12983. texture.generateMipMaps = !noMipmap;
  12984. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12985. }
  12986. texture.isReady = true;
  12987. // this.resetTextureCache();
  12988. scene._removePendingData(texture);
  12989. if (onLoad) {
  12990. onLoad();
  12991. }
  12992. };
  12993. this._loadFile(url, function (data) {
  12994. internalCallback(data);
  12995. }, undefined, scene.database, true, onerror);
  12996. return texture;
  12997. };
  12998. ;
  12999. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13000. if (compression === void 0) { compression = null; }
  13001. var internalFormat = this._getInternalFormat(format);
  13002. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13003. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13004. if (!this._doNotHandleContextLost) {
  13005. texture._bufferView = data;
  13006. texture.format = format;
  13007. texture.invertY = invertY;
  13008. texture._compression = compression;
  13009. }
  13010. if (texture.width % 4 !== 0) {
  13011. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13012. }
  13013. if (compression && data) {
  13014. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13015. }
  13016. else {
  13017. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13018. }
  13019. if (texture.generateMipMaps) {
  13020. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13021. }
  13022. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13023. // this.resetTextureCache();
  13024. texture.isReady = true;
  13025. };
  13026. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13027. if (compression === void 0) { compression = null; }
  13028. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13029. texture.baseWidth = width;
  13030. texture.baseHeight = height;
  13031. texture.baseDepth = depth;
  13032. texture.width = width;
  13033. texture.height = height;
  13034. texture.depth = depth;
  13035. texture.format = format;
  13036. texture.generateMipMaps = generateMipMaps;
  13037. texture.samplingMode = samplingMode;
  13038. texture.is3D = true;
  13039. if (!this._doNotHandleContextLost) {
  13040. texture._bufferView = data;
  13041. }
  13042. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13043. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13044. // Filters
  13045. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13046. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13047. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13048. if (generateMipMaps) {
  13049. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13050. }
  13051. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13052. this._internalTexturesCache.push(texture);
  13053. return texture;
  13054. };
  13055. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13056. var gl = this._gl;
  13057. if (!gl) {
  13058. return;
  13059. }
  13060. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13061. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13062. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13063. if (!noMipmap && !isCompressed) {
  13064. gl.generateMipmap(gl.TEXTURE_2D);
  13065. }
  13066. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13067. // this.resetTextureCache();
  13068. if (scene) {
  13069. scene._removePendingData(texture);
  13070. }
  13071. texture.onLoadedObservable.notifyObservers(texture);
  13072. texture.onLoadedObservable.clear();
  13073. };
  13074. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13075. var _this = this;
  13076. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13077. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13078. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13079. var gl = this._gl;
  13080. if (!gl) {
  13081. return;
  13082. }
  13083. if (!texture._webGLTexture) {
  13084. // this.resetTextureCache();
  13085. if (scene) {
  13086. scene._removePendingData(texture);
  13087. }
  13088. return;
  13089. }
  13090. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13091. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13092. texture.baseWidth = width;
  13093. texture.baseHeight = height;
  13094. texture.width = potWidth;
  13095. texture.height = potHeight;
  13096. texture.isReady = true;
  13097. if (processFunction(potWidth, potHeight, function () {
  13098. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13099. })) {
  13100. // Returning as texture needs extra async steps
  13101. return;
  13102. }
  13103. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13104. };
  13105. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13106. // Create new RGBA data container.
  13107. var rgbaData;
  13108. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13109. rgbaData = new Float32Array(width * height * 4);
  13110. }
  13111. else {
  13112. rgbaData = new Uint32Array(width * height * 4);
  13113. }
  13114. // Convert each pixel.
  13115. for (var x = 0; x < width; x++) {
  13116. for (var y = 0; y < height; y++) {
  13117. var index = (y * width + x) * 3;
  13118. var newIndex = (y * width + x) * 4;
  13119. // Map Old Value to new value.
  13120. rgbaData[newIndex + 0] = rgbData[index + 0];
  13121. rgbaData[newIndex + 1] = rgbData[index + 1];
  13122. rgbaData[newIndex + 2] = rgbData[index + 2];
  13123. // Add fully opaque alpha channel.
  13124. rgbaData[newIndex + 3] = 1;
  13125. }
  13126. }
  13127. return rgbaData;
  13128. };
  13129. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13130. var gl = this._gl;
  13131. if (texture._framebuffer) {
  13132. gl.deleteFramebuffer(texture._framebuffer);
  13133. texture._framebuffer = null;
  13134. }
  13135. if (texture._depthStencilBuffer) {
  13136. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13137. texture._depthStencilBuffer = null;
  13138. }
  13139. if (texture._MSAAFramebuffer) {
  13140. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13141. texture._MSAAFramebuffer = null;
  13142. }
  13143. if (texture._MSAARenderBuffer) {
  13144. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13145. texture._MSAARenderBuffer = null;
  13146. }
  13147. };
  13148. Engine.prototype._releaseTexture = function (texture) {
  13149. var gl = this._gl;
  13150. this._releaseFramebufferObjects(texture);
  13151. gl.deleteTexture(texture._webGLTexture);
  13152. // Unbind channels
  13153. this.unbindAllTextures();
  13154. var index = this._internalTexturesCache.indexOf(texture);
  13155. if (index !== -1) {
  13156. this._internalTexturesCache.splice(index, 1);
  13157. }
  13158. // Integrated fixed lod samplers.
  13159. if (texture._lodTextureHigh) {
  13160. texture._lodTextureHigh.dispose();
  13161. }
  13162. if (texture._lodTextureMid) {
  13163. texture._lodTextureMid.dispose();
  13164. }
  13165. if (texture._lodTextureLow) {
  13166. texture._lodTextureLow.dispose();
  13167. }
  13168. };
  13169. Engine.prototype.setProgram = function (program) {
  13170. if (this._currentProgram !== program) {
  13171. this._gl.useProgram(program);
  13172. this._currentProgram = program;
  13173. }
  13174. };
  13175. Engine.prototype.bindSamplers = function (effect) {
  13176. this.setProgram(effect.getProgram());
  13177. var samplers = effect.getSamplers();
  13178. for (var index = 0; index < samplers.length; index++) {
  13179. var uniform = effect.getUniform(samplers[index]);
  13180. if (uniform) {
  13181. this._boundUniforms[index] = uniform;
  13182. }
  13183. }
  13184. this._currentEffect = null;
  13185. };
  13186. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13187. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13188. return;
  13189. }
  13190. // Remove
  13191. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13192. // Bind last to it
  13193. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13194. // Bind to dummy
  13195. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13196. };
  13197. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13198. if (!internalTexture) {
  13199. return -1;
  13200. }
  13201. internalTexture._initialSlot = channel;
  13202. if (this.disableTextureBindingOptimization) {
  13203. if (channel !== internalTexture._designatedSlot) {
  13204. this._textureCollisions.addCount(1, false);
  13205. }
  13206. }
  13207. else {
  13208. if (channel !== internalTexture._designatedSlot) {
  13209. if (internalTexture._designatedSlot > -1) {
  13210. return internalTexture._designatedSlot;
  13211. }
  13212. else {
  13213. // No slot for this texture, let's pick a new one (if we find a free slot)
  13214. if (this._nextFreeTextureSlots.length) {
  13215. return this._nextFreeTextureSlots[0];
  13216. }
  13217. // We need to recycle the oldest bound texture, sorry.
  13218. this._textureCollisions.addCount(1, false);
  13219. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13220. }
  13221. }
  13222. }
  13223. return channel;
  13224. };
  13225. Engine.prototype._linkTrackers = function (previous, next) {
  13226. previous.next = next;
  13227. next.previous = previous;
  13228. };
  13229. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  13230. var currentSlot = internalTexture._designatedSlot;
  13231. if (currentSlot === -1) {
  13232. return -1;
  13233. }
  13234. internalTexture._designatedSlot = -1;
  13235. // Remove from bound list
  13236. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13237. // Free the slot
  13238. this._boundTexturesCache[currentSlot] = null;
  13239. this._nextFreeTextureSlots.push(currentSlot);
  13240. return currentSlot;
  13241. };
  13242. Engine.prototype._activateCurrentTexture = function () {
  13243. if (this._currentTextureChannel !== this._activeChannel) {
  13244. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  13245. this._currentTextureChannel = this._activeChannel;
  13246. }
  13247. };
  13248. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  13249. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  13250. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  13251. this._activeChannel = texture._designatedSlot;
  13252. }
  13253. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  13254. var isTextureForRendering = texture && texture._initialSlot > -1;
  13255. if (currentTextureBound !== texture) {
  13256. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  13257. this._removeDesignatedSlot(currentTextureBound);
  13258. }
  13259. this._activateCurrentTexture();
  13260. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  13261. this._boundTexturesCache[this._activeChannel] = texture;
  13262. if (texture) {
  13263. if (!this.disableTextureBindingOptimization) {
  13264. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  13265. if (slotIndex > -1) {
  13266. this._nextFreeTextureSlots.splice(slotIndex, 1);
  13267. }
  13268. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  13269. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  13270. }
  13271. texture._designatedSlot = this._activeChannel;
  13272. }
  13273. }
  13274. else if (forTextureDataUpdate) {
  13275. this._activateCurrentTexture();
  13276. }
  13277. if (isTextureForRendering && !forTextureDataUpdate) {
  13278. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  13279. }
  13280. };
  13281. Engine.prototype._bindTexture = function (channel, texture) {
  13282. if (channel < 0) {
  13283. return;
  13284. }
  13285. if (texture) {
  13286. channel = this._getCorrectTextureChannel(channel, texture);
  13287. }
  13288. this._activeChannel = channel;
  13289. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  13290. };
  13291. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13292. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  13293. };
  13294. Engine.prototype.unbindAllTextures = function () {
  13295. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  13296. this._activeChannel = channel;
  13297. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13298. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13299. if (this.webGLVersion > 1) {
  13300. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13301. }
  13302. }
  13303. };
  13304. Engine.prototype.setTexture = function (channel, uniform, texture) {
  13305. if (channel < 0) {
  13306. return;
  13307. }
  13308. if (uniform) {
  13309. this._boundUniforms[channel] = uniform;
  13310. }
  13311. this._setTexture(channel, texture);
  13312. };
  13313. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  13314. var uniform = this._boundUniforms[sourceSlot];
  13315. if (uniform._currentState === destination) {
  13316. return;
  13317. }
  13318. this._gl.uniform1i(uniform, destination);
  13319. uniform._currentState = destination;
  13320. };
  13321. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  13322. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  13323. // Not ready?
  13324. if (!texture) {
  13325. if (this._boundTexturesCache[channel] != null) {
  13326. this._activeChannel = channel;
  13327. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13328. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13329. if (this.webGLVersion > 1) {
  13330. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13331. }
  13332. }
  13333. return false;
  13334. }
  13335. // Video
  13336. if (texture.video) {
  13337. this._activeChannel = channel;
  13338. texture.update();
  13339. }
  13340. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  13341. texture.delayLoad();
  13342. return false;
  13343. }
  13344. var internalTexture;
  13345. if (texture.isReady()) {
  13346. internalTexture = texture.getInternalTexture();
  13347. }
  13348. else if (texture.isCube) {
  13349. internalTexture = this.emptyCubeTexture;
  13350. }
  13351. else if (texture.is3D) {
  13352. internalTexture = this.emptyTexture3D;
  13353. }
  13354. else {
  13355. internalTexture = this.emptyTexture;
  13356. }
  13357. if (!isPartOfTextureArray) {
  13358. channel = this._getCorrectTextureChannel(channel, internalTexture);
  13359. }
  13360. if (this._boundTexturesCache[channel] === internalTexture) {
  13361. this._moveBoundTextureOnTop(internalTexture);
  13362. if (!isPartOfTextureArray) {
  13363. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  13364. }
  13365. return false;
  13366. }
  13367. this._activeChannel = channel;
  13368. if (internalTexture && internalTexture.is3D) {
  13369. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  13370. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13371. internalTexture._cachedWrapU = texture.wrapU;
  13372. switch (texture.wrapU) {
  13373. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13374. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13375. break;
  13376. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13377. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13378. break;
  13379. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13380. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13381. break;
  13382. }
  13383. }
  13384. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13385. internalTexture._cachedWrapV = texture.wrapV;
  13386. switch (texture.wrapV) {
  13387. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13388. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13389. break;
  13390. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13391. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13392. break;
  13393. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13394. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13395. break;
  13396. }
  13397. }
  13398. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  13399. internalTexture._cachedWrapR = texture.wrapR;
  13400. switch (texture.wrapV) {
  13401. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13402. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  13403. break;
  13404. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13405. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  13406. break;
  13407. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13408. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  13409. break;
  13410. }
  13411. }
  13412. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  13413. }
  13414. else if (internalTexture && internalTexture.isCube) {
  13415. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  13416. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  13417. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  13418. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  13419. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  13420. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  13421. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  13422. }
  13423. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  13424. }
  13425. else {
  13426. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  13427. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13428. internalTexture._cachedWrapU = texture.wrapU;
  13429. switch (texture.wrapU) {
  13430. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13431. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13432. break;
  13433. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13434. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13435. break;
  13436. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13437. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13438. break;
  13439. }
  13440. }
  13441. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13442. internalTexture._cachedWrapV = texture.wrapV;
  13443. switch (texture.wrapV) {
  13444. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13445. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13446. break;
  13447. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13448. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13449. break;
  13450. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13451. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13452. break;
  13453. }
  13454. }
  13455. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  13456. }
  13457. return true;
  13458. };
  13459. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  13460. if (channel < 0 || !uniform) {
  13461. return;
  13462. }
  13463. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  13464. this._textureUnits = new Int32Array(textures.length);
  13465. }
  13466. for (var i = 0; i < textures.length; i++) {
  13467. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  13468. }
  13469. this._gl.uniform1iv(uniform, this._textureUnits);
  13470. for (var index = 0; index < textures.length; index++) {
  13471. this._setTexture(this._textureUnits[index], textures[index], true);
  13472. }
  13473. };
  13474. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  13475. var internalTexture = texture.getInternalTexture();
  13476. if (!internalTexture) {
  13477. return;
  13478. }
  13479. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13480. var value = texture.anisotropicFilteringLevel;
  13481. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13482. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13483. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13484. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13485. }
  13486. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13487. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13488. internalTexture._cachedAnisotropicFilteringLevel = value;
  13489. }
  13490. };
  13491. Engine.prototype.readPixels = function (x, y, width, height) {
  13492. var data = new Uint8Array(height * width * 4);
  13493. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13494. return data;
  13495. };
  13496. /**
  13497. * Add an externaly attached data from its key.
  13498. * This method call will fail and return false, if such key already exists.
  13499. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13500. * @param key the unique key that identifies the data
  13501. * @param data the data object to associate to the key for this Engine instance
  13502. * @return true if no such key were already present and the data was added successfully, false otherwise
  13503. */
  13504. Engine.prototype.addExternalData = function (key, data) {
  13505. if (!this._externalData) {
  13506. this._externalData = new BABYLON.StringDictionary();
  13507. }
  13508. return this._externalData.add(key, data);
  13509. };
  13510. /**
  13511. * Get an externaly attached data from its key
  13512. * @param key the unique key that identifies the data
  13513. * @return the associated data, if present (can be null), or undefined if not present
  13514. */
  13515. Engine.prototype.getExternalData = function (key) {
  13516. if (!this._externalData) {
  13517. this._externalData = new BABYLON.StringDictionary();
  13518. }
  13519. return this._externalData.get(key);
  13520. };
  13521. /**
  13522. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13523. * @param key the unique key that identifies the data
  13524. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13525. * @return the associated data, can be null if the factory returned null.
  13526. */
  13527. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13528. if (!this._externalData) {
  13529. this._externalData = new BABYLON.StringDictionary();
  13530. }
  13531. return this._externalData.getOrAddWithFactory(key, factory);
  13532. };
  13533. /**
  13534. * Remove an externaly attached data from the Engine instance
  13535. * @param key the unique key that identifies the data
  13536. * @return true if the data was successfully removed, false if it doesn't exist
  13537. */
  13538. Engine.prototype.removeExternalData = function (key) {
  13539. if (!this._externalData) {
  13540. this._externalData = new BABYLON.StringDictionary();
  13541. }
  13542. return this._externalData.remove(key);
  13543. };
  13544. Engine.prototype.unbindAllAttributes = function () {
  13545. if (this._mustWipeVertexAttributes) {
  13546. this._mustWipeVertexAttributes = false;
  13547. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13548. this._gl.disableVertexAttribArray(i);
  13549. this._vertexAttribArraysEnabled[i] = false;
  13550. this._currentBufferPointers[i].active = false;
  13551. }
  13552. return;
  13553. }
  13554. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13555. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13556. continue;
  13557. }
  13558. this._gl.disableVertexAttribArray(i);
  13559. this._vertexAttribArraysEnabled[i] = false;
  13560. this._currentBufferPointers[i].active = false;
  13561. }
  13562. };
  13563. Engine.prototype.releaseEffects = function () {
  13564. for (var name in this._compiledEffects) {
  13565. this._deleteProgram(this._compiledEffects[name]._program);
  13566. }
  13567. this._compiledEffects = {};
  13568. };
  13569. // Dispose
  13570. Engine.prototype.dispose = function () {
  13571. this.hideLoadingUI();
  13572. this.stopRenderLoop();
  13573. // Release postProcesses
  13574. while (this.postProcesses.length) {
  13575. this.postProcesses[0].dispose();
  13576. }
  13577. // Empty texture
  13578. if (this._emptyTexture) {
  13579. this._releaseTexture(this._emptyTexture);
  13580. this._emptyTexture = null;
  13581. }
  13582. if (this._emptyCubeTexture) {
  13583. this._releaseTexture(this._emptyCubeTexture);
  13584. this._emptyCubeTexture = null;
  13585. }
  13586. // Rescale PP
  13587. if (this._rescalePostProcess) {
  13588. this._rescalePostProcess.dispose();
  13589. }
  13590. // Release scenes
  13591. while (this.scenes.length) {
  13592. this.scenes[0].dispose();
  13593. }
  13594. // Release audio engine
  13595. if (Engine.audioEngine) {
  13596. Engine.audioEngine.dispose();
  13597. }
  13598. // Release effects
  13599. this.releaseEffects();
  13600. // Unbind
  13601. this.unbindAllAttributes();
  13602. if (this._dummyFramebuffer) {
  13603. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13604. }
  13605. //WebVR
  13606. this.disableVR();
  13607. // Events
  13608. if (BABYLON.Tools.IsWindowObjectExist()) {
  13609. window.removeEventListener("blur", this._onBlur);
  13610. window.removeEventListener("focus", this._onFocus);
  13611. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13612. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13613. if (this._renderingCanvas) {
  13614. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13615. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13616. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13617. if (!this._doNotHandleContextLost) {
  13618. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13619. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13620. }
  13621. }
  13622. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13623. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13624. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13625. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13626. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13627. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13628. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13629. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13630. if (this._onVrDisplayConnect) {
  13631. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13632. if (this._onVrDisplayDisconnect) {
  13633. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13634. }
  13635. if (this._onVrDisplayPresentChange) {
  13636. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13637. }
  13638. this._onVrDisplayConnect = null;
  13639. this._onVrDisplayDisconnect = null;
  13640. }
  13641. }
  13642. // Remove from Instances
  13643. var index = Engine.Instances.indexOf(this);
  13644. if (index >= 0) {
  13645. Engine.Instances.splice(index, 1);
  13646. }
  13647. this._workingCanvas = null;
  13648. this._workingContext = null;
  13649. this._currentBufferPointers = [];
  13650. this._renderingCanvas = null;
  13651. this._currentProgram = null;
  13652. this.onResizeObservable.clear();
  13653. this.onCanvasBlurObservable.clear();
  13654. this.onCanvasFocusObservable.clear();
  13655. this.onCanvasPointerOutObservable.clear();
  13656. this.onBeginFrameObservable.clear();
  13657. this.onEndFrameObservable.clear();
  13658. BABYLON.Effect.ResetCache();
  13659. // Abort active requests
  13660. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13661. var request = _a[_i];
  13662. request.abort();
  13663. }
  13664. };
  13665. // Loading screen
  13666. Engine.prototype.displayLoadingUI = function () {
  13667. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13668. return;
  13669. }
  13670. var loadingScreen = this.loadingScreen;
  13671. if (loadingScreen) {
  13672. loadingScreen.displayLoadingUI();
  13673. }
  13674. };
  13675. Engine.prototype.hideLoadingUI = function () {
  13676. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13677. return;
  13678. }
  13679. var loadingScreen = this.loadingScreen;
  13680. if (loadingScreen) {
  13681. loadingScreen.hideLoadingUI();
  13682. }
  13683. };
  13684. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13685. get: function () {
  13686. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13687. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13688. return this._loadingScreen;
  13689. },
  13690. set: function (loadingScreen) {
  13691. this._loadingScreen = loadingScreen;
  13692. },
  13693. enumerable: true,
  13694. configurable: true
  13695. });
  13696. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13697. set: function (text) {
  13698. this.loadingScreen.loadingUIText = text;
  13699. },
  13700. enumerable: true,
  13701. configurable: true
  13702. });
  13703. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13704. set: function (color) {
  13705. this.loadingScreen.loadingUIBackgroundColor = color;
  13706. },
  13707. enumerable: true,
  13708. configurable: true
  13709. });
  13710. Engine.prototype.attachContextLostEvent = function (callback) {
  13711. if (this._renderingCanvas) {
  13712. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13713. }
  13714. };
  13715. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13716. if (this._renderingCanvas) {
  13717. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13718. }
  13719. };
  13720. Engine.prototype.getVertexShaderSource = function (program) {
  13721. var shaders = this._gl.getAttachedShaders(program);
  13722. if (!shaders) {
  13723. return null;
  13724. }
  13725. return this._gl.getShaderSource(shaders[0]);
  13726. };
  13727. Engine.prototype.getFragmentShaderSource = function (program) {
  13728. var shaders = this._gl.getAttachedShaders(program);
  13729. if (!shaders) {
  13730. return null;
  13731. }
  13732. return this._gl.getShaderSource(shaders[1]);
  13733. };
  13734. Engine.prototype.getError = function () {
  13735. return this._gl.getError();
  13736. };
  13737. // FPS
  13738. Engine.prototype.getFps = function () {
  13739. return this._fps;
  13740. };
  13741. Engine.prototype.getDeltaTime = function () {
  13742. return this._deltaTime;
  13743. };
  13744. Engine.prototype._measureFps = function () {
  13745. this._performanceMonitor.sampleFrame();
  13746. this._fps = this._performanceMonitor.averageFPS;
  13747. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13748. };
  13749. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13750. if (faceIndex === void 0) { faceIndex = -1; }
  13751. var gl = this._gl;
  13752. if (!this._dummyFramebuffer) {
  13753. var dummy = gl.createFramebuffer();
  13754. if (!dummy) {
  13755. throw new Error("Unable to create dummy framebuffer");
  13756. }
  13757. this._dummyFramebuffer = dummy;
  13758. }
  13759. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13760. if (faceIndex > -1) {
  13761. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13762. }
  13763. else {
  13764. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13765. }
  13766. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13767. var buffer;
  13768. switch (readType) {
  13769. case gl.UNSIGNED_BYTE:
  13770. buffer = new Uint8Array(4 * width * height);
  13771. readType = gl.UNSIGNED_BYTE;
  13772. break;
  13773. default:
  13774. buffer = new Float32Array(4 * width * height);
  13775. readType = gl.FLOAT;
  13776. break;
  13777. }
  13778. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13779. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13780. return buffer;
  13781. };
  13782. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13783. if (this._webGLVersion > 1) {
  13784. return this._caps.colorBufferFloat;
  13785. }
  13786. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13787. };
  13788. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13789. if (this._webGLVersion > 1) {
  13790. return this._caps.colorBufferFloat;
  13791. }
  13792. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13793. };
  13794. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13795. Engine.prototype._canRenderToFramebuffer = function (type) {
  13796. var gl = this._gl;
  13797. //clear existing errors
  13798. while (gl.getError() !== gl.NO_ERROR) { }
  13799. var successful = true;
  13800. var texture = gl.createTexture();
  13801. gl.bindTexture(gl.TEXTURE_2D, texture);
  13802. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13803. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13804. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13805. var fb = gl.createFramebuffer();
  13806. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13807. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13808. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13809. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13810. successful = successful && (gl.getError() === gl.NO_ERROR);
  13811. //try render by clearing frame buffer's color buffer
  13812. if (successful) {
  13813. gl.clear(gl.COLOR_BUFFER_BIT);
  13814. successful = successful && (gl.getError() === gl.NO_ERROR);
  13815. }
  13816. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13817. if (successful) {
  13818. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13819. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13820. var readFormat = gl.RGBA;
  13821. var readType = gl.UNSIGNED_BYTE;
  13822. var buffer = new Uint8Array(4);
  13823. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13824. successful = successful && (gl.getError() === gl.NO_ERROR);
  13825. }
  13826. //clean up
  13827. gl.deleteTexture(texture);
  13828. gl.deleteFramebuffer(fb);
  13829. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13830. //clear accumulated errors
  13831. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13832. return successful;
  13833. };
  13834. Engine.prototype._getWebGLTextureType = function (type) {
  13835. if (type === Engine.TEXTURETYPE_FLOAT) {
  13836. return this._gl.FLOAT;
  13837. }
  13838. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13839. // Add Half Float Constant.
  13840. return this._gl.HALF_FLOAT_OES;
  13841. }
  13842. return this._gl.UNSIGNED_BYTE;
  13843. };
  13844. ;
  13845. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13846. if (this._webGLVersion === 1) {
  13847. return this._gl.RGBA;
  13848. }
  13849. if (type === Engine.TEXTURETYPE_FLOAT) {
  13850. return this._gl.RGBA32F;
  13851. }
  13852. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13853. return this._gl.RGBA16F;
  13854. }
  13855. return this._gl.RGBA;
  13856. };
  13857. ;
  13858. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13859. if (type === Engine.TEXTURETYPE_FLOAT) {
  13860. return this._gl.RGBA32F;
  13861. }
  13862. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13863. return this._gl.RGBA16F;
  13864. }
  13865. return this._gl.RGBA8;
  13866. };
  13867. ;
  13868. Engine.prototype.createQuery = function () {
  13869. return this._gl.createQuery();
  13870. };
  13871. Engine.prototype.deleteQuery = function (query) {
  13872. this._gl.deleteQuery(query);
  13873. return this;
  13874. };
  13875. Engine.prototype.isQueryResultAvailable = function (query) {
  13876. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13877. };
  13878. Engine.prototype.getQueryResult = function (query) {
  13879. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13880. };
  13881. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13882. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13883. this._gl.beginQuery(glAlgorithm, query);
  13884. return this;
  13885. };
  13886. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13887. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13888. this._gl.endQuery(glAlgorithm);
  13889. return this;
  13890. };
  13891. /* Time queries */
  13892. Engine.prototype._createTimeQuery = function () {
  13893. var timerQuery = this._caps.timerQuery;
  13894. if (timerQuery.createQueryEXT) {
  13895. return timerQuery.createQueryEXT();
  13896. }
  13897. return this.createQuery();
  13898. };
  13899. Engine.prototype._deleteTimeQuery = function (query) {
  13900. var timerQuery = this._caps.timerQuery;
  13901. if (timerQuery.deleteQueryEXT) {
  13902. timerQuery.deleteQueryEXT(query);
  13903. return;
  13904. }
  13905. this.deleteQuery(query);
  13906. };
  13907. Engine.prototype._getTimeQueryResult = function (query) {
  13908. var timerQuery = this._caps.timerQuery;
  13909. if (timerQuery.getQueryObjectEXT) {
  13910. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13911. }
  13912. return this.getQueryResult(query);
  13913. };
  13914. Engine.prototype._getTimeQueryAvailability = function (query) {
  13915. var timerQuery = this._caps.timerQuery;
  13916. if (timerQuery.getQueryObjectEXT) {
  13917. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13918. }
  13919. return this.isQueryResultAvailable(query);
  13920. };
  13921. Engine.prototype.startTimeQuery = function () {
  13922. var timerQuery = this._caps.timerQuery;
  13923. if (!timerQuery) {
  13924. return null;
  13925. }
  13926. var token = new BABYLON._TimeToken();
  13927. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13928. if (this._caps.canUseTimestampForTimerQuery) {
  13929. token._startTimeQuery = this._createTimeQuery();
  13930. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13931. }
  13932. else {
  13933. if (this._currentNonTimestampToken) {
  13934. return this._currentNonTimestampToken;
  13935. }
  13936. token._timeElapsedQuery = this._createTimeQuery();
  13937. if (timerQuery.beginQueryEXT) {
  13938. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13939. }
  13940. else {
  13941. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13942. }
  13943. this._currentNonTimestampToken = token;
  13944. }
  13945. return token;
  13946. };
  13947. Engine.prototype.endTimeQuery = function (token) {
  13948. var timerQuery = this._caps.timerQuery;
  13949. if (!timerQuery || !token) {
  13950. return -1;
  13951. }
  13952. if (this._caps.canUseTimestampForTimerQuery) {
  13953. if (!token._startTimeQuery) {
  13954. return -1;
  13955. }
  13956. if (!token._endTimeQuery) {
  13957. token._endTimeQuery = this._createTimeQuery();
  13958. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13959. }
  13960. }
  13961. else if (!token._timeElapsedQueryEnded) {
  13962. if (!token._timeElapsedQuery) {
  13963. return -1;
  13964. }
  13965. if (timerQuery.endQueryEXT) {
  13966. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13967. }
  13968. else {
  13969. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13970. }
  13971. token._timeElapsedQueryEnded = true;
  13972. }
  13973. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13974. var available = false;
  13975. if (token._endTimeQuery) {
  13976. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13977. }
  13978. else if (token._timeElapsedQuery) {
  13979. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13980. }
  13981. if (available && !disjoint) {
  13982. var result = 0;
  13983. if (this._caps.canUseTimestampForTimerQuery) {
  13984. if (!token._startTimeQuery || !token._endTimeQuery) {
  13985. return -1;
  13986. }
  13987. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13988. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13989. result = timeEnd - timeStart;
  13990. this._deleteTimeQuery(token._startTimeQuery);
  13991. this._deleteTimeQuery(token._endTimeQuery);
  13992. token._startTimeQuery = null;
  13993. token._endTimeQuery = null;
  13994. }
  13995. else {
  13996. if (!token._timeElapsedQuery) {
  13997. return -1;
  13998. }
  13999. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14000. this._deleteTimeQuery(token._timeElapsedQuery);
  14001. token._timeElapsedQuery = null;
  14002. token._timeElapsedQueryEnded = false;
  14003. this._currentNonTimestampToken = null;
  14004. }
  14005. return result;
  14006. }
  14007. return -1;
  14008. };
  14009. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14010. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14011. };
  14012. // Transform feedback
  14013. Engine.prototype.createTransformFeedback = function () {
  14014. return this._gl.createTransformFeedback();
  14015. };
  14016. Engine.prototype.deleteTransformFeedback = function (value) {
  14017. this._gl.deleteTransformFeedback(value);
  14018. };
  14019. Engine.prototype.bindTransformFeedback = function (value) {
  14020. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14021. };
  14022. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14023. if (usePoints === void 0) { usePoints = true; }
  14024. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14025. };
  14026. Engine.prototype.endTransformFeedback = function () {
  14027. this._gl.endTransformFeedback();
  14028. };
  14029. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14030. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14031. };
  14032. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14033. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14034. };
  14035. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14036. var _this = this;
  14037. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14038. this._activeRequests.push(request);
  14039. request.onCompleteObservable.add(function (request) {
  14040. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14041. });
  14042. return request;
  14043. };
  14044. /** @ignore */
  14045. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14046. var _this = this;
  14047. return new Promise(function (resolve, reject) {
  14048. _this._loadFile(url, function (data) {
  14049. resolve(data);
  14050. }, undefined, database, useArrayBuffer, function (request, exception) {
  14051. reject(exception);
  14052. });
  14053. });
  14054. };
  14055. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14056. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14057. var onload = function (data) {
  14058. loadedFiles[index] = data;
  14059. loadedFiles._internalCount++;
  14060. if (loadedFiles._internalCount === 6) {
  14061. onfinish(loadedFiles);
  14062. }
  14063. };
  14064. var onerror = function (request, exception) {
  14065. if (onErrorCallBack && request) {
  14066. onErrorCallBack(request.status + " " + request.statusText, exception);
  14067. }
  14068. };
  14069. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14070. };
  14071. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14072. if (onError === void 0) { onError = null; }
  14073. var loadedFiles = [];
  14074. loadedFiles._internalCount = 0;
  14075. for (var index = 0; index < 6; index++) {
  14076. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14077. }
  14078. };
  14079. // Statics
  14080. Engine.isSupported = function () {
  14081. try {
  14082. var tempcanvas = document.createElement("canvas");
  14083. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14084. return gl != null && !!window.WebGLRenderingContext;
  14085. }
  14086. catch (e) {
  14087. return false;
  14088. }
  14089. };
  14090. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14091. Engine.ExceptionList = [
  14092. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14093. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14094. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14095. ];
  14096. Engine.Instances = new Array();
  14097. // Const statics
  14098. Engine._ALPHA_DISABLE = 0;
  14099. Engine._ALPHA_ADD = 1;
  14100. Engine._ALPHA_COMBINE = 2;
  14101. Engine._ALPHA_SUBTRACT = 3;
  14102. Engine._ALPHA_MULTIPLY = 4;
  14103. Engine._ALPHA_MAXIMIZED = 5;
  14104. Engine._ALPHA_ONEONE = 6;
  14105. Engine._ALPHA_PREMULTIPLIED = 7;
  14106. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14107. Engine._ALPHA_INTERPOLATE = 9;
  14108. Engine._ALPHA_SCREENMODE = 10;
  14109. Engine._DELAYLOADSTATE_NONE = 0;
  14110. Engine._DELAYLOADSTATE_LOADED = 1;
  14111. Engine._DELAYLOADSTATE_LOADING = 2;
  14112. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14113. Engine._TEXTUREFORMAT_ALPHA = 0;
  14114. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14115. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14116. Engine._TEXTUREFORMAT_RGB = 4;
  14117. Engine._TEXTUREFORMAT_RGBA = 5;
  14118. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14119. Engine._TEXTURETYPE_FLOAT = 1;
  14120. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14121. // Depht or Stencil test Constants.
  14122. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14123. 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.
  14124. 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.
  14125. 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.
  14126. 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.
  14127. 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.
  14128. 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.
  14129. 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.
  14130. // Stencil Actions Constants.
  14131. Engine._KEEP = 0x1E00;
  14132. Engine._REPLACE = 0x1E01;
  14133. Engine._INCR = 0x1E02;
  14134. Engine._DECR = 0x1E03;
  14135. Engine._INVERT = 0x150A;
  14136. Engine._INCR_WRAP = 0x8507;
  14137. Engine._DECR_WRAP = 0x8508;
  14138. // Texture rescaling mode
  14139. Engine._SCALEMODE_FLOOR = 1;
  14140. Engine._SCALEMODE_NEAREST = 2;
  14141. Engine._SCALEMODE_CEILING = 3;
  14142. // Updatable statics so stick with vars here
  14143. Engine.CollisionsEpsilon = 0.001;
  14144. Engine.CodeRepository = "src/";
  14145. Engine.ShadersRepository = "src/Shaders/";
  14146. return Engine;
  14147. }());
  14148. BABYLON.Engine = Engine;
  14149. })(BABYLON || (BABYLON = {}));
  14150. //# sourceMappingURL=babylon.engine.js.map
  14151. var BABYLON;
  14152. (function (BABYLON) {
  14153. /**
  14154. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14155. */
  14156. var Node = /** @class */ (function () {
  14157. /**
  14158. * @constructor
  14159. * @param {string} name - the name and id to be given to this node
  14160. * @param {BABYLON.Scene} the scene this node will be added to
  14161. */
  14162. function Node(name, scene) {
  14163. if (scene === void 0) { scene = null; }
  14164. this.state = "";
  14165. this.metadata = null;
  14166. this.doNotSerialize = false;
  14167. this.animations = new Array();
  14168. this._ranges = {};
  14169. this._isEnabled = true;
  14170. this._isReady = true;
  14171. this._currentRenderId = -1;
  14172. this._parentRenderId = -1;
  14173. /**
  14174. * An event triggered when the mesh is disposed.
  14175. * @type {BABYLON.Observable}
  14176. */
  14177. this.onDisposeObservable = new BABYLON.Observable();
  14178. // Behaviors
  14179. this._behaviors = new Array();
  14180. this.name = name;
  14181. this.id = name;
  14182. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14183. this.uniqueId = this._scene.getUniqueId();
  14184. this._initCache();
  14185. }
  14186. Object.defineProperty(Node.prototype, "parent", {
  14187. get: function () {
  14188. return this._parentNode;
  14189. },
  14190. set: function (parent) {
  14191. if (this._parentNode === parent) {
  14192. return;
  14193. }
  14194. // Remove self from list of children of parent
  14195. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14196. var index = this._parentNode._children.indexOf(this);
  14197. if (index !== -1) {
  14198. this._parentNode._children.splice(index, 1);
  14199. }
  14200. }
  14201. // Store new parent
  14202. this._parentNode = parent;
  14203. // Add as child to new parent
  14204. if (this._parentNode) {
  14205. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14206. this._parentNode._children = new Array();
  14207. }
  14208. this._parentNode._children.push(this);
  14209. }
  14210. },
  14211. enumerable: true,
  14212. configurable: true
  14213. });
  14214. Node.prototype.getClassName = function () {
  14215. return "Node";
  14216. };
  14217. Object.defineProperty(Node.prototype, "onDispose", {
  14218. set: function (callback) {
  14219. if (this._onDisposeObserver) {
  14220. this.onDisposeObservable.remove(this._onDisposeObserver);
  14221. }
  14222. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14223. },
  14224. enumerable: true,
  14225. configurable: true
  14226. });
  14227. Node.prototype.getScene = function () {
  14228. return this._scene;
  14229. };
  14230. Node.prototype.getEngine = function () {
  14231. return this._scene.getEngine();
  14232. };
  14233. Node.prototype.addBehavior = function (behavior) {
  14234. var _this = this;
  14235. var index = this._behaviors.indexOf(behavior);
  14236. if (index !== -1) {
  14237. return this;
  14238. }
  14239. behavior.init();
  14240. if (this._scene.isLoading) {
  14241. // We defer the attach when the scene will be loaded
  14242. var observer = this._scene.onDataLoadedObservable.add(function () {
  14243. behavior.attach(_this);
  14244. setTimeout(function () {
  14245. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  14246. _this._scene.onDataLoadedObservable.remove(observer);
  14247. }, 0);
  14248. });
  14249. }
  14250. else {
  14251. behavior.attach(this);
  14252. }
  14253. this._behaviors.push(behavior);
  14254. return this;
  14255. };
  14256. Node.prototype.removeBehavior = function (behavior) {
  14257. var index = this._behaviors.indexOf(behavior);
  14258. if (index === -1) {
  14259. return this;
  14260. }
  14261. this._behaviors[index].detach();
  14262. this._behaviors.splice(index, 1);
  14263. return this;
  14264. };
  14265. Object.defineProperty(Node.prototype, "behaviors", {
  14266. get: function () {
  14267. return this._behaviors;
  14268. },
  14269. enumerable: true,
  14270. configurable: true
  14271. });
  14272. Node.prototype.getBehaviorByName = function (name) {
  14273. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14274. var behavior = _a[_i];
  14275. if (behavior.name === name) {
  14276. return behavior;
  14277. }
  14278. }
  14279. return null;
  14280. };
  14281. // override it in derived class
  14282. Node.prototype.getWorldMatrix = function () {
  14283. return BABYLON.Matrix.Identity();
  14284. };
  14285. // override it in derived class if you add new variables to the cache
  14286. // and call the parent class method
  14287. Node.prototype._initCache = function () {
  14288. this._cache = {};
  14289. this._cache.parent = undefined;
  14290. };
  14291. Node.prototype.updateCache = function (force) {
  14292. if (!force && this.isSynchronized())
  14293. return;
  14294. this._cache.parent = this.parent;
  14295. this._updateCache();
  14296. };
  14297. // override it in derived class if you add new variables to the cache
  14298. // and call the parent class method if !ignoreParentClass
  14299. Node.prototype._updateCache = function (ignoreParentClass) {
  14300. };
  14301. // override it in derived class if you add new variables to the cache
  14302. Node.prototype._isSynchronized = function () {
  14303. return true;
  14304. };
  14305. Node.prototype._markSyncedWithParent = function () {
  14306. if (this.parent) {
  14307. this._parentRenderId = this.parent._currentRenderId;
  14308. }
  14309. };
  14310. Node.prototype.isSynchronizedWithParent = function () {
  14311. if (!this.parent) {
  14312. return true;
  14313. }
  14314. if (this._parentRenderId !== this.parent._currentRenderId) {
  14315. return false;
  14316. }
  14317. return this.parent.isSynchronized();
  14318. };
  14319. Node.prototype.isSynchronized = function (updateCache) {
  14320. var check = this.hasNewParent();
  14321. check = check || !this.isSynchronizedWithParent();
  14322. check = check || !this._isSynchronized();
  14323. if (updateCache)
  14324. this.updateCache(true);
  14325. return !check;
  14326. };
  14327. Node.prototype.hasNewParent = function (update) {
  14328. if (this._cache.parent === this.parent)
  14329. return false;
  14330. if (update)
  14331. this._cache.parent = this.parent;
  14332. return true;
  14333. };
  14334. /**
  14335. * Is this node ready to be used/rendered
  14336. * @return {boolean} is it ready
  14337. */
  14338. Node.prototype.isReady = function () {
  14339. return this._isReady;
  14340. };
  14341. /**
  14342. * Is this node enabled.
  14343. * 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.
  14344. * @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.
  14345. * @return {boolean} whether this node (and its parent) is enabled.
  14346. * @see setEnabled
  14347. */
  14348. Node.prototype.isEnabled = function (checkAncestors) {
  14349. if (checkAncestors === void 0) { checkAncestors = true; }
  14350. if (checkAncestors === false) {
  14351. return this._isEnabled;
  14352. }
  14353. if (this._isEnabled === false) {
  14354. return false;
  14355. }
  14356. if (this.parent !== undefined && this.parent !== null) {
  14357. return this.parent.isEnabled(checkAncestors);
  14358. }
  14359. return true;
  14360. };
  14361. /**
  14362. * Set the enabled state of this node.
  14363. * @param {boolean} value - the new enabled state
  14364. * @see isEnabled
  14365. */
  14366. Node.prototype.setEnabled = function (value) {
  14367. this._isEnabled = value;
  14368. };
  14369. /**
  14370. * Is this node a descendant of the given node.
  14371. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  14372. * @param {BABYLON.Node} ancestor - The parent node to inspect
  14373. * @see parent
  14374. */
  14375. Node.prototype.isDescendantOf = function (ancestor) {
  14376. if (this.parent) {
  14377. if (this.parent === ancestor) {
  14378. return true;
  14379. }
  14380. return this.parent.isDescendantOf(ancestor);
  14381. }
  14382. return false;
  14383. };
  14384. /**
  14385. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  14386. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  14387. * @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.
  14388. * @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.
  14389. */
  14390. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  14391. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  14392. if (!this._children) {
  14393. return;
  14394. }
  14395. for (var index = 0; index < this._children.length; index++) {
  14396. var item = this._children[index];
  14397. if (!predicate || predicate(item)) {
  14398. results.push(item);
  14399. }
  14400. if (!directDescendantsOnly) {
  14401. item._getDescendants(results, false, predicate);
  14402. }
  14403. }
  14404. };
  14405. /**
  14406. * Will return all nodes that have this node as ascendant.
  14407. * @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.
  14408. * @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.
  14409. * @return {BABYLON.Node[]} all children nodes of all types.
  14410. */
  14411. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  14412. var results = new Array();
  14413. this._getDescendants(results, directDescendantsOnly, predicate);
  14414. return results;
  14415. };
  14416. /**
  14417. * Get all child-meshes of this node.
  14418. */
  14419. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  14420. var results = [];
  14421. this._getDescendants(results, directDescendantsOnly, function (node) {
  14422. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  14423. });
  14424. return results;
  14425. };
  14426. /**
  14427. * Get all child-transformNodes of this node.
  14428. */
  14429. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  14430. var results = [];
  14431. this._getDescendants(results, directDescendantsOnly, function (node) {
  14432. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  14433. });
  14434. return results;
  14435. };
  14436. /**
  14437. * Get all direct children of this node.
  14438. */
  14439. Node.prototype.getChildren = function (predicate) {
  14440. return this.getDescendants(true, predicate);
  14441. };
  14442. Node.prototype._setReady = function (state) {
  14443. if (state === this._isReady) {
  14444. return;
  14445. }
  14446. if (!state) {
  14447. this._isReady = false;
  14448. return;
  14449. }
  14450. this._isReady = true;
  14451. if (this.onReady) {
  14452. this.onReady(this);
  14453. }
  14454. };
  14455. Node.prototype.getAnimationByName = function (name) {
  14456. for (var i = 0; i < this.animations.length; i++) {
  14457. var animation = this.animations[i];
  14458. if (animation.name === name) {
  14459. return animation;
  14460. }
  14461. }
  14462. return null;
  14463. };
  14464. Node.prototype.createAnimationRange = function (name, from, to) {
  14465. // check name not already in use
  14466. if (!this._ranges[name]) {
  14467. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  14468. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14469. if (this.animations[i]) {
  14470. this.animations[i].createRange(name, from, to);
  14471. }
  14472. }
  14473. }
  14474. };
  14475. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  14476. if (deleteFrames === void 0) { deleteFrames = true; }
  14477. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14478. if (this.animations[i]) {
  14479. this.animations[i].deleteRange(name, deleteFrames);
  14480. }
  14481. }
  14482. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  14483. };
  14484. Node.prototype.getAnimationRange = function (name) {
  14485. return this._ranges[name];
  14486. };
  14487. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14488. var range = this.getAnimationRange(name);
  14489. if (!range) {
  14490. return;
  14491. }
  14492. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14493. };
  14494. Node.prototype.serializeAnimationRanges = function () {
  14495. var serializationRanges = [];
  14496. for (var name in this._ranges) {
  14497. var localRange = this._ranges[name];
  14498. if (!localRange) {
  14499. continue;
  14500. }
  14501. var range = {};
  14502. range.name = name;
  14503. range.from = localRange.from;
  14504. range.to = localRange.to;
  14505. serializationRanges.push(range);
  14506. }
  14507. return serializationRanges;
  14508. };
  14509. // override it in derived class
  14510. Node.prototype.computeWorldMatrix = function (force) {
  14511. return BABYLON.Matrix.Identity();
  14512. };
  14513. Node.prototype.dispose = function () {
  14514. this.parent = null;
  14515. // Callback
  14516. this.onDisposeObservable.notifyObservers(this);
  14517. this.onDisposeObservable.clear();
  14518. // Behaviors
  14519. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14520. var behavior = _a[_i];
  14521. behavior.detach();
  14522. }
  14523. this._behaviors = [];
  14524. };
  14525. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14526. if (parsedNode.ranges) {
  14527. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14528. var data = parsedNode.ranges[index];
  14529. node.createAnimationRange(data.name, data.from, data.to);
  14530. }
  14531. }
  14532. };
  14533. __decorate([
  14534. BABYLON.serialize()
  14535. ], Node.prototype, "name", void 0);
  14536. __decorate([
  14537. BABYLON.serialize()
  14538. ], Node.prototype, "id", void 0);
  14539. __decorate([
  14540. BABYLON.serialize()
  14541. ], Node.prototype, "uniqueId", void 0);
  14542. __decorate([
  14543. BABYLON.serialize()
  14544. ], Node.prototype, "state", void 0);
  14545. __decorate([
  14546. BABYLON.serialize()
  14547. ], Node.prototype, "metadata", void 0);
  14548. return Node;
  14549. }());
  14550. BABYLON.Node = Node;
  14551. })(BABYLON || (BABYLON = {}));
  14552. //# sourceMappingURL=babylon.node.js.map
  14553. var BABYLON;
  14554. (function (BABYLON) {
  14555. var BoundingSphere = /** @class */ (function () {
  14556. function BoundingSphere(minimum, maximum) {
  14557. this.minimum = minimum;
  14558. this.maximum = maximum;
  14559. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14560. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14561. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14562. this.radius = distance * 0.5;
  14563. this.centerWorld = BABYLON.Vector3.Zero();
  14564. this._update(BABYLON.Matrix.Identity());
  14565. }
  14566. // Methods
  14567. BoundingSphere.prototype._update = function (world) {
  14568. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14569. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14570. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14571. };
  14572. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14573. for (var i = 0; i < 6; i++) {
  14574. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14575. return false;
  14576. }
  14577. return true;
  14578. };
  14579. BoundingSphere.prototype.intersectsPoint = function (point) {
  14580. var x = this.centerWorld.x - point.x;
  14581. var y = this.centerWorld.y - point.y;
  14582. var z = this.centerWorld.z - point.z;
  14583. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14584. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14585. return false;
  14586. return true;
  14587. };
  14588. // Statics
  14589. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14590. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14591. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14592. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14593. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14594. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14595. return false;
  14596. return true;
  14597. };
  14598. return BoundingSphere;
  14599. }());
  14600. BABYLON.BoundingSphere = BoundingSphere;
  14601. })(BABYLON || (BABYLON = {}));
  14602. //# sourceMappingURL=babylon.boundingSphere.js.map
  14603. var BABYLON;
  14604. (function (BABYLON) {
  14605. var BoundingBox = /** @class */ (function () {
  14606. function BoundingBox(minimum, maximum) {
  14607. this.minimum = minimum;
  14608. this.maximum = maximum;
  14609. this.vectors = new Array();
  14610. this.vectorsWorld = new Array();
  14611. // Bounding vectors
  14612. this.vectors.push(this.minimum.clone());
  14613. this.vectors.push(this.maximum.clone());
  14614. this.vectors.push(this.minimum.clone());
  14615. this.vectors[2].x = this.maximum.x;
  14616. this.vectors.push(this.minimum.clone());
  14617. this.vectors[3].y = this.maximum.y;
  14618. this.vectors.push(this.minimum.clone());
  14619. this.vectors[4].z = this.maximum.z;
  14620. this.vectors.push(this.maximum.clone());
  14621. this.vectors[5].z = this.minimum.z;
  14622. this.vectors.push(this.maximum.clone());
  14623. this.vectors[6].x = this.minimum.x;
  14624. this.vectors.push(this.maximum.clone());
  14625. this.vectors[7].y = this.minimum.y;
  14626. // OBB
  14627. this.center = this.maximum.add(this.minimum).scale(0.5);
  14628. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14629. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14630. // World
  14631. for (var index = 0; index < this.vectors.length; index++) {
  14632. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14633. }
  14634. this.minimumWorld = BABYLON.Vector3.Zero();
  14635. this.maximumWorld = BABYLON.Vector3.Zero();
  14636. this.centerWorld = BABYLON.Vector3.Zero();
  14637. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14638. this._update(BABYLON.Matrix.Identity());
  14639. }
  14640. // Methods
  14641. BoundingBox.prototype.getWorldMatrix = function () {
  14642. return this._worldMatrix;
  14643. };
  14644. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14645. this._worldMatrix.copyFrom(matrix);
  14646. return this;
  14647. };
  14648. BoundingBox.prototype._update = function (world) {
  14649. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14650. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14651. for (var index = 0; index < this.vectors.length; index++) {
  14652. var v = this.vectorsWorld[index];
  14653. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14654. if (v.x < this.minimumWorld.x)
  14655. this.minimumWorld.x = v.x;
  14656. if (v.y < this.minimumWorld.y)
  14657. this.minimumWorld.y = v.y;
  14658. if (v.z < this.minimumWorld.z)
  14659. this.minimumWorld.z = v.z;
  14660. if (v.x > this.maximumWorld.x)
  14661. this.maximumWorld.x = v.x;
  14662. if (v.y > this.maximumWorld.y)
  14663. this.maximumWorld.y = v.y;
  14664. if (v.z > this.maximumWorld.z)
  14665. this.maximumWorld.z = v.z;
  14666. }
  14667. // Extend
  14668. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14669. this.extendSizeWorld.scaleInPlace(0.5);
  14670. // OBB
  14671. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14672. this.centerWorld.scaleInPlace(0.5);
  14673. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14674. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14675. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14676. this._worldMatrix = world;
  14677. };
  14678. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14679. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14680. };
  14681. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14682. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14683. };
  14684. BoundingBox.prototype.intersectsPoint = function (point) {
  14685. var delta = -BABYLON.Epsilon;
  14686. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14687. return false;
  14688. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14689. return false;
  14690. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14691. return false;
  14692. return true;
  14693. };
  14694. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14695. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14696. };
  14697. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14698. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14699. return false;
  14700. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14701. return false;
  14702. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14703. return false;
  14704. return true;
  14705. };
  14706. // Statics
  14707. BoundingBox.Intersects = function (box0, box1) {
  14708. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14709. return false;
  14710. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14711. return false;
  14712. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14713. return false;
  14714. return true;
  14715. };
  14716. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14717. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14718. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14719. return (num <= (sphereRadius * sphereRadius));
  14720. };
  14721. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14722. for (var p = 0; p < 6; p++) {
  14723. for (var i = 0; i < 8; i++) {
  14724. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14725. return false;
  14726. }
  14727. }
  14728. }
  14729. return true;
  14730. };
  14731. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14732. for (var p = 0; p < 6; p++) {
  14733. var inCount = 8;
  14734. for (var i = 0; i < 8; i++) {
  14735. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14736. --inCount;
  14737. }
  14738. else {
  14739. break;
  14740. }
  14741. }
  14742. if (inCount === 0)
  14743. return false;
  14744. }
  14745. return true;
  14746. };
  14747. return BoundingBox;
  14748. }());
  14749. BABYLON.BoundingBox = BoundingBox;
  14750. })(BABYLON || (BABYLON = {}));
  14751. //# sourceMappingURL=babylon.boundingBox.js.map
  14752. var BABYLON;
  14753. (function (BABYLON) {
  14754. var computeBoxExtents = function (axis, box) {
  14755. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14756. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14757. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14758. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14759. var r = r0 + r1 + r2;
  14760. return {
  14761. min: p - r,
  14762. max: p + r
  14763. };
  14764. };
  14765. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14766. var axisOverlap = function (axis, box0, box1) {
  14767. var result0 = computeBoxExtents(axis, box0);
  14768. var result1 = computeBoxExtents(axis, box1);
  14769. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14770. };
  14771. var BoundingInfo = /** @class */ (function () {
  14772. function BoundingInfo(minimum, maximum) {
  14773. this.minimum = minimum;
  14774. this.maximum = maximum;
  14775. this._isLocked = false;
  14776. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14777. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14778. }
  14779. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14780. get: function () {
  14781. return this._isLocked;
  14782. },
  14783. set: function (value) {
  14784. this._isLocked = value;
  14785. },
  14786. enumerable: true,
  14787. configurable: true
  14788. });
  14789. // Methods
  14790. BoundingInfo.prototype.update = function (world) {
  14791. if (this._isLocked) {
  14792. return;
  14793. }
  14794. this.boundingBox._update(world);
  14795. this.boundingSphere._update(world);
  14796. };
  14797. /**
  14798. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14799. * @param center New center of the bounding info
  14800. * @param extend New extend of the bounding info
  14801. */
  14802. BoundingInfo.prototype.centerOn = function (center, extend) {
  14803. this.minimum = center.subtract(extend);
  14804. this.maximum = center.add(extend);
  14805. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14806. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14807. return this;
  14808. };
  14809. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14810. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14811. return false;
  14812. return this.boundingBox.isInFrustum(frustumPlanes);
  14813. };
  14814. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14815. /**
  14816. * Gets the world distance between the min and max points of the bounding box
  14817. */
  14818. get: function () {
  14819. var boundingBox = this.boundingBox;
  14820. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14821. return size.length();
  14822. },
  14823. enumerable: true,
  14824. configurable: true
  14825. });
  14826. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14827. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14828. };
  14829. BoundingInfo.prototype._checkCollision = function (collider) {
  14830. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14831. };
  14832. BoundingInfo.prototype.intersectsPoint = function (point) {
  14833. if (!this.boundingSphere.centerWorld) {
  14834. return false;
  14835. }
  14836. if (!this.boundingSphere.intersectsPoint(point)) {
  14837. return false;
  14838. }
  14839. if (!this.boundingBox.intersectsPoint(point)) {
  14840. return false;
  14841. }
  14842. return true;
  14843. };
  14844. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14845. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14846. return false;
  14847. }
  14848. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14849. return false;
  14850. }
  14851. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14852. return false;
  14853. }
  14854. if (!precise) {
  14855. return true;
  14856. }
  14857. var box0 = this.boundingBox;
  14858. var box1 = boundingInfo.boundingBox;
  14859. if (!axisOverlap(box0.directions[0], box0, box1))
  14860. return false;
  14861. if (!axisOverlap(box0.directions[1], box0, box1))
  14862. return false;
  14863. if (!axisOverlap(box0.directions[2], box0, box1))
  14864. return false;
  14865. if (!axisOverlap(box1.directions[0], box0, box1))
  14866. return false;
  14867. if (!axisOverlap(box1.directions[1], box0, box1))
  14868. return false;
  14869. if (!axisOverlap(box1.directions[2], box0, box1))
  14870. return false;
  14871. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14872. return false;
  14873. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14874. return false;
  14875. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14876. return false;
  14877. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14878. return false;
  14879. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14880. return false;
  14881. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14882. return false;
  14883. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14884. return false;
  14885. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14886. return false;
  14887. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14888. return false;
  14889. return true;
  14890. };
  14891. return BoundingInfo;
  14892. }());
  14893. BABYLON.BoundingInfo = BoundingInfo;
  14894. })(BABYLON || (BABYLON = {}));
  14895. //# sourceMappingURL=babylon.boundingInfo.js.map
  14896. var BABYLON;
  14897. (function (BABYLON) {
  14898. var TransformNode = /** @class */ (function (_super) {
  14899. __extends(TransformNode, _super);
  14900. function TransformNode(name, scene, isPure) {
  14901. if (scene === void 0) { scene = null; }
  14902. if (isPure === void 0) { isPure = true; }
  14903. var _this = _super.call(this, name, scene) || this;
  14904. // Properties
  14905. _this._rotation = BABYLON.Vector3.Zero();
  14906. _this._scaling = BABYLON.Vector3.One();
  14907. _this._isDirty = false;
  14908. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14909. _this.scalingDeterminant = 1;
  14910. _this.infiniteDistance = false;
  14911. _this.position = BABYLON.Vector3.Zero();
  14912. _this._localWorld = BABYLON.Matrix.Zero();
  14913. _this._worldMatrix = BABYLON.Matrix.Zero();
  14914. _this._worldMatrixDeterminant = 0;
  14915. _this._absolutePosition = BABYLON.Vector3.Zero();
  14916. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14917. _this._postMultiplyPivotMatrix = false;
  14918. _this._isWorldMatrixFrozen = false;
  14919. /**
  14920. * An event triggered after the world matrix is updated
  14921. * @type {BABYLON.Observable}
  14922. */
  14923. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14924. _this._nonUniformScaling = false;
  14925. if (isPure) {
  14926. _this.getScene().addTransformNode(_this);
  14927. }
  14928. return _this;
  14929. }
  14930. Object.defineProperty(TransformNode.prototype, "rotation", {
  14931. /**
  14932. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14933. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14934. * Default : (0.0, 0.0, 0.0)
  14935. */
  14936. get: function () {
  14937. return this._rotation;
  14938. },
  14939. set: function (newRotation) {
  14940. this._rotation = newRotation;
  14941. },
  14942. enumerable: true,
  14943. configurable: true
  14944. });
  14945. Object.defineProperty(TransformNode.prototype, "scaling", {
  14946. /**
  14947. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14948. * Default : (1.0, 1.0, 1.0)
  14949. */
  14950. get: function () {
  14951. return this._scaling;
  14952. },
  14953. /**
  14954. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14955. * Default : (1.0, 1.0, 1.0)
  14956. */
  14957. set: function (newScaling) {
  14958. this._scaling = newScaling;
  14959. },
  14960. enumerable: true,
  14961. configurable: true
  14962. });
  14963. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14964. /**
  14965. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14966. * It's null by default.
  14967. * 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)
  14968. */
  14969. get: function () {
  14970. return this._rotationQuaternion;
  14971. },
  14972. set: function (quaternion) {
  14973. this._rotationQuaternion = quaternion;
  14974. //reset the rotation vector.
  14975. if (quaternion && this.rotation.length()) {
  14976. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14977. }
  14978. },
  14979. enumerable: true,
  14980. configurable: true
  14981. });
  14982. /**
  14983. * Returns the latest update of the World matrix
  14984. * Returns a Matrix.
  14985. */
  14986. TransformNode.prototype.getWorldMatrix = function () {
  14987. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14988. this.computeWorldMatrix();
  14989. }
  14990. return this._worldMatrix;
  14991. };
  14992. /**
  14993. * Returns the latest update of the World matrix determinant.
  14994. */
  14995. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14996. return this._worldMatrixDeterminant;
  14997. };
  14998. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14999. /**
  15000. * Returns directly the latest state of the mesh World matrix.
  15001. * A Matrix is returned.
  15002. */
  15003. get: function () {
  15004. return this._worldMatrix;
  15005. },
  15006. enumerable: true,
  15007. configurable: true
  15008. });
  15009. /**
  15010. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15011. * Returns the AbstractMesh.
  15012. */
  15013. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15014. this._poseMatrix.copyFrom(matrix);
  15015. return this;
  15016. };
  15017. /**
  15018. * Returns the mesh Pose matrix.
  15019. * Returned object : Matrix
  15020. */
  15021. TransformNode.prototype.getPoseMatrix = function () {
  15022. return this._poseMatrix;
  15023. };
  15024. TransformNode.prototype._isSynchronized = function () {
  15025. if (this._isDirty) {
  15026. return false;
  15027. }
  15028. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15029. return false;
  15030. if (this._cache.pivotMatrixUpdated) {
  15031. return false;
  15032. }
  15033. if (this.infiniteDistance) {
  15034. return false;
  15035. }
  15036. if (!this._cache.position.equals(this.position))
  15037. return false;
  15038. if (this.rotationQuaternion) {
  15039. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15040. return false;
  15041. }
  15042. if (!this._cache.rotation.equals(this.rotation))
  15043. return false;
  15044. if (!this._cache.scaling.equals(this.scaling))
  15045. return false;
  15046. return true;
  15047. };
  15048. TransformNode.prototype._initCache = function () {
  15049. _super.prototype._initCache.call(this);
  15050. this._cache.localMatrixUpdated = false;
  15051. this._cache.position = BABYLON.Vector3.Zero();
  15052. this._cache.scaling = BABYLON.Vector3.Zero();
  15053. this._cache.rotation = BABYLON.Vector3.Zero();
  15054. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15055. this._cache.billboardMode = -1;
  15056. };
  15057. TransformNode.prototype.markAsDirty = function (property) {
  15058. if (property === "rotation") {
  15059. this.rotationQuaternion = null;
  15060. }
  15061. this._currentRenderId = Number.MAX_VALUE;
  15062. this._isDirty = true;
  15063. return this;
  15064. };
  15065. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15066. /**
  15067. * Returns the current mesh absolute position.
  15068. * Retuns a Vector3.
  15069. */
  15070. get: function () {
  15071. return this._absolutePosition;
  15072. },
  15073. enumerable: true,
  15074. configurable: true
  15075. });
  15076. /**
  15077. * Sets a new pivot matrix to the mesh.
  15078. * Returns the AbstractMesh.
  15079. */
  15080. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15081. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  15082. this._pivotMatrix = matrix.clone();
  15083. this._cache.pivotMatrixUpdated = true;
  15084. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15085. if (this._postMultiplyPivotMatrix) {
  15086. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  15087. }
  15088. return this;
  15089. };
  15090. /**
  15091. * Returns the mesh pivot matrix.
  15092. * Default : Identity.
  15093. * A Matrix is returned.
  15094. */
  15095. TransformNode.prototype.getPivotMatrix = function () {
  15096. return this._pivotMatrix;
  15097. };
  15098. /**
  15099. * Prevents the World matrix to be computed any longer.
  15100. * Returns the AbstractMesh.
  15101. */
  15102. TransformNode.prototype.freezeWorldMatrix = function () {
  15103. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  15104. this.computeWorldMatrix(true);
  15105. this._isWorldMatrixFrozen = true;
  15106. return this;
  15107. };
  15108. /**
  15109. * Allows back the World matrix computation.
  15110. * Returns the AbstractMesh.
  15111. */
  15112. TransformNode.prototype.unfreezeWorldMatrix = function () {
  15113. this._isWorldMatrixFrozen = false;
  15114. this.computeWorldMatrix(true);
  15115. return this;
  15116. };
  15117. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  15118. /**
  15119. * True if the World matrix has been frozen.
  15120. * Returns a boolean.
  15121. */
  15122. get: function () {
  15123. return this._isWorldMatrixFrozen;
  15124. },
  15125. enumerable: true,
  15126. configurable: true
  15127. });
  15128. /**
  15129. * Retuns the mesh absolute position in the World.
  15130. * Returns a Vector3.
  15131. */
  15132. TransformNode.prototype.getAbsolutePosition = function () {
  15133. this.computeWorldMatrix();
  15134. return this._absolutePosition;
  15135. };
  15136. /**
  15137. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  15138. * Returns the AbstractMesh.
  15139. */
  15140. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  15141. if (!absolutePosition) {
  15142. return this;
  15143. }
  15144. var absolutePositionX;
  15145. var absolutePositionY;
  15146. var absolutePositionZ;
  15147. if (absolutePosition.x === undefined) {
  15148. if (arguments.length < 3) {
  15149. return this;
  15150. }
  15151. absolutePositionX = arguments[0];
  15152. absolutePositionY = arguments[1];
  15153. absolutePositionZ = arguments[2];
  15154. }
  15155. else {
  15156. absolutePositionX = absolutePosition.x;
  15157. absolutePositionY = absolutePosition.y;
  15158. absolutePositionZ = absolutePosition.z;
  15159. }
  15160. if (this.parent) {
  15161. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15162. invertParentWorldMatrix.invert();
  15163. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  15164. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  15165. }
  15166. else {
  15167. this.position.x = absolutePositionX;
  15168. this.position.y = absolutePositionY;
  15169. this.position.z = absolutePositionZ;
  15170. }
  15171. return this;
  15172. };
  15173. /**
  15174. * Sets the mesh position in its local space.
  15175. * Returns the AbstractMesh.
  15176. */
  15177. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  15178. this.computeWorldMatrix();
  15179. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  15180. return this;
  15181. };
  15182. /**
  15183. * Returns the mesh position in the local space from the current World matrix values.
  15184. * Returns a new Vector3.
  15185. */
  15186. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  15187. this.computeWorldMatrix();
  15188. var invLocalWorldMatrix = this._localWorld.clone();
  15189. invLocalWorldMatrix.invert();
  15190. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  15191. };
  15192. /**
  15193. * Translates the mesh along the passed Vector3 in its local space.
  15194. * Returns the AbstractMesh.
  15195. */
  15196. TransformNode.prototype.locallyTranslate = function (vector3) {
  15197. this.computeWorldMatrix(true);
  15198. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  15199. return this;
  15200. };
  15201. /**
  15202. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  15203. * @param targetPoint the position (must be in same space as current mesh) to look at
  15204. * @param yawCor optional yaw (y-axis) correction in radians
  15205. * @param pitchCor optional pitch (x-axis) correction in radians
  15206. * @param rollCor optional roll (z-axis) correction in radians
  15207. * @param space the choosen space of the target
  15208. * @returns the TransformNode.
  15209. */
  15210. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  15211. if (yawCor === void 0) { yawCor = 0; }
  15212. if (pitchCor === void 0) { pitchCor = 0; }
  15213. if (rollCor === void 0) { rollCor = 0; }
  15214. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15215. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  15216. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  15217. targetPoint.subtractToRef(pos, dv);
  15218. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  15219. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  15220. var pitch = Math.atan2(dv.y, len);
  15221. if (this.rotationQuaternion) {
  15222. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  15223. }
  15224. else {
  15225. this.rotation.x = pitch + pitchCor;
  15226. this.rotation.y = yaw + yawCor;
  15227. this.rotation.z = rollCor;
  15228. }
  15229. return this;
  15230. };
  15231. /**
  15232. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  15233. * This Vector3 is expressed in the World space.
  15234. */
  15235. TransformNode.prototype.getDirection = function (localAxis) {
  15236. var result = BABYLON.Vector3.Zero();
  15237. this.getDirectionToRef(localAxis, result);
  15238. return result;
  15239. };
  15240. /**
  15241. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  15242. * localAxis is expressed in the mesh local space.
  15243. * result is computed in the Wordl space from the mesh World matrix.
  15244. * Returns the AbstractMesh.
  15245. */
  15246. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  15247. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15248. return this;
  15249. };
  15250. TransformNode.prototype.setPivotPoint = function (point, space) {
  15251. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15252. if (this.getScene().getRenderId() == 0) {
  15253. this.computeWorldMatrix(true);
  15254. }
  15255. var wm = this.getWorldMatrix();
  15256. if (space == BABYLON.Space.WORLD) {
  15257. var tmat = BABYLON.Tmp.Matrix[0];
  15258. wm.invertToRef(tmat);
  15259. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  15260. }
  15261. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  15262. this._pivotMatrix.m[12] = -point.x;
  15263. this._pivotMatrix.m[13] = -point.y;
  15264. this._pivotMatrix.m[14] = -point.z;
  15265. this._cache.pivotMatrixUpdated = true;
  15266. return this;
  15267. };
  15268. /**
  15269. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  15270. */
  15271. TransformNode.prototype.getPivotPoint = function () {
  15272. var point = BABYLON.Vector3.Zero();
  15273. this.getPivotPointToRef(point);
  15274. return point;
  15275. };
  15276. /**
  15277. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  15278. * Returns the AbstractMesh.
  15279. */
  15280. TransformNode.prototype.getPivotPointToRef = function (result) {
  15281. result.x = -this._pivotMatrix.m[12];
  15282. result.y = -this._pivotMatrix.m[13];
  15283. result.z = -this._pivotMatrix.m[14];
  15284. return this;
  15285. };
  15286. /**
  15287. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  15288. */
  15289. TransformNode.prototype.getAbsolutePivotPoint = function () {
  15290. var point = BABYLON.Vector3.Zero();
  15291. this.getAbsolutePivotPointToRef(point);
  15292. return point;
  15293. };
  15294. /**
  15295. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  15296. * Returns the AbstractMesh.
  15297. */
  15298. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  15299. result.x = this._pivotMatrix.m[12];
  15300. result.y = this._pivotMatrix.m[13];
  15301. result.z = this._pivotMatrix.m[14];
  15302. this.getPivotPointToRef(result);
  15303. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  15304. return this;
  15305. };
  15306. /**
  15307. * Defines the passed node as the parent of the current node.
  15308. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  15309. * Returns the TransformNode.
  15310. */
  15311. TransformNode.prototype.setParent = function (node) {
  15312. if (node === null) {
  15313. var rotation = BABYLON.Tmp.Quaternion[0];
  15314. var position = BABYLON.Tmp.Vector3[0];
  15315. var scale = BABYLON.Tmp.Vector3[1];
  15316. if (this.parent && this.parent.computeWorldMatrix) {
  15317. this.parent.computeWorldMatrix(true);
  15318. }
  15319. this.computeWorldMatrix(true);
  15320. this.getWorldMatrix().decompose(scale, rotation, position);
  15321. if (this.rotationQuaternion) {
  15322. this.rotationQuaternion.copyFrom(rotation);
  15323. }
  15324. else {
  15325. rotation.toEulerAnglesToRef(this.rotation);
  15326. }
  15327. this.scaling.x = scale.x;
  15328. this.scaling.y = scale.y;
  15329. this.scaling.z = scale.z;
  15330. this.position.x = position.x;
  15331. this.position.y = position.y;
  15332. this.position.z = position.z;
  15333. }
  15334. else {
  15335. var rotation = BABYLON.Tmp.Quaternion[0];
  15336. var position = BABYLON.Tmp.Vector3[0];
  15337. var scale = BABYLON.Tmp.Vector3[1];
  15338. var diffMatrix = BABYLON.Tmp.Matrix[0];
  15339. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  15340. this.computeWorldMatrix(true);
  15341. node.computeWorldMatrix(true);
  15342. node.getWorldMatrix().invertToRef(invParentMatrix);
  15343. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  15344. diffMatrix.decompose(scale, rotation, position);
  15345. if (this.rotationQuaternion) {
  15346. this.rotationQuaternion.copyFrom(rotation);
  15347. }
  15348. else {
  15349. rotation.toEulerAnglesToRef(this.rotation);
  15350. }
  15351. this.position.x = position.x;
  15352. this.position.y = position.y;
  15353. this.position.z = position.z;
  15354. this.scaling.x = scale.x;
  15355. this.scaling.y = scale.y;
  15356. this.scaling.z = scale.z;
  15357. }
  15358. this.parent = node;
  15359. return this;
  15360. };
  15361. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  15362. get: function () {
  15363. return this._nonUniformScaling;
  15364. },
  15365. enumerable: true,
  15366. configurable: true
  15367. });
  15368. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  15369. if (this._nonUniformScaling === value) {
  15370. return false;
  15371. }
  15372. this._nonUniformScaling = true;
  15373. return true;
  15374. };
  15375. /**
  15376. * Attach the current TransformNode to another TransformNode associated with a bone
  15377. * @param bone Bone affecting the TransformNode
  15378. * @param affectedTransformNode TransformNode associated with the bone
  15379. */
  15380. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  15381. this._transformToBoneReferal = affectedTransformNode;
  15382. this.parent = bone;
  15383. if (bone.getWorldMatrix().determinant() < 0) {
  15384. this.scalingDeterminant *= -1;
  15385. }
  15386. return this;
  15387. };
  15388. TransformNode.prototype.detachFromBone = function () {
  15389. if (!this.parent) {
  15390. return this;
  15391. }
  15392. if (this.parent.getWorldMatrix().determinant() < 0) {
  15393. this.scalingDeterminant *= -1;
  15394. }
  15395. this._transformToBoneReferal = null;
  15396. this.parent = null;
  15397. return this;
  15398. };
  15399. /**
  15400. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  15401. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15402. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15403. * The passed axis is also normalized.
  15404. * Returns the AbstractMesh.
  15405. */
  15406. TransformNode.prototype.rotate = function (axis, amount, space) {
  15407. axis.normalize();
  15408. if (!this.rotationQuaternion) {
  15409. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15410. this.rotation = BABYLON.Vector3.Zero();
  15411. }
  15412. var rotationQuaternion;
  15413. if (!space || space === BABYLON.Space.LOCAL) {
  15414. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15415. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  15416. }
  15417. else {
  15418. if (this.parent) {
  15419. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15420. invertParentWorldMatrix.invert();
  15421. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  15422. }
  15423. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15424. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15425. }
  15426. return this;
  15427. };
  15428. /**
  15429. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  15430. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15431. * The passed axis is also normalized.
  15432. * Returns the AbstractMesh.
  15433. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  15434. */
  15435. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  15436. axis.normalize();
  15437. if (!this.rotationQuaternion) {
  15438. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15439. this.rotation.copyFromFloats(0, 0, 0);
  15440. }
  15441. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  15442. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  15443. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  15444. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  15445. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  15446. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  15447. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  15448. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  15449. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15450. return this;
  15451. };
  15452. /**
  15453. * Translates the mesh along the axis vector for the passed distance in the given space.
  15454. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15455. * Returns the AbstractMesh.
  15456. */
  15457. TransformNode.prototype.translate = function (axis, distance, space) {
  15458. var displacementVector = axis.scale(distance);
  15459. if (!space || space === BABYLON.Space.LOCAL) {
  15460. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  15461. this.setPositionWithLocalVector(tempV3);
  15462. }
  15463. else {
  15464. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  15465. }
  15466. return this;
  15467. };
  15468. /**
  15469. * Adds a rotation step to the mesh current rotation.
  15470. * x, y, z are Euler angles expressed in radians.
  15471. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  15472. * This means this rotation is made in the mesh local space only.
  15473. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  15474. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  15475. * ```javascript
  15476. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  15477. * ```
  15478. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  15479. * 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.
  15480. * Returns the AbstractMesh.
  15481. */
  15482. TransformNode.prototype.addRotation = function (x, y, z) {
  15483. var rotationQuaternion;
  15484. if (this.rotationQuaternion) {
  15485. rotationQuaternion = this.rotationQuaternion;
  15486. }
  15487. else {
  15488. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15489. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15490. }
  15491. var accumulation = BABYLON.Tmp.Quaternion[0];
  15492. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15493. rotationQuaternion.multiplyInPlace(accumulation);
  15494. if (!this.rotationQuaternion) {
  15495. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15496. }
  15497. return this;
  15498. };
  15499. /**
  15500. * Computes the mesh World matrix and returns it.
  15501. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15502. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15503. * If the parameter `force`is set to `true`, the actual computation is done.
  15504. * Returns the mesh World Matrix.
  15505. */
  15506. TransformNode.prototype.computeWorldMatrix = function (force) {
  15507. if (this._isWorldMatrixFrozen) {
  15508. return this._worldMatrix;
  15509. }
  15510. if (!force && this.isSynchronized(true)) {
  15511. return this._worldMatrix;
  15512. }
  15513. this._cache.position.copyFrom(this.position);
  15514. this._cache.scaling.copyFrom(this.scaling);
  15515. this._cache.pivotMatrixUpdated = false;
  15516. this._cache.billboardMode = this.billboardMode;
  15517. this._currentRenderId = this.getScene().getRenderId();
  15518. this._isDirty = false;
  15519. // Scaling
  15520. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15521. // Rotation
  15522. //rotate, if quaternion is set and rotation was used
  15523. if (this.rotationQuaternion) {
  15524. var len = this.rotation.length();
  15525. if (len) {
  15526. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15527. this.rotation.copyFromFloats(0, 0, 0);
  15528. }
  15529. }
  15530. if (this.rotationQuaternion) {
  15531. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15532. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15533. }
  15534. else {
  15535. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15536. this._cache.rotation.copyFrom(this.rotation);
  15537. }
  15538. // Translation
  15539. var camera = this.getScene().activeCamera;
  15540. if (this.infiniteDistance && !this.parent && camera) {
  15541. var cameraWorldMatrix = camera.getWorldMatrix();
  15542. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15543. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15544. }
  15545. else {
  15546. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15547. }
  15548. // Composing transformations
  15549. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15550. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15551. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15552. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15553. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15554. // Need to decompose each rotation here
  15555. var currentPosition = BABYLON.Tmp.Vector3[3];
  15556. if (this.parent && this.parent.getWorldMatrix) {
  15557. if (this._transformToBoneReferal) {
  15558. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15559. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15560. }
  15561. else {
  15562. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15563. }
  15564. }
  15565. else {
  15566. currentPosition.copyFrom(this.position);
  15567. }
  15568. currentPosition.subtractInPlace(camera.globalPosition);
  15569. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15570. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15571. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15572. }
  15573. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15574. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15575. }
  15576. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15577. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15578. }
  15579. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15580. }
  15581. else {
  15582. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15583. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15584. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15585. }
  15586. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15587. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15588. }
  15589. // Local world
  15590. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15591. // Parent
  15592. if (this.parent && this.parent.getWorldMatrix) {
  15593. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15594. if (this._transformToBoneReferal) {
  15595. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15596. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15597. }
  15598. else {
  15599. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15600. }
  15601. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15602. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15603. this._worldMatrix.copyFrom(this._localWorld);
  15604. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15605. }
  15606. else {
  15607. if (this._transformToBoneReferal) {
  15608. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15609. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15610. }
  15611. else {
  15612. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15613. }
  15614. }
  15615. this._markSyncedWithParent();
  15616. }
  15617. else {
  15618. this._worldMatrix.copyFrom(this._localWorld);
  15619. }
  15620. // Post multiply inverse of pivotMatrix
  15621. if (this._postMultiplyPivotMatrix) {
  15622. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15623. }
  15624. // Normal matrix
  15625. if (this.scaling.isNonUniform) {
  15626. this._updateNonUniformScalingState(true);
  15627. }
  15628. else if (this.parent && this.parent._nonUniformScaling) {
  15629. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15630. }
  15631. else {
  15632. this._updateNonUniformScalingState(false);
  15633. }
  15634. this._afterComputeWorldMatrix();
  15635. // Absolute position
  15636. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15637. // Callbacks
  15638. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15639. if (!this._poseMatrix) {
  15640. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15641. }
  15642. // Cache the determinant
  15643. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15644. return this._worldMatrix;
  15645. };
  15646. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15647. };
  15648. /**
  15649. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15650. * @param func: callback function to add
  15651. *
  15652. * Returns the TransformNode.
  15653. */
  15654. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15655. this.onAfterWorldMatrixUpdateObservable.add(func);
  15656. return this;
  15657. };
  15658. /**
  15659. * Removes a registered callback function.
  15660. * Returns the TransformNode.
  15661. */
  15662. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15663. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15664. return this;
  15665. };
  15666. /**
  15667. * Clone the current transform node
  15668. * Returns the new transform node
  15669. * @param name Name of the new clone
  15670. * @param newParent New parent for the clone
  15671. * @param doNotCloneChildren Do not clone children hierarchy
  15672. */
  15673. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15674. var _this = this;
  15675. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15676. result.name = name;
  15677. result.id = name;
  15678. if (newParent) {
  15679. result.parent = newParent;
  15680. }
  15681. if (!doNotCloneChildren) {
  15682. // Children
  15683. var directDescendants = this.getDescendants(true);
  15684. for (var index = 0; index < directDescendants.length; index++) {
  15685. var child = directDescendants[index];
  15686. if (child.clone) {
  15687. child.clone(name + "." + child.name, result);
  15688. }
  15689. }
  15690. }
  15691. return result;
  15692. };
  15693. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15694. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15695. serializationObject.type = this.getClassName();
  15696. // Parent
  15697. if (this.parent) {
  15698. serializationObject.parentId = this.parent.id;
  15699. }
  15700. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15701. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15702. }
  15703. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15704. serializationObject.isEnabled = this.isEnabled();
  15705. // Parent
  15706. if (this.parent) {
  15707. serializationObject.parentId = this.parent.id;
  15708. }
  15709. return serializationObject;
  15710. };
  15711. // Statics
  15712. /**
  15713. * Returns a new TransformNode object parsed from the source provided.
  15714. * The parameter `parsedMesh` is the source.
  15715. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15716. */
  15717. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15718. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15719. if (BABYLON.Tags) {
  15720. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15721. }
  15722. if (parsedTransformNode.localMatrix) {
  15723. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15724. }
  15725. else if (parsedTransformNode.pivotMatrix) {
  15726. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15727. }
  15728. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15729. // Parent
  15730. if (parsedTransformNode.parentId) {
  15731. transformNode._waitingParentId = parsedTransformNode.parentId;
  15732. }
  15733. return transformNode;
  15734. };
  15735. /**
  15736. * Disposes the TransformNode.
  15737. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15738. * Returns nothing.
  15739. */
  15740. TransformNode.prototype.dispose = function (doNotRecurse) {
  15741. // Animations
  15742. this.getScene().stopAnimation(this);
  15743. // Remove from scene
  15744. this.getScene().removeTransformNode(this);
  15745. if (!doNotRecurse) {
  15746. // Children
  15747. var objects = this.getDescendants(true);
  15748. for (var index = 0; index < objects.length; index++) {
  15749. objects[index].dispose();
  15750. }
  15751. }
  15752. else {
  15753. var childMeshes = this.getChildMeshes(true);
  15754. for (index = 0; index < childMeshes.length; index++) {
  15755. var child = childMeshes[index];
  15756. child.parent = null;
  15757. child.computeWorldMatrix(true);
  15758. }
  15759. }
  15760. this.onAfterWorldMatrixUpdateObservable.clear();
  15761. _super.prototype.dispose.call(this);
  15762. };
  15763. // Statics
  15764. TransformNode.BILLBOARDMODE_NONE = 0;
  15765. TransformNode.BILLBOARDMODE_X = 1;
  15766. TransformNode.BILLBOARDMODE_Y = 2;
  15767. TransformNode.BILLBOARDMODE_Z = 4;
  15768. TransformNode.BILLBOARDMODE_ALL = 7;
  15769. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15770. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15771. __decorate([
  15772. BABYLON.serializeAsVector3()
  15773. ], TransformNode.prototype, "_rotation", void 0);
  15774. __decorate([
  15775. BABYLON.serializeAsQuaternion()
  15776. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15777. __decorate([
  15778. BABYLON.serializeAsVector3()
  15779. ], TransformNode.prototype, "_scaling", void 0);
  15780. __decorate([
  15781. BABYLON.serialize()
  15782. ], TransformNode.prototype, "billboardMode", void 0);
  15783. __decorate([
  15784. BABYLON.serialize()
  15785. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15786. __decorate([
  15787. BABYLON.serialize()
  15788. ], TransformNode.prototype, "infiniteDistance", void 0);
  15789. __decorate([
  15790. BABYLON.serializeAsVector3()
  15791. ], TransformNode.prototype, "position", void 0);
  15792. return TransformNode;
  15793. }(BABYLON.Node));
  15794. BABYLON.TransformNode = TransformNode;
  15795. })(BABYLON || (BABYLON = {}));
  15796. //# sourceMappingURL=babylon.transformNode.js.map
  15797. var BABYLON;
  15798. (function (BABYLON) {
  15799. var AbstractMesh = /** @class */ (function (_super) {
  15800. __extends(AbstractMesh, _super);
  15801. // Constructor
  15802. function AbstractMesh(name, scene) {
  15803. if (scene === void 0) { scene = null; }
  15804. var _this = _super.call(this, name, scene, false) || this;
  15805. _this._facetNb = 0; // facet number
  15806. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15807. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15808. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15809. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15810. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15811. _this._subDiv = {
  15812. max: 1,
  15813. X: 1,
  15814. Y: 1,
  15815. Z: 1
  15816. };
  15817. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15818. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15819. // Events
  15820. /**
  15821. * An event triggered when this mesh collides with another one
  15822. * @type {BABYLON.Observable}
  15823. */
  15824. _this.onCollideObservable = new BABYLON.Observable();
  15825. /**
  15826. * An event triggered when the collision's position changes
  15827. * @type {BABYLON.Observable}
  15828. */
  15829. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15830. /**
  15831. * An event triggered when material is changed
  15832. * @type {BABYLON.Observable}
  15833. */
  15834. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15835. // Properties
  15836. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15837. /**
  15838. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15839. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15840. * or
  15841. * 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.
  15842. * for more info check WebGl documentations
  15843. */
  15844. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15845. /**
  15846. * 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:
  15847. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15848. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15849. * 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.
  15850. */
  15851. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15852. /**
  15853. * 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.
  15854. * The default value is -1 which means don't break the query and wait till the result.
  15855. */
  15856. _this.occlusionRetryCount = -1;
  15857. _this._occlusionInternalRetryCounter = 0;
  15858. _this._isOccluded = false;
  15859. _this._isOcclusionQueryInProgress = false;
  15860. _this._visibility = 1.0;
  15861. _this.alphaIndex = Number.MAX_VALUE;
  15862. _this.isVisible = true;
  15863. _this.isPickable = true;
  15864. _this.showBoundingBox = false;
  15865. _this.showSubMeshesBoundingBox = false;
  15866. _this.isBlocker = false;
  15867. _this.enablePointerMoveEvents = false;
  15868. _this.renderingGroupId = 0;
  15869. _this._receiveShadows = false;
  15870. _this.renderOutline = false;
  15871. _this.outlineColor = BABYLON.Color3.Red();
  15872. _this.outlineWidth = 0.02;
  15873. _this.renderOverlay = false;
  15874. _this.overlayColor = BABYLON.Color3.Red();
  15875. _this.overlayAlpha = 0.5;
  15876. _this._hasVertexAlpha = false;
  15877. _this._useVertexColors = true;
  15878. _this._computeBonesUsingShaders = true;
  15879. _this._numBoneInfluencers = 4;
  15880. _this._applyFog = true;
  15881. _this.useOctreeForRenderingSelection = true;
  15882. _this.useOctreeForPicking = true;
  15883. _this.useOctreeForCollisions = true;
  15884. _this._layerMask = 0x0FFFFFFF;
  15885. /**
  15886. * True if the mesh must be rendered in any case.
  15887. */
  15888. _this.alwaysSelectAsActiveMesh = false;
  15889. /**
  15890. * This scene's action manager
  15891. * @type {BABYLON.ActionManager}
  15892. */
  15893. _this.actionManager = null;
  15894. // Physics
  15895. _this.physicsImpostor = null;
  15896. // Collisions
  15897. _this._checkCollisions = false;
  15898. _this._collisionMask = -1;
  15899. _this._collisionGroup = -1;
  15900. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15901. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15902. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15903. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15904. // Edges
  15905. _this.edgesWidth = 1;
  15906. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15907. // Cache
  15908. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15909. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15910. _this._isDisposed = false;
  15911. _this._renderId = 0;
  15912. _this._intersectionsInProgress = new Array();
  15913. _this._unIndexed = false;
  15914. _this._lightSources = new Array();
  15915. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15916. if (collidedMesh === void 0) { collidedMesh = null; }
  15917. //TODO move this to the collision coordinator!
  15918. if (_this.getScene().workerCollisions)
  15919. newPosition.multiplyInPlace(_this._collider._radius);
  15920. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15921. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15922. _this.position.addInPlace(_this._diffPositionForCollisions);
  15923. }
  15924. if (collidedMesh) {
  15925. _this.onCollideObservable.notifyObservers(collidedMesh);
  15926. }
  15927. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15928. };
  15929. _this.getScene().addMesh(_this);
  15930. _this._resyncLightSources();
  15931. return _this;
  15932. }
  15933. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15934. get: function () {
  15935. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15936. },
  15937. enumerable: true,
  15938. configurable: true
  15939. });
  15940. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15941. get: function () {
  15942. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15943. },
  15944. enumerable: true,
  15945. configurable: true
  15946. });
  15947. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15948. get: function () {
  15949. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15950. },
  15951. enumerable: true,
  15952. configurable: true
  15953. });
  15954. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15955. get: function () {
  15956. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15957. },
  15958. enumerable: true,
  15959. configurable: true
  15960. });
  15961. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15962. get: function () {
  15963. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15964. },
  15965. enumerable: true,
  15966. configurable: true
  15967. });
  15968. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15969. /**
  15970. * Read-only : the number of facets in the mesh
  15971. */
  15972. get: function () {
  15973. return this._facetNb;
  15974. },
  15975. enumerable: true,
  15976. configurable: true
  15977. });
  15978. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15979. /**
  15980. * The number (integer) of subdivisions per axis in the partioning space
  15981. */
  15982. get: function () {
  15983. return this._partitioningSubdivisions;
  15984. },
  15985. set: function (nb) {
  15986. this._partitioningSubdivisions = nb;
  15987. },
  15988. enumerable: true,
  15989. configurable: true
  15990. });
  15991. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15992. /**
  15993. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15994. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15995. */
  15996. get: function () {
  15997. return this._partitioningBBoxRatio;
  15998. },
  15999. set: function (ratio) {
  16000. this._partitioningBBoxRatio = ratio;
  16001. },
  16002. enumerable: true,
  16003. configurable: true
  16004. });
  16005. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16006. /**
  16007. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16008. * Works only for updatable meshes.
  16009. * Doesn't work with multi-materials.
  16010. */
  16011. get: function () {
  16012. return this._facetDepthSort;
  16013. },
  16014. set: function (sort) {
  16015. this._facetDepthSort = sort;
  16016. },
  16017. enumerable: true,
  16018. configurable: true
  16019. });
  16020. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16021. /**
  16022. * The location (Vector3) where the facet depth sort must be computed from.
  16023. * By default, the active camera position.
  16024. * Used only when facet depth sort is enabled.
  16025. */
  16026. get: function () {
  16027. return this._facetDepthSortFrom;
  16028. },
  16029. set: function (location) {
  16030. this._facetDepthSortFrom = location;
  16031. },
  16032. enumerable: true,
  16033. configurable: true
  16034. });
  16035. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16036. /**
  16037. * Read-only boolean : is the feature facetData enabled ?
  16038. */
  16039. get: function () {
  16040. return this._facetDataEnabled;
  16041. },
  16042. enumerable: true,
  16043. configurable: true
  16044. });
  16045. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16046. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16047. return false;
  16048. }
  16049. this._markSubMeshesAsMiscDirty();
  16050. return true;
  16051. };
  16052. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16053. set: function (callback) {
  16054. if (this._onCollideObserver) {
  16055. this.onCollideObservable.remove(this._onCollideObserver);
  16056. }
  16057. this._onCollideObserver = this.onCollideObservable.add(callback);
  16058. },
  16059. enumerable: true,
  16060. configurable: true
  16061. });
  16062. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16063. set: function (callback) {
  16064. if (this._onCollisionPositionChangeObserver) {
  16065. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16066. }
  16067. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16068. },
  16069. enumerable: true,
  16070. configurable: true
  16071. });
  16072. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16073. /**
  16074. * 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.
  16075. */
  16076. get: function () {
  16077. return this._isOccluded;
  16078. },
  16079. set: function (value) {
  16080. this._isOccluded = value;
  16081. },
  16082. enumerable: true,
  16083. configurable: true
  16084. });
  16085. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16086. /**
  16087. * Flag to check the progress status of the query
  16088. */
  16089. get: function () {
  16090. return this._isOcclusionQueryInProgress;
  16091. },
  16092. enumerable: true,
  16093. configurable: true
  16094. });
  16095. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16096. /**
  16097. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16098. */
  16099. get: function () {
  16100. return this._visibility;
  16101. },
  16102. /**
  16103. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16104. */
  16105. set: function (value) {
  16106. if (this._visibility === value) {
  16107. return;
  16108. }
  16109. this._visibility = value;
  16110. this._markSubMeshesAsMiscDirty();
  16111. },
  16112. enumerable: true,
  16113. configurable: true
  16114. });
  16115. Object.defineProperty(AbstractMesh.prototype, "material", {
  16116. get: function () {
  16117. return this._material;
  16118. },
  16119. set: function (value) {
  16120. if (this._material === value) {
  16121. return;
  16122. }
  16123. this._material = value;
  16124. if (this.onMaterialChangedObservable.hasObservers) {
  16125. this.onMaterialChangedObservable.notifyObservers(this);
  16126. }
  16127. if (!this.subMeshes) {
  16128. return;
  16129. }
  16130. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16131. var subMesh = _a[_i];
  16132. subMesh.setEffect(null);
  16133. }
  16134. },
  16135. enumerable: true,
  16136. configurable: true
  16137. });
  16138. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  16139. get: function () {
  16140. return this._receiveShadows;
  16141. },
  16142. set: function (value) {
  16143. if (this._receiveShadows === value) {
  16144. return;
  16145. }
  16146. this._receiveShadows = value;
  16147. this._markSubMeshesAsLightDirty();
  16148. },
  16149. enumerable: true,
  16150. configurable: true
  16151. });
  16152. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  16153. get: function () {
  16154. return this._hasVertexAlpha;
  16155. },
  16156. set: function (value) {
  16157. if (this._hasVertexAlpha === value) {
  16158. return;
  16159. }
  16160. this._hasVertexAlpha = value;
  16161. this._markSubMeshesAsAttributesDirty();
  16162. this._markSubMeshesAsMiscDirty();
  16163. },
  16164. enumerable: true,
  16165. configurable: true
  16166. });
  16167. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  16168. get: function () {
  16169. return this._useVertexColors;
  16170. },
  16171. set: function (value) {
  16172. if (this._useVertexColors === value) {
  16173. return;
  16174. }
  16175. this._useVertexColors = value;
  16176. this._markSubMeshesAsAttributesDirty();
  16177. },
  16178. enumerable: true,
  16179. configurable: true
  16180. });
  16181. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  16182. get: function () {
  16183. return this._computeBonesUsingShaders;
  16184. },
  16185. set: function (value) {
  16186. if (this._computeBonesUsingShaders === value) {
  16187. return;
  16188. }
  16189. this._computeBonesUsingShaders = value;
  16190. this._markSubMeshesAsAttributesDirty();
  16191. },
  16192. enumerable: true,
  16193. configurable: true
  16194. });
  16195. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  16196. get: function () {
  16197. return this._numBoneInfluencers;
  16198. },
  16199. set: function (value) {
  16200. if (this._numBoneInfluencers === value) {
  16201. return;
  16202. }
  16203. this._numBoneInfluencers = value;
  16204. this._markSubMeshesAsAttributesDirty();
  16205. },
  16206. enumerable: true,
  16207. configurable: true
  16208. });
  16209. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  16210. get: function () {
  16211. return this._applyFog;
  16212. },
  16213. set: function (value) {
  16214. if (this._applyFog === value) {
  16215. return;
  16216. }
  16217. this._applyFog = value;
  16218. this._markSubMeshesAsMiscDirty();
  16219. },
  16220. enumerable: true,
  16221. configurable: true
  16222. });
  16223. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  16224. get: function () {
  16225. return this._layerMask;
  16226. },
  16227. set: function (value) {
  16228. if (value === this._layerMask) {
  16229. return;
  16230. }
  16231. this._layerMask = value;
  16232. this._resyncLightSources();
  16233. },
  16234. enumerable: true,
  16235. configurable: true
  16236. });
  16237. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  16238. get: function () {
  16239. return this._collisionMask;
  16240. },
  16241. set: function (mask) {
  16242. this._collisionMask = !isNaN(mask) ? mask : -1;
  16243. },
  16244. enumerable: true,
  16245. configurable: true
  16246. });
  16247. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  16248. get: function () {
  16249. return this._collisionGroup;
  16250. },
  16251. set: function (mask) {
  16252. this._collisionGroup = !isNaN(mask) ? mask : -1;
  16253. },
  16254. enumerable: true,
  16255. configurable: true
  16256. });
  16257. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  16258. get: function () {
  16259. return null;
  16260. },
  16261. enumerable: true,
  16262. configurable: true
  16263. });
  16264. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  16265. get: function () {
  16266. return this._skeleton;
  16267. },
  16268. set: function (value) {
  16269. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  16270. this._skeleton._unregisterMeshWithPoseMatrix(this);
  16271. }
  16272. if (value && value.needInitialSkinMatrix) {
  16273. value._registerMeshWithPoseMatrix(this);
  16274. }
  16275. this._skeleton = value;
  16276. if (!this._skeleton) {
  16277. this._bonesTransformMatrices = null;
  16278. }
  16279. this._markSubMeshesAsAttributesDirty();
  16280. },
  16281. enumerable: true,
  16282. configurable: true
  16283. });
  16284. /**
  16285. * Boolean : true if the mesh has been disposed.
  16286. */
  16287. AbstractMesh.prototype.isDisposed = function () {
  16288. return this._isDisposed;
  16289. };
  16290. /**
  16291. * Returns the string "AbstractMesh"
  16292. */
  16293. AbstractMesh.prototype.getClassName = function () {
  16294. return "AbstractMesh";
  16295. };
  16296. /**
  16297. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16298. */
  16299. AbstractMesh.prototype.toString = function (fullDetails) {
  16300. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  16301. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  16302. if (this._skeleton) {
  16303. ret += ", skeleton: " + this._skeleton.name;
  16304. }
  16305. if (fullDetails) {
  16306. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  16307. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  16308. }
  16309. return ret;
  16310. };
  16311. AbstractMesh.prototype._rebuild = function () {
  16312. if (this._occlusionQuery) {
  16313. this._occlusionQuery = null;
  16314. }
  16315. if (this._edgesRenderer) {
  16316. this._edgesRenderer._rebuild();
  16317. }
  16318. if (!this.subMeshes) {
  16319. return;
  16320. }
  16321. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16322. var subMesh = _a[_i];
  16323. subMesh._rebuild();
  16324. }
  16325. };
  16326. AbstractMesh.prototype._resyncLightSources = function () {
  16327. this._lightSources.length = 0;
  16328. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  16329. var light = _a[_i];
  16330. if (!light.isEnabled()) {
  16331. continue;
  16332. }
  16333. if (light.canAffectMesh(this)) {
  16334. this._lightSources.push(light);
  16335. }
  16336. }
  16337. this._markSubMeshesAsLightDirty();
  16338. };
  16339. AbstractMesh.prototype._resyncLighSource = function (light) {
  16340. var isIn = light.isEnabled() && light.canAffectMesh(this);
  16341. var index = this._lightSources.indexOf(light);
  16342. if (index === -1) {
  16343. if (!isIn) {
  16344. return;
  16345. }
  16346. this._lightSources.push(light);
  16347. }
  16348. else {
  16349. if (isIn) {
  16350. return;
  16351. }
  16352. this._lightSources.splice(index, 1);
  16353. }
  16354. this._markSubMeshesAsLightDirty();
  16355. };
  16356. AbstractMesh.prototype._removeLightSource = function (light) {
  16357. var index = this._lightSources.indexOf(light);
  16358. if (index === -1) {
  16359. return;
  16360. }
  16361. this._lightSources.splice(index, 1);
  16362. this._markSubMeshesAsLightDirty();
  16363. };
  16364. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  16365. if (!this.subMeshes) {
  16366. return;
  16367. }
  16368. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16369. var subMesh = _a[_i];
  16370. if (subMesh._materialDefines) {
  16371. func(subMesh._materialDefines);
  16372. }
  16373. }
  16374. };
  16375. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  16376. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  16377. };
  16378. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  16379. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  16380. };
  16381. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  16382. if (!this.subMeshes) {
  16383. return;
  16384. }
  16385. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16386. var subMesh = _a[_i];
  16387. var material = subMesh.getMaterial();
  16388. if (material) {
  16389. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  16390. }
  16391. }
  16392. };
  16393. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  16394. /**
  16395. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16396. * Default : (1.0, 1.0, 1.0)
  16397. */
  16398. get: function () {
  16399. return this._scaling;
  16400. },
  16401. /**
  16402. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16403. * Default : (1.0, 1.0, 1.0)
  16404. */
  16405. set: function (newScaling) {
  16406. this._scaling = newScaling;
  16407. if (this.physicsImpostor) {
  16408. this.physicsImpostor.forceUpdate();
  16409. }
  16410. },
  16411. enumerable: true,
  16412. configurable: true
  16413. });
  16414. // Methods
  16415. /**
  16416. * Disables the mesh edger rendering mode.
  16417. * Returns the AbstractMesh.
  16418. */
  16419. AbstractMesh.prototype.disableEdgesRendering = function () {
  16420. if (this._edgesRenderer) {
  16421. this._edgesRenderer.dispose();
  16422. this._edgesRenderer = null;
  16423. }
  16424. return this;
  16425. };
  16426. /**
  16427. * Enables the edge rendering mode on the mesh.
  16428. * This mode makes the mesh edges visible.
  16429. * Returns the AbstractMesh.
  16430. */
  16431. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  16432. if (epsilon === void 0) { epsilon = 0.95; }
  16433. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  16434. this.disableEdgesRendering();
  16435. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  16436. return this;
  16437. };
  16438. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  16439. /**
  16440. * Returns true if the mesh is blocked. Used by the class Mesh.
  16441. * Returns the boolean `false` by default.
  16442. */
  16443. get: function () {
  16444. return false;
  16445. },
  16446. enumerable: true,
  16447. configurable: true
  16448. });
  16449. /**
  16450. * Returns the mesh itself by default, used by the class Mesh.
  16451. * Returned type : AbstractMesh
  16452. */
  16453. AbstractMesh.prototype.getLOD = function (camera) {
  16454. return this;
  16455. };
  16456. /**
  16457. * Returns 0 by default, used by the class Mesh.
  16458. * Returns an integer.
  16459. */
  16460. AbstractMesh.prototype.getTotalVertices = function () {
  16461. return 0;
  16462. };
  16463. /**
  16464. * Returns null by default, used by the class Mesh.
  16465. * Returned type : integer array
  16466. */
  16467. AbstractMesh.prototype.getIndices = function () {
  16468. return null;
  16469. };
  16470. /**
  16471. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  16472. * Returned type : float array or Float32Array
  16473. */
  16474. AbstractMesh.prototype.getVerticesData = function (kind) {
  16475. return null;
  16476. };
  16477. /**
  16478. * Sets the vertex data of the mesh geometry for the requested `kind`.
  16479. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  16480. * The `data` are either a numeric array either a Float32Array.
  16481. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  16482. * 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).
  16483. * Note that a new underlying VertexBuffer object is created each call.
  16484. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  16485. *
  16486. * Possible `kind` values :
  16487. * - BABYLON.VertexBuffer.PositionKind
  16488. * - BABYLON.VertexBuffer.UVKind
  16489. * - BABYLON.VertexBuffer.UV2Kind
  16490. * - BABYLON.VertexBuffer.UV3Kind
  16491. * - BABYLON.VertexBuffer.UV4Kind
  16492. * - BABYLON.VertexBuffer.UV5Kind
  16493. * - BABYLON.VertexBuffer.UV6Kind
  16494. * - BABYLON.VertexBuffer.ColorKind
  16495. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16496. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16497. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16498. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16499. *
  16500. * Returns the Mesh.
  16501. */
  16502. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16503. return this;
  16504. };
  16505. /**
  16506. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  16507. * If the mesh has no geometry, it is simply returned as it is.
  16508. * The `data` are either a numeric array either a Float32Array.
  16509. * No new underlying VertexBuffer object is created.
  16510. * 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.
  16511. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16512. *
  16513. * Possible `kind` values :
  16514. * - BABYLON.VertexBuffer.PositionKind
  16515. * - BABYLON.VertexBuffer.UVKind
  16516. * - BABYLON.VertexBuffer.UV2Kind
  16517. * - BABYLON.VertexBuffer.UV3Kind
  16518. * - BABYLON.VertexBuffer.UV4Kind
  16519. * - BABYLON.VertexBuffer.UV5Kind
  16520. * - BABYLON.VertexBuffer.UV6Kind
  16521. * - BABYLON.VertexBuffer.ColorKind
  16522. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16523. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16524. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16525. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16526. *
  16527. * Returns the Mesh.
  16528. */
  16529. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16530. return this;
  16531. };
  16532. /**
  16533. * Sets the mesh indices.
  16534. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16535. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16536. * This method creates a new index buffer each call.
  16537. * Returns the Mesh.
  16538. */
  16539. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16540. return this;
  16541. };
  16542. /** Returns false by default, used by the class Mesh.
  16543. * Returns a boolean
  16544. */
  16545. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16546. return false;
  16547. };
  16548. /**
  16549. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16550. * Returns a BoundingInfo
  16551. */
  16552. AbstractMesh.prototype.getBoundingInfo = function () {
  16553. if (this._masterMesh) {
  16554. return this._masterMesh.getBoundingInfo();
  16555. }
  16556. if (!this._boundingInfo) {
  16557. // this._boundingInfo is being created here
  16558. this._updateBoundingInfo();
  16559. }
  16560. // cannot be null.
  16561. return this._boundingInfo;
  16562. };
  16563. /**
  16564. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16565. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16566. */
  16567. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16568. if (includeDescendants === void 0) { includeDescendants = true; }
  16569. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16570. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16571. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16572. if (maxDimension === 0) {
  16573. return this;
  16574. }
  16575. var scale = 1 / maxDimension;
  16576. this.scaling.scaleInPlace(scale);
  16577. return this;
  16578. };
  16579. /**
  16580. * Sets a mesh new object BoundingInfo.
  16581. * Returns the AbstractMesh.
  16582. */
  16583. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16584. this._boundingInfo = boundingInfo;
  16585. return this;
  16586. };
  16587. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16588. get: function () {
  16589. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16590. },
  16591. enumerable: true,
  16592. configurable: true
  16593. });
  16594. AbstractMesh.prototype._preActivate = function () {
  16595. };
  16596. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16597. };
  16598. AbstractMesh.prototype._activate = function (renderId) {
  16599. this._renderId = renderId;
  16600. };
  16601. /**
  16602. * Returns the latest update of the World matrix
  16603. * Returns a Matrix.
  16604. */
  16605. AbstractMesh.prototype.getWorldMatrix = function () {
  16606. if (this._masterMesh) {
  16607. return this._masterMesh.getWorldMatrix();
  16608. }
  16609. return _super.prototype.getWorldMatrix.call(this);
  16610. };
  16611. /**
  16612. * Returns the latest update of the World matrix determinant.
  16613. */
  16614. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16615. if (this._masterMesh) {
  16616. return this._masterMesh._getWorldMatrixDeterminant();
  16617. }
  16618. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16619. };
  16620. // ================================== Point of View Movement =================================
  16621. /**
  16622. * Perform relative position change from the point of view of behind the front of the mesh.
  16623. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16624. * Supports definition of mesh facing forward or backward.
  16625. * @param {number} amountRight
  16626. * @param {number} amountUp
  16627. * @param {number} amountForward
  16628. *
  16629. * Returns the AbstractMesh.
  16630. */
  16631. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16632. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16633. return this;
  16634. };
  16635. /**
  16636. * Calculate relative position change from the point of view of behind the front of the mesh.
  16637. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16638. * Supports definition of mesh facing forward or backward.
  16639. * @param {number} amountRight
  16640. * @param {number} amountUp
  16641. * @param {number} amountForward
  16642. *
  16643. * Returns a new Vector3.
  16644. */
  16645. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16646. var rotMatrix = new BABYLON.Matrix();
  16647. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16648. rotQuaternion.toRotationMatrix(rotMatrix);
  16649. var translationDelta = BABYLON.Vector3.Zero();
  16650. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16651. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16652. return translationDelta;
  16653. };
  16654. // ================================== Point of View Rotation =================================
  16655. /**
  16656. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16657. * Supports definition of mesh facing forward or backward.
  16658. * @param {number} flipBack
  16659. * @param {number} twirlClockwise
  16660. * @param {number} tiltRight
  16661. *
  16662. * Returns the AbstractMesh.
  16663. */
  16664. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16665. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16666. return this;
  16667. };
  16668. /**
  16669. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16670. * Supports definition of mesh facing forward or backward.
  16671. * @param {number} flipBack
  16672. * @param {number} twirlClockwise
  16673. * @param {number} tiltRight
  16674. *
  16675. * Returns a new Vector3.
  16676. */
  16677. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16678. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16679. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16680. };
  16681. /**
  16682. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16683. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16684. */
  16685. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16686. if (includeDescendants === void 0) { includeDescendants = true; }
  16687. this.computeWorldMatrix(true);
  16688. var min;
  16689. var max;
  16690. var boundingInfo = this.getBoundingInfo();
  16691. if (!this.subMeshes) {
  16692. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16693. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16694. }
  16695. else {
  16696. min = boundingInfo.boundingBox.minimumWorld;
  16697. max = boundingInfo.boundingBox.maximumWorld;
  16698. }
  16699. if (includeDescendants) {
  16700. var descendants = this.getDescendants(false);
  16701. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16702. var descendant = descendants_1[_i];
  16703. var childMesh = descendant;
  16704. childMesh.computeWorldMatrix(true);
  16705. //make sure we have the needed params to get mix and max
  16706. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16707. continue;
  16708. }
  16709. var childBoundingInfo = childMesh.getBoundingInfo();
  16710. var boundingBox = childBoundingInfo.boundingBox;
  16711. var minBox = boundingBox.minimumWorld;
  16712. var maxBox = boundingBox.maximumWorld;
  16713. BABYLON.Tools.CheckExtends(minBox, min, max);
  16714. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16715. }
  16716. }
  16717. return {
  16718. min: min,
  16719. max: max
  16720. };
  16721. };
  16722. /**
  16723. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16724. * Returns the AbstractMesh.
  16725. */
  16726. AbstractMesh.prototype._updateBoundingInfo = function () {
  16727. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16728. this._boundingInfo.update(this.worldMatrixFromCache);
  16729. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16730. return this;
  16731. };
  16732. /**
  16733. * Update a mesh's children BoundingInfo objects only.
  16734. * Returns the AbstractMesh.
  16735. */
  16736. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16737. if (!this.subMeshes) {
  16738. return this;
  16739. }
  16740. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16741. var subMesh = this.subMeshes[subIndex];
  16742. if (!subMesh.IsGlobal) {
  16743. subMesh.updateBoundingInfo(matrix);
  16744. }
  16745. }
  16746. return this;
  16747. };
  16748. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16749. // Bounding info
  16750. this._updateBoundingInfo();
  16751. };
  16752. /**
  16753. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16754. * A mesh is in the frustum if its bounding box intersects the frustum.
  16755. * Boolean returned.
  16756. */
  16757. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16758. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16759. };
  16760. /**
  16761. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16762. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16763. * Boolean returned.
  16764. */
  16765. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16766. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16767. ;
  16768. };
  16769. /**
  16770. * True if the mesh intersects another mesh or a SolidParticle object.
  16771. * 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)
  16772. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16773. * Returns a boolean.
  16774. */
  16775. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16776. if (precise === void 0) { precise = false; }
  16777. if (!this._boundingInfo || !mesh._boundingInfo) {
  16778. return false;
  16779. }
  16780. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16781. return true;
  16782. }
  16783. if (includeDescendants) {
  16784. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16785. var child = _a[_i];
  16786. if (child.intersectsMesh(mesh, precise, true)) {
  16787. return true;
  16788. }
  16789. }
  16790. }
  16791. return false;
  16792. };
  16793. /**
  16794. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16795. * Returns a boolean.
  16796. */
  16797. AbstractMesh.prototype.intersectsPoint = function (point) {
  16798. if (!this._boundingInfo) {
  16799. return false;
  16800. }
  16801. return this._boundingInfo.intersectsPoint(point);
  16802. };
  16803. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16804. return this.physicsImpostor;
  16805. };
  16806. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16807. if (camera === void 0) { camera = null; }
  16808. if (!camera) {
  16809. camera = this.getScene().activeCamera;
  16810. }
  16811. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16812. };
  16813. /**
  16814. * Returns the distance from the mesh to the active camera.
  16815. * Returns a float.
  16816. */
  16817. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16818. if (camera === void 0) { camera = null; }
  16819. if (!camera) {
  16820. camera = this.getScene().activeCamera;
  16821. }
  16822. return this.absolutePosition.subtract(camera.position).length();
  16823. };
  16824. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16825. if (!this.physicsImpostor) {
  16826. return this;
  16827. }
  16828. this.physicsImpostor.applyImpulse(force, contactPoint);
  16829. return this;
  16830. };
  16831. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16832. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16833. return this;
  16834. }
  16835. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16836. mainPivot: pivot1,
  16837. connectedPivot: pivot2,
  16838. nativeParams: options
  16839. });
  16840. return this;
  16841. };
  16842. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16843. // Collisions
  16844. /**
  16845. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16846. * Default `false`.
  16847. */
  16848. get: function () {
  16849. return this._checkCollisions;
  16850. },
  16851. set: function (collisionEnabled) {
  16852. this._checkCollisions = collisionEnabled;
  16853. if (this.getScene().workerCollisions) {
  16854. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16855. }
  16856. },
  16857. enumerable: true,
  16858. configurable: true
  16859. });
  16860. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16861. /**
  16862. * Gets Collider object used to compute collisions (not physics)
  16863. */
  16864. get: function () {
  16865. return this._collider;
  16866. },
  16867. enumerable: true,
  16868. configurable: true
  16869. });
  16870. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16871. var globalPosition = this.getAbsolutePosition();
  16872. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16873. if (!this._collider) {
  16874. this._collider = new BABYLON.Collider();
  16875. }
  16876. this._collider._radius = this.ellipsoid;
  16877. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16878. return this;
  16879. };
  16880. // Submeshes octree
  16881. /**
  16882. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16883. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16884. * Returns an Octree of submeshes.
  16885. */
  16886. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16887. if (maxCapacity === void 0) { maxCapacity = 64; }
  16888. if (maxDepth === void 0) { maxDepth = 2; }
  16889. if (!this._submeshesOctree) {
  16890. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16891. }
  16892. this.computeWorldMatrix(true);
  16893. var boundingInfo = this.getBoundingInfo();
  16894. // Update octree
  16895. var bbox = boundingInfo.boundingBox;
  16896. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16897. return this._submeshesOctree;
  16898. };
  16899. // Collisions
  16900. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16901. this._generatePointsArray();
  16902. if (!this._positions) {
  16903. return this;
  16904. }
  16905. // Transformation
  16906. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16907. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16908. subMesh._lastColliderWorldVertices = [];
  16909. subMesh._trianglePlanes = [];
  16910. var start = subMesh.verticesStart;
  16911. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16912. for (var i = start; i < end; i++) {
  16913. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16914. }
  16915. }
  16916. // Collide
  16917. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16918. if (collider.collisionFound) {
  16919. collider.collidedMesh = this;
  16920. }
  16921. return this;
  16922. };
  16923. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16924. var subMeshes;
  16925. var len;
  16926. // Octrees
  16927. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16928. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16929. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16930. len = intersections.length;
  16931. subMeshes = intersections.data;
  16932. }
  16933. else {
  16934. subMeshes = this.subMeshes;
  16935. len = subMeshes.length;
  16936. }
  16937. for (var index = 0; index < len; index++) {
  16938. var subMesh = subMeshes[index];
  16939. // Bounding test
  16940. if (len > 1 && !subMesh._checkCollision(collider))
  16941. continue;
  16942. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16943. }
  16944. return this;
  16945. };
  16946. AbstractMesh.prototype._checkCollision = function (collider) {
  16947. // Bounding box test
  16948. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16949. return this;
  16950. // Transformation matrix
  16951. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16952. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16953. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16954. return this;
  16955. };
  16956. // Picking
  16957. AbstractMesh.prototype._generatePointsArray = function () {
  16958. return false;
  16959. };
  16960. /**
  16961. * Checks if the passed Ray intersects with the mesh.
  16962. * Returns an object PickingInfo.
  16963. */
  16964. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16965. var pickingInfo = new BABYLON.PickingInfo();
  16966. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16967. return pickingInfo;
  16968. }
  16969. if (!this._generatePointsArray()) {
  16970. return pickingInfo;
  16971. }
  16972. var intersectInfo = null;
  16973. // Octrees
  16974. var subMeshes;
  16975. var len;
  16976. if (this._submeshesOctree && this.useOctreeForPicking) {
  16977. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16978. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16979. len = intersections.length;
  16980. subMeshes = intersections.data;
  16981. }
  16982. else {
  16983. subMeshes = this.subMeshes;
  16984. len = subMeshes.length;
  16985. }
  16986. for (var index = 0; index < len; index++) {
  16987. var subMesh = subMeshes[index];
  16988. // Bounding test
  16989. if (len > 1 && !subMesh.canIntersects(ray))
  16990. continue;
  16991. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16992. if (currentIntersectInfo) {
  16993. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16994. intersectInfo = currentIntersectInfo;
  16995. intersectInfo.subMeshId = index;
  16996. if (fastCheck) {
  16997. break;
  16998. }
  16999. }
  17000. }
  17001. }
  17002. if (intersectInfo) {
  17003. // Get picked point
  17004. var world = this.getWorldMatrix();
  17005. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17006. var direction = ray.direction.clone();
  17007. direction = direction.scale(intersectInfo.distance);
  17008. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17009. var pickedPoint = worldOrigin.add(worldDirection);
  17010. // Return result
  17011. pickingInfo.hit = true;
  17012. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17013. pickingInfo.pickedPoint = pickedPoint;
  17014. pickingInfo.pickedMesh = this;
  17015. pickingInfo.bu = intersectInfo.bu || 0;
  17016. pickingInfo.bv = intersectInfo.bv || 0;
  17017. pickingInfo.faceId = intersectInfo.faceId;
  17018. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17019. return pickingInfo;
  17020. }
  17021. return pickingInfo;
  17022. };
  17023. /**
  17024. * Clones the mesh, used by the class Mesh.
  17025. * Just returns `null` for an AbstractMesh.
  17026. */
  17027. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17028. return null;
  17029. };
  17030. /**
  17031. * Disposes all the mesh submeshes.
  17032. * Returns the AbstractMesh.
  17033. */
  17034. AbstractMesh.prototype.releaseSubMeshes = function () {
  17035. if (this.subMeshes) {
  17036. while (this.subMeshes.length) {
  17037. this.subMeshes[0].dispose();
  17038. }
  17039. }
  17040. else {
  17041. this.subMeshes = new Array();
  17042. }
  17043. return this;
  17044. };
  17045. /**
  17046. * Disposes the AbstractMesh.
  17047. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17048. * Returns nothing.
  17049. */
  17050. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17051. var _this = this;
  17052. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17053. var index;
  17054. // Action manager
  17055. if (this.actionManager !== undefined && this.actionManager !== null) {
  17056. this.actionManager.dispose();
  17057. this.actionManager = null;
  17058. }
  17059. // Skeleton
  17060. this.skeleton = null;
  17061. // Physics
  17062. if (this.physicsImpostor) {
  17063. this.physicsImpostor.dispose();
  17064. }
  17065. // Intersections in progress
  17066. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17067. var other = this._intersectionsInProgress[index];
  17068. var pos = other._intersectionsInProgress.indexOf(this);
  17069. other._intersectionsInProgress.splice(pos, 1);
  17070. }
  17071. this._intersectionsInProgress = [];
  17072. // Lights
  17073. var lights = this.getScene().lights;
  17074. lights.forEach(function (light) {
  17075. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17076. if (meshIndex !== -1) {
  17077. light.includedOnlyMeshes.splice(meshIndex, 1);
  17078. }
  17079. meshIndex = light.excludedMeshes.indexOf(_this);
  17080. if (meshIndex !== -1) {
  17081. light.excludedMeshes.splice(meshIndex, 1);
  17082. }
  17083. // Shadow generators
  17084. var generator = light.getShadowGenerator();
  17085. if (generator) {
  17086. var shadowMap = generator.getShadowMap();
  17087. if (shadowMap && shadowMap.renderList) {
  17088. meshIndex = shadowMap.renderList.indexOf(_this);
  17089. if (meshIndex !== -1) {
  17090. shadowMap.renderList.splice(meshIndex, 1);
  17091. }
  17092. }
  17093. }
  17094. });
  17095. // Edges
  17096. if (this._edgesRenderer) {
  17097. this._edgesRenderer.dispose();
  17098. this._edgesRenderer = null;
  17099. }
  17100. // SubMeshes
  17101. if (this.getClassName() !== "InstancedMesh") {
  17102. this.releaseSubMeshes();
  17103. }
  17104. // Octree
  17105. var sceneOctree = this.getScene().selectionOctree;
  17106. if (sceneOctree !== undefined && sceneOctree !== null) {
  17107. var index = sceneOctree.dynamicContent.indexOf(this);
  17108. if (index !== -1) {
  17109. sceneOctree.dynamicContent.splice(index, 1);
  17110. }
  17111. }
  17112. // Query
  17113. var engine = this.getScene().getEngine();
  17114. if (this._occlusionQuery) {
  17115. this._isOcclusionQueryInProgress = false;
  17116. engine.deleteQuery(this._occlusionQuery);
  17117. this._occlusionQuery = null;
  17118. }
  17119. // Engine
  17120. engine.wipeCaches();
  17121. // Remove from scene
  17122. this.getScene().removeMesh(this);
  17123. if (disposeMaterialAndTextures) {
  17124. if (this.material) {
  17125. this.material.dispose(false, true);
  17126. }
  17127. }
  17128. if (!doNotRecurse) {
  17129. // Particles
  17130. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  17131. if (this.getScene().particleSystems[index].emitter === this) {
  17132. this.getScene().particleSystems[index].dispose();
  17133. index--;
  17134. }
  17135. }
  17136. }
  17137. // facet data
  17138. if (this._facetDataEnabled) {
  17139. this.disableFacetData();
  17140. }
  17141. this.onAfterWorldMatrixUpdateObservable.clear();
  17142. this.onCollideObservable.clear();
  17143. this.onCollisionPositionChangeObservable.clear();
  17144. this._isDisposed = true;
  17145. _super.prototype.dispose.call(this, doNotRecurse);
  17146. };
  17147. /**
  17148. * Adds the passed mesh as a child to the current mesh.
  17149. * Returns the AbstractMesh.
  17150. */
  17151. AbstractMesh.prototype.addChild = function (mesh) {
  17152. mesh.setParent(this);
  17153. return this;
  17154. };
  17155. /**
  17156. * Removes the passed mesh from the current mesh children list.
  17157. * Returns the AbstractMesh.
  17158. */
  17159. AbstractMesh.prototype.removeChild = function (mesh) {
  17160. mesh.setParent(null);
  17161. return this;
  17162. };
  17163. // Facet data
  17164. /**
  17165. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  17166. * Returns the AbstractMesh.
  17167. */
  17168. AbstractMesh.prototype._initFacetData = function () {
  17169. if (!this._facetNormals) {
  17170. this._facetNormals = new Array();
  17171. }
  17172. if (!this._facetPositions) {
  17173. this._facetPositions = new Array();
  17174. }
  17175. if (!this._facetPartitioning) {
  17176. this._facetPartitioning = new Array();
  17177. }
  17178. this._facetNb = (this.getIndices().length / 3) | 0;
  17179. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  17180. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  17181. for (var f = 0; f < this._facetNb; f++) {
  17182. this._facetNormals[f] = BABYLON.Vector3.Zero();
  17183. this._facetPositions[f] = BABYLON.Vector3.Zero();
  17184. }
  17185. this._facetDataEnabled = true;
  17186. return this;
  17187. };
  17188. /**
  17189. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  17190. * This method can be called within the render loop.
  17191. * 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.
  17192. * Returns the AbstractMesh.
  17193. */
  17194. AbstractMesh.prototype.updateFacetData = function () {
  17195. if (!this._facetDataEnabled) {
  17196. this._initFacetData();
  17197. }
  17198. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17199. var indices = this.getIndices();
  17200. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17201. var bInfo = this.getBoundingInfo();
  17202. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  17203. // init arrays, matrix and sort function on first call
  17204. this._facetDepthSortEnabled = true;
  17205. if (indices instanceof Uint16Array) {
  17206. this._depthSortedIndices = new Uint16Array(indices);
  17207. }
  17208. else if (indices instanceof Uint32Array) {
  17209. this._depthSortedIndices = new Uint32Array(indices);
  17210. }
  17211. else {
  17212. var needs32bits = false;
  17213. for (var i = 0; i < indices.length; i++) {
  17214. if (indices[i] > 65535) {
  17215. needs32bits = true;
  17216. break;
  17217. }
  17218. }
  17219. if (needs32bits) {
  17220. this._depthSortedIndices = new Uint32Array(indices);
  17221. }
  17222. else {
  17223. this._depthSortedIndices = new Uint16Array(indices);
  17224. }
  17225. }
  17226. this._facetDepthSortFunction = function (f1, f2) {
  17227. return (f2.sqDistance - f1.sqDistance);
  17228. };
  17229. if (!this._facetDepthSortFrom) {
  17230. var camera = this.getScene().activeCamera;
  17231. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  17232. }
  17233. this._depthSortedFacets = [];
  17234. for (var f = 0; f < this._facetNb; f++) {
  17235. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  17236. this._depthSortedFacets.push(depthSortedFacet);
  17237. }
  17238. this._invertedMatrix = BABYLON.Matrix.Identity();
  17239. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  17240. }
  17241. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  17242. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  17243. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  17244. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  17245. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  17246. this._subDiv.max = this._partitioningSubdivisions;
  17247. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  17248. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  17249. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  17250. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  17251. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  17252. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  17253. // set the parameters for ComputeNormals()
  17254. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  17255. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  17256. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  17257. this._facetParameters.bInfo = bInfo;
  17258. this._facetParameters.bbSize = this._bbSize;
  17259. this._facetParameters.subDiv = this._subDiv;
  17260. this._facetParameters.ratio = this.partitioningBBoxRatio;
  17261. this._facetParameters.depthSort = this._facetDepthSort;
  17262. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17263. this.computeWorldMatrix(true);
  17264. this._worldMatrix.invertToRef(this._invertedMatrix);
  17265. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  17266. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  17267. }
  17268. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  17269. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  17270. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17271. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  17272. var l = (this._depthSortedIndices.length / 3) | 0;
  17273. for (var f = 0; f < l; f++) {
  17274. var sind = this._depthSortedFacets[f].ind;
  17275. this._depthSortedIndices[f * 3] = indices[sind];
  17276. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  17277. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  17278. }
  17279. this.updateIndices(this._depthSortedIndices);
  17280. }
  17281. return this;
  17282. };
  17283. /**
  17284. * Returns the facetLocalNormals array.
  17285. * The normals are expressed in the mesh local space.
  17286. */
  17287. AbstractMesh.prototype.getFacetLocalNormals = function () {
  17288. if (!this._facetNormals) {
  17289. this.updateFacetData();
  17290. }
  17291. return this._facetNormals;
  17292. };
  17293. /**
  17294. * Returns the facetLocalPositions array.
  17295. * The facet positions are expressed in the mesh local space.
  17296. */
  17297. AbstractMesh.prototype.getFacetLocalPositions = function () {
  17298. if (!this._facetPositions) {
  17299. this.updateFacetData();
  17300. }
  17301. return this._facetPositions;
  17302. };
  17303. /**
  17304. * Returns the facetLocalPartioning array.
  17305. */
  17306. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  17307. if (!this._facetPartitioning) {
  17308. this.updateFacetData();
  17309. }
  17310. return this._facetPartitioning;
  17311. };
  17312. /**
  17313. * Returns the i-th facet position in the world system.
  17314. * This method allocates a new Vector3 per call.
  17315. */
  17316. AbstractMesh.prototype.getFacetPosition = function (i) {
  17317. var pos = BABYLON.Vector3.Zero();
  17318. this.getFacetPositionToRef(i, pos);
  17319. return pos;
  17320. };
  17321. /**
  17322. * Sets the reference Vector3 with the i-th facet position in the world system.
  17323. * Returns the AbstractMesh.
  17324. */
  17325. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  17326. var localPos = (this.getFacetLocalPositions())[i];
  17327. var world = this.getWorldMatrix();
  17328. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  17329. return this;
  17330. };
  17331. /**
  17332. * Returns the i-th facet normal in the world system.
  17333. * This method allocates a new Vector3 per call.
  17334. */
  17335. AbstractMesh.prototype.getFacetNormal = function (i) {
  17336. var norm = BABYLON.Vector3.Zero();
  17337. this.getFacetNormalToRef(i, norm);
  17338. return norm;
  17339. };
  17340. /**
  17341. * Sets the reference Vector3 with the i-th facet normal in the world system.
  17342. * Returns the AbstractMesh.
  17343. */
  17344. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  17345. var localNorm = (this.getFacetLocalNormals())[i];
  17346. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  17347. return this;
  17348. };
  17349. /**
  17350. * 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).
  17351. */
  17352. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  17353. var bInfo = this.getBoundingInfo();
  17354. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  17355. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  17356. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  17357. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  17358. return null;
  17359. }
  17360. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  17361. };
  17362. /**
  17363. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  17364. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  17365. * 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.
  17366. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17367. * 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.
  17368. */
  17369. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  17370. if (checkFace === void 0) { checkFace = false; }
  17371. if (facing === void 0) { facing = true; }
  17372. var world = this.getWorldMatrix();
  17373. var invMat = BABYLON.Tmp.Matrix[5];
  17374. world.invertToRef(invMat);
  17375. var invVect = BABYLON.Tmp.Vector3[8];
  17376. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  17377. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  17378. if (projected) {
  17379. // tranform the local computed projected vector to world coordinates
  17380. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  17381. }
  17382. return closest;
  17383. };
  17384. /**
  17385. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  17386. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  17387. * 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.
  17388. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17389. * 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.
  17390. */
  17391. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  17392. if (checkFace === void 0) { checkFace = false; }
  17393. if (facing === void 0) { facing = true; }
  17394. var closest = null;
  17395. var tmpx = 0.0;
  17396. var tmpy = 0.0;
  17397. var tmpz = 0.0;
  17398. var d = 0.0; // tmp dot facet normal * facet position
  17399. var t0 = 0.0;
  17400. var projx = 0.0;
  17401. var projy = 0.0;
  17402. var projz = 0.0;
  17403. // Get all the facets in the same partitioning block than (x, y, z)
  17404. var facetPositions = this.getFacetLocalPositions();
  17405. var facetNormals = this.getFacetLocalNormals();
  17406. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  17407. if (!facetsInBlock) {
  17408. return null;
  17409. }
  17410. // Get the closest facet to (x, y, z)
  17411. var shortest = Number.MAX_VALUE; // init distance vars
  17412. var tmpDistance = shortest;
  17413. var fib; // current facet in the block
  17414. var norm; // current facet normal
  17415. var p0; // current facet barycenter position
  17416. // loop on all the facets in the current partitioning block
  17417. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  17418. fib = facetsInBlock[idx];
  17419. norm = facetNormals[fib];
  17420. p0 = facetPositions[fib];
  17421. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  17422. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  17423. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  17424. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  17425. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  17426. projx = x + norm.x * t0;
  17427. projy = y + norm.y * t0;
  17428. projz = z + norm.z * t0;
  17429. tmpx = projx - x;
  17430. tmpy = projy - y;
  17431. tmpz = projz - z;
  17432. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  17433. if (tmpDistance < shortest) {
  17434. shortest = tmpDistance;
  17435. closest = fib;
  17436. if (projected) {
  17437. projected.x = projx;
  17438. projected.y = projy;
  17439. projected.z = projz;
  17440. }
  17441. }
  17442. }
  17443. }
  17444. return closest;
  17445. };
  17446. /**
  17447. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  17448. */
  17449. AbstractMesh.prototype.getFacetDataParameters = function () {
  17450. return this._facetParameters;
  17451. };
  17452. /**
  17453. * Disables the feature FacetData and frees the related memory.
  17454. * Returns the AbstractMesh.
  17455. */
  17456. AbstractMesh.prototype.disableFacetData = function () {
  17457. if (this._facetDataEnabled) {
  17458. this._facetDataEnabled = false;
  17459. this._facetPositions = new Array();
  17460. this._facetNormals = new Array();
  17461. this._facetPartitioning = new Array();
  17462. this._facetParameters = null;
  17463. this._depthSortedIndices = new Uint32Array(0);
  17464. }
  17465. return this;
  17466. };
  17467. /**
  17468. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  17469. * Returns the mesh.
  17470. */
  17471. AbstractMesh.prototype.updateIndices = function (indices) {
  17472. return this;
  17473. };
  17474. /**
  17475. * The mesh Geometry. Actually used by the Mesh object.
  17476. * Returns a blank geometry object.
  17477. */
  17478. /**
  17479. * Creates new normals data for the mesh.
  17480. * @param updatable.
  17481. */
  17482. AbstractMesh.prototype.createNormals = function (updatable) {
  17483. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17484. var indices = this.getIndices();
  17485. var normals;
  17486. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17487. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17488. }
  17489. else {
  17490. normals = [];
  17491. }
  17492. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  17493. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  17494. };
  17495. /**
  17496. * Align the mesh with a normal.
  17497. * Returns the mesh.
  17498. */
  17499. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  17500. if (!upDirection) {
  17501. upDirection = BABYLON.Axis.Y;
  17502. }
  17503. var axisX = BABYLON.Tmp.Vector3[0];
  17504. var axisZ = BABYLON.Tmp.Vector3[1];
  17505. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  17506. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  17507. if (this.rotationQuaternion) {
  17508. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17509. }
  17510. else {
  17511. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17512. }
  17513. return this;
  17514. };
  17515. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17516. var engine = this.getEngine();
  17517. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17518. this._isOccluded = false;
  17519. return;
  17520. }
  17521. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17522. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17523. if (isOcclusionQueryAvailable) {
  17524. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17525. this._isOcclusionQueryInProgress = false;
  17526. this._occlusionInternalRetryCounter = 0;
  17527. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17528. }
  17529. else {
  17530. this._occlusionInternalRetryCounter++;
  17531. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17532. this._isOcclusionQueryInProgress = false;
  17533. this._occlusionInternalRetryCounter = 0;
  17534. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17535. // if strict continue the last state of the object.
  17536. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17537. }
  17538. else {
  17539. return;
  17540. }
  17541. }
  17542. }
  17543. var scene = this.getScene();
  17544. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17545. if (!this._occlusionQuery) {
  17546. this._occlusionQuery = engine.createQuery();
  17547. }
  17548. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17549. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17550. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17551. this._isOcclusionQueryInProgress = true;
  17552. };
  17553. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17554. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17555. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17556. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17557. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17558. return AbstractMesh;
  17559. }(BABYLON.TransformNode));
  17560. BABYLON.AbstractMesh = AbstractMesh;
  17561. })(BABYLON || (BABYLON = {}));
  17562. //# sourceMappingURL=babylon.abstractMesh.js.map
  17563. var BABYLON;
  17564. (function (BABYLON) {
  17565. var Light = /** @class */ (function (_super) {
  17566. __extends(Light, _super);
  17567. /**
  17568. * Creates a Light object in the scene.
  17569. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17570. */
  17571. function Light(name, scene) {
  17572. var _this = _super.call(this, name, scene) || this;
  17573. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17574. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17575. _this.intensity = 1.0;
  17576. _this.range = Number.MAX_VALUE;
  17577. /**
  17578. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17579. * of light.
  17580. */
  17581. _this._photometricScale = 1.0;
  17582. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17583. _this._radius = 0.00001;
  17584. _this.renderPriority = 0;
  17585. /**
  17586. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17587. * the current shadow generator.
  17588. */
  17589. _this.shadowEnabled = true;
  17590. _this._excludeWithLayerMask = 0;
  17591. _this._includeOnlyWithLayerMask = 0;
  17592. _this._lightmapMode = 0;
  17593. _this._excludedMeshesIds = new Array();
  17594. _this._includedOnlyMeshesIds = new Array();
  17595. _this.getScene().addLight(_this);
  17596. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17597. _this._buildUniformLayout();
  17598. _this.includedOnlyMeshes = new Array();
  17599. _this.excludedMeshes = new Array();
  17600. _this._resyncMeshes();
  17601. return _this;
  17602. }
  17603. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17604. /**
  17605. * If every light affecting the material is in this lightmapMode,
  17606. * material.lightmapTexture adds or multiplies
  17607. * (depends on material.useLightmapAsShadowmap)
  17608. * after every other light calculations.
  17609. */
  17610. get: function () {
  17611. return Light._LIGHTMAP_DEFAULT;
  17612. },
  17613. enumerable: true,
  17614. configurable: true
  17615. });
  17616. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17617. /**
  17618. * material.lightmapTexture as only diffuse lighting from this light
  17619. * adds only specular lighting from this light
  17620. * adds dynamic shadows
  17621. */
  17622. get: function () {
  17623. return Light._LIGHTMAP_SPECULAR;
  17624. },
  17625. enumerable: true,
  17626. configurable: true
  17627. });
  17628. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17629. /**
  17630. * material.lightmapTexture as only lighting
  17631. * no light calculation from this light
  17632. * only adds dynamic shadows from this light
  17633. */
  17634. get: function () {
  17635. return Light._LIGHTMAP_SHADOWSONLY;
  17636. },
  17637. enumerable: true,
  17638. configurable: true
  17639. });
  17640. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17641. /**
  17642. * Each light type uses the default quantity according to its type:
  17643. * point/spot lights use luminous intensity
  17644. * directional lights use illuminance
  17645. */
  17646. get: function () {
  17647. return Light._INTENSITYMODE_AUTOMATIC;
  17648. },
  17649. enumerable: true,
  17650. configurable: true
  17651. });
  17652. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17653. /**
  17654. * lumen (lm)
  17655. */
  17656. get: function () {
  17657. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17658. },
  17659. enumerable: true,
  17660. configurable: true
  17661. });
  17662. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17663. /**
  17664. * candela (lm/sr)
  17665. */
  17666. get: function () {
  17667. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17668. },
  17669. enumerable: true,
  17670. configurable: true
  17671. });
  17672. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17673. /**
  17674. * lux (lm/m^2)
  17675. */
  17676. get: function () {
  17677. return Light._INTENSITYMODE_ILLUMINANCE;
  17678. },
  17679. enumerable: true,
  17680. configurable: true
  17681. });
  17682. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17683. /**
  17684. * nit (cd/m^2)
  17685. */
  17686. get: function () {
  17687. return Light._INTENSITYMODE_LUMINANCE;
  17688. },
  17689. enumerable: true,
  17690. configurable: true
  17691. });
  17692. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17693. /**
  17694. * Light type const id of the point light.
  17695. */
  17696. get: function () {
  17697. return Light._LIGHTTYPEID_POINTLIGHT;
  17698. },
  17699. enumerable: true,
  17700. configurable: true
  17701. });
  17702. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17703. /**
  17704. * Light type const id of the directional light.
  17705. */
  17706. get: function () {
  17707. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17713. /**
  17714. * Light type const id of the spot light.
  17715. */
  17716. get: function () {
  17717. return Light._LIGHTTYPEID_SPOTLIGHT;
  17718. },
  17719. enumerable: true,
  17720. configurable: true
  17721. });
  17722. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17723. /**
  17724. * Light type const id of the hemispheric light.
  17725. */
  17726. get: function () {
  17727. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17728. },
  17729. enumerable: true,
  17730. configurable: true
  17731. });
  17732. Object.defineProperty(Light.prototype, "intensityMode", {
  17733. /**
  17734. * Gets the photometric scale used to interpret the intensity.
  17735. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17736. */
  17737. get: function () {
  17738. return this._intensityMode;
  17739. },
  17740. /**
  17741. * Sets the photometric scale used to interpret the intensity.
  17742. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17743. */
  17744. set: function (value) {
  17745. this._intensityMode = value;
  17746. this._computePhotometricScale();
  17747. },
  17748. enumerable: true,
  17749. configurable: true
  17750. });
  17751. ;
  17752. ;
  17753. Object.defineProperty(Light.prototype, "radius", {
  17754. /**
  17755. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17756. */
  17757. get: function () {
  17758. return this._radius;
  17759. },
  17760. /**
  17761. * sets the light radius used by PBR Materials to simulate soft area lights.
  17762. */
  17763. set: function (value) {
  17764. this._radius = value;
  17765. this._computePhotometricScale();
  17766. },
  17767. enumerable: true,
  17768. configurable: true
  17769. });
  17770. ;
  17771. ;
  17772. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17773. get: function () {
  17774. return this._includedOnlyMeshes;
  17775. },
  17776. set: function (value) {
  17777. this._includedOnlyMeshes = value;
  17778. this._hookArrayForIncludedOnly(value);
  17779. },
  17780. enumerable: true,
  17781. configurable: true
  17782. });
  17783. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17784. get: function () {
  17785. return this._excludedMeshes;
  17786. },
  17787. set: function (value) {
  17788. this._excludedMeshes = value;
  17789. this._hookArrayForExcluded(value);
  17790. },
  17791. enumerable: true,
  17792. configurable: true
  17793. });
  17794. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17795. get: function () {
  17796. return this._excludeWithLayerMask;
  17797. },
  17798. set: function (value) {
  17799. this._excludeWithLayerMask = value;
  17800. this._resyncMeshes();
  17801. },
  17802. enumerable: true,
  17803. configurable: true
  17804. });
  17805. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17806. get: function () {
  17807. return this._includeOnlyWithLayerMask;
  17808. },
  17809. set: function (value) {
  17810. this._includeOnlyWithLayerMask = value;
  17811. this._resyncMeshes();
  17812. },
  17813. enumerable: true,
  17814. configurable: true
  17815. });
  17816. Object.defineProperty(Light.prototype, "lightmapMode", {
  17817. get: function () {
  17818. return this._lightmapMode;
  17819. },
  17820. set: function (value) {
  17821. if (this._lightmapMode === value) {
  17822. return;
  17823. }
  17824. this._lightmapMode = value;
  17825. this._markMeshesAsLightDirty();
  17826. },
  17827. enumerable: true,
  17828. configurable: true
  17829. });
  17830. Light.prototype._buildUniformLayout = function () {
  17831. // Overridden
  17832. };
  17833. /**
  17834. * Returns the string "Light".
  17835. */
  17836. Light.prototype.getClassName = function () {
  17837. return "Light";
  17838. };
  17839. /**
  17840. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17841. */
  17842. Light.prototype.toString = function (fullDetails) {
  17843. var ret = "Name: " + this.name;
  17844. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17845. if (this.animations) {
  17846. for (var i = 0; i < this.animations.length; i++) {
  17847. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17848. }
  17849. }
  17850. if (fullDetails) {
  17851. }
  17852. return ret;
  17853. };
  17854. /**
  17855. * Set the enabled state of this node.
  17856. * @param {boolean} value - the new enabled state
  17857. * @see isEnabled
  17858. */
  17859. Light.prototype.setEnabled = function (value) {
  17860. _super.prototype.setEnabled.call(this, value);
  17861. this._resyncMeshes();
  17862. };
  17863. /**
  17864. * Returns the Light associated shadow generator.
  17865. */
  17866. Light.prototype.getShadowGenerator = function () {
  17867. return this._shadowGenerator;
  17868. };
  17869. /**
  17870. * Returns a Vector3, the absolute light position in the World.
  17871. */
  17872. Light.prototype.getAbsolutePosition = function () {
  17873. return BABYLON.Vector3.Zero();
  17874. };
  17875. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17876. };
  17877. Light.prototype._getWorldMatrix = function () {
  17878. return BABYLON.Matrix.Identity();
  17879. };
  17880. /**
  17881. * Boolean : True if the light will affect the passed mesh.
  17882. */
  17883. Light.prototype.canAffectMesh = function (mesh) {
  17884. if (!mesh) {
  17885. return true;
  17886. }
  17887. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17888. return false;
  17889. }
  17890. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17891. return false;
  17892. }
  17893. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17894. return false;
  17895. }
  17896. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17897. return false;
  17898. }
  17899. return true;
  17900. };
  17901. /**
  17902. * Returns the light World matrix.
  17903. */
  17904. Light.prototype.getWorldMatrix = function () {
  17905. this._currentRenderId = this.getScene().getRenderId();
  17906. var worldMatrix = this._getWorldMatrix();
  17907. if (this.parent && this.parent.getWorldMatrix) {
  17908. if (!this._parentedWorldMatrix) {
  17909. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17910. }
  17911. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17912. this._markSyncedWithParent();
  17913. return this._parentedWorldMatrix;
  17914. }
  17915. return worldMatrix;
  17916. };
  17917. /**
  17918. * Sort function to order lights for rendering.
  17919. * @param a First Light object to compare to second.
  17920. * @param b Second Light object to compare first.
  17921. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17922. */
  17923. Light.compareLightsPriority = function (a, b) {
  17924. //shadow-casting lights have priority over non-shadow-casting lights
  17925. //the renderPrioirty is a secondary sort criterion
  17926. if (a.shadowEnabled !== b.shadowEnabled) {
  17927. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17928. }
  17929. return b.renderPriority - a.renderPriority;
  17930. };
  17931. /**
  17932. * Disposes the light.
  17933. */
  17934. Light.prototype.dispose = function () {
  17935. if (this._shadowGenerator) {
  17936. this._shadowGenerator.dispose();
  17937. this._shadowGenerator = null;
  17938. }
  17939. // Animations
  17940. this.getScene().stopAnimation(this);
  17941. this._uniformBuffer.dispose();
  17942. // Remove from scene
  17943. this.getScene().removeLight(this);
  17944. _super.prototype.dispose.call(this);
  17945. };
  17946. /**
  17947. * Returns the light type ID (integer).
  17948. */
  17949. Light.prototype.getTypeID = function () {
  17950. return 0;
  17951. };
  17952. /**
  17953. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17954. */
  17955. Light.prototype.getScaledIntensity = function () {
  17956. return this._photometricScale * this.intensity;
  17957. };
  17958. /**
  17959. * Returns a new Light object, named "name", from the current one.
  17960. */
  17961. Light.prototype.clone = function (name) {
  17962. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17963. if (!constructor) {
  17964. return null;
  17965. }
  17966. return BABYLON.SerializationHelper.Clone(constructor, this);
  17967. };
  17968. /**
  17969. * Serializes the current light into a Serialization object.
  17970. * Returns the serialized object.
  17971. */
  17972. Light.prototype.serialize = function () {
  17973. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17974. // Type
  17975. serializationObject.type = this.getTypeID();
  17976. // Parent
  17977. if (this.parent) {
  17978. serializationObject.parentId = this.parent.id;
  17979. }
  17980. // Inclusion / exclusions
  17981. if (this.excludedMeshes.length > 0) {
  17982. serializationObject.excludedMeshesIds = [];
  17983. this.excludedMeshes.forEach(function (mesh) {
  17984. serializationObject.excludedMeshesIds.push(mesh.id);
  17985. });
  17986. }
  17987. if (this.includedOnlyMeshes.length > 0) {
  17988. serializationObject.includedOnlyMeshesIds = [];
  17989. this.includedOnlyMeshes.forEach(function (mesh) {
  17990. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17991. });
  17992. }
  17993. // Animations
  17994. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17995. serializationObject.ranges = this.serializeAnimationRanges();
  17996. return serializationObject;
  17997. };
  17998. /**
  17999. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18000. * This new light is named "name" and added to the passed scene.
  18001. */
  18002. Light.GetConstructorFromName = function (type, name, scene) {
  18003. switch (type) {
  18004. case 0:
  18005. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18006. case 1:
  18007. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18008. case 2:
  18009. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18010. case 3:
  18011. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18012. }
  18013. return null;
  18014. };
  18015. /**
  18016. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18017. */
  18018. Light.Parse = function (parsedLight, scene) {
  18019. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18020. if (!constructor) {
  18021. return null;
  18022. }
  18023. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  18024. // Inclusion / exclusions
  18025. if (parsedLight.excludedMeshesIds) {
  18026. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18027. }
  18028. if (parsedLight.includedOnlyMeshesIds) {
  18029. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18030. }
  18031. // Parent
  18032. if (parsedLight.parentId) {
  18033. light._waitingParentId = parsedLight.parentId;
  18034. }
  18035. // Animations
  18036. if (parsedLight.animations) {
  18037. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18038. var parsedAnimation = parsedLight.animations[animationIndex];
  18039. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18040. }
  18041. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  18042. }
  18043. if (parsedLight.autoAnimate) {
  18044. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  18045. }
  18046. return light;
  18047. };
  18048. Light.prototype._hookArrayForExcluded = function (array) {
  18049. var _this = this;
  18050. var oldPush = array.push;
  18051. array.push = function () {
  18052. var items = [];
  18053. for (var _i = 0; _i < arguments.length; _i++) {
  18054. items[_i] = arguments[_i];
  18055. }
  18056. var result = oldPush.apply(array, items);
  18057. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  18058. var item = items_1[_a];
  18059. item._resyncLighSource(_this);
  18060. }
  18061. return result;
  18062. };
  18063. var oldSplice = array.splice;
  18064. array.splice = function (index, deleteCount) {
  18065. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18066. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  18067. var item = deleted_1[_i];
  18068. item._resyncLighSource(_this);
  18069. }
  18070. return deleted;
  18071. };
  18072. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  18073. var item = array_1[_i];
  18074. item._resyncLighSource(this);
  18075. }
  18076. };
  18077. Light.prototype._hookArrayForIncludedOnly = function (array) {
  18078. var _this = this;
  18079. var oldPush = array.push;
  18080. array.push = function () {
  18081. var items = [];
  18082. for (var _i = 0; _i < arguments.length; _i++) {
  18083. items[_i] = arguments[_i];
  18084. }
  18085. var result = oldPush.apply(array, items);
  18086. _this._resyncMeshes();
  18087. return result;
  18088. };
  18089. var oldSplice = array.splice;
  18090. array.splice = function (index, deleteCount) {
  18091. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18092. _this._resyncMeshes();
  18093. return deleted;
  18094. };
  18095. this._resyncMeshes();
  18096. };
  18097. Light.prototype._resyncMeshes = function () {
  18098. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18099. var mesh = _a[_i];
  18100. mesh._resyncLighSource(this);
  18101. }
  18102. };
  18103. Light.prototype._markMeshesAsLightDirty = function () {
  18104. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18105. var mesh = _a[_i];
  18106. if (mesh._lightSources.indexOf(this) !== -1) {
  18107. mesh._markSubMeshesAsLightDirty();
  18108. }
  18109. }
  18110. };
  18111. /**
  18112. * Recomputes the cached photometric scale if needed.
  18113. */
  18114. Light.prototype._computePhotometricScale = function () {
  18115. this._photometricScale = this._getPhotometricScale();
  18116. this.getScene().resetCachedMaterial();
  18117. };
  18118. /**
  18119. * Returns the Photometric Scale according to the light type and intensity mode.
  18120. */
  18121. Light.prototype._getPhotometricScale = function () {
  18122. var photometricScale = 0.0;
  18123. var lightTypeID = this.getTypeID();
  18124. //get photometric mode
  18125. var photometricMode = this.intensityMode;
  18126. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  18127. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  18128. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  18129. }
  18130. else {
  18131. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  18132. }
  18133. }
  18134. //compute photometric scale
  18135. switch (lightTypeID) {
  18136. case Light.LIGHTTYPEID_POINTLIGHT:
  18137. case Light.LIGHTTYPEID_SPOTLIGHT:
  18138. switch (photometricMode) {
  18139. case Light.INTENSITYMODE_LUMINOUSPOWER:
  18140. photometricScale = 1.0 / (4.0 * Math.PI);
  18141. break;
  18142. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  18143. photometricScale = 1.0;
  18144. break;
  18145. case Light.INTENSITYMODE_LUMINANCE:
  18146. photometricScale = this.radius * this.radius;
  18147. break;
  18148. }
  18149. break;
  18150. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  18151. switch (photometricMode) {
  18152. case Light.INTENSITYMODE_ILLUMINANCE:
  18153. photometricScale = 1.0;
  18154. break;
  18155. case Light.INTENSITYMODE_LUMINANCE:
  18156. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  18157. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  18158. var apexAngleRadians = this.radius;
  18159. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  18160. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  18161. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  18162. photometricScale = solidAngle;
  18163. break;
  18164. }
  18165. break;
  18166. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  18167. // No fall off in hemisperic light.
  18168. photometricScale = 1.0;
  18169. break;
  18170. }
  18171. return photometricScale;
  18172. };
  18173. Light.prototype._reorderLightsInScene = function () {
  18174. var scene = this.getScene();
  18175. if (this._renderPriority != 0) {
  18176. scene.requireLightSorting = true;
  18177. }
  18178. this.getScene().sortLightsByPriority();
  18179. };
  18180. //lightmapMode Consts
  18181. Light._LIGHTMAP_DEFAULT = 0;
  18182. Light._LIGHTMAP_SPECULAR = 1;
  18183. Light._LIGHTMAP_SHADOWSONLY = 2;
  18184. // Intensity Mode Consts
  18185. Light._INTENSITYMODE_AUTOMATIC = 0;
  18186. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  18187. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  18188. Light._INTENSITYMODE_ILLUMINANCE = 3;
  18189. Light._INTENSITYMODE_LUMINANCE = 4;
  18190. // Light types ids const.
  18191. Light._LIGHTTYPEID_POINTLIGHT = 0;
  18192. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  18193. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  18194. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  18195. __decorate([
  18196. BABYLON.serializeAsColor3()
  18197. ], Light.prototype, "diffuse", void 0);
  18198. __decorate([
  18199. BABYLON.serializeAsColor3()
  18200. ], Light.prototype, "specular", void 0);
  18201. __decorate([
  18202. BABYLON.serialize()
  18203. ], Light.prototype, "intensity", void 0);
  18204. __decorate([
  18205. BABYLON.serialize()
  18206. ], Light.prototype, "range", void 0);
  18207. __decorate([
  18208. BABYLON.serialize()
  18209. ], Light.prototype, "intensityMode", null);
  18210. __decorate([
  18211. BABYLON.serialize()
  18212. ], Light.prototype, "radius", null);
  18213. __decorate([
  18214. BABYLON.serialize()
  18215. ], Light.prototype, "_renderPriority", void 0);
  18216. __decorate([
  18217. BABYLON.expandToProperty("_reorderLightsInScene")
  18218. ], Light.prototype, "renderPriority", void 0);
  18219. __decorate([
  18220. BABYLON.serialize()
  18221. ], Light.prototype, "shadowEnabled", void 0);
  18222. __decorate([
  18223. BABYLON.serialize("excludeWithLayerMask")
  18224. ], Light.prototype, "_excludeWithLayerMask", void 0);
  18225. __decorate([
  18226. BABYLON.serialize("includeOnlyWithLayerMask")
  18227. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  18228. __decorate([
  18229. BABYLON.serialize("lightmapMode")
  18230. ], Light.prototype, "_lightmapMode", void 0);
  18231. return Light;
  18232. }(BABYLON.Node));
  18233. BABYLON.Light = Light;
  18234. })(BABYLON || (BABYLON = {}));
  18235. //# sourceMappingURL=babylon.light.js.map
  18236. var BABYLON;
  18237. (function (BABYLON) {
  18238. var Camera = /** @class */ (function (_super) {
  18239. __extends(Camera, _super);
  18240. function Camera(name, position, scene) {
  18241. var _this = _super.call(this, name, scene) || this;
  18242. /**
  18243. * The vector the camera should consider as up.
  18244. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  18245. */
  18246. _this.upVector = BABYLON.Vector3.Up();
  18247. _this.orthoLeft = null;
  18248. _this.orthoRight = null;
  18249. _this.orthoBottom = null;
  18250. _this.orthoTop = null;
  18251. /**
  18252. * FOV is set in Radians. (default is 0.8)
  18253. */
  18254. _this.fov = 0.8;
  18255. _this.minZ = 1;
  18256. _this.maxZ = 10000.0;
  18257. _this.inertia = 0.9;
  18258. _this.mode = Camera.PERSPECTIVE_CAMERA;
  18259. _this.isIntermediate = false;
  18260. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  18261. /**
  18262. * Restricts the camera to viewing objects with the same layerMask.
  18263. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  18264. */
  18265. _this.layerMask = 0x0FFFFFFF;
  18266. /**
  18267. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  18268. */
  18269. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  18270. // Camera rig members
  18271. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  18272. _this._rigCameras = new Array();
  18273. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  18274. _this._skipRendering = false;
  18275. _this.customRenderTargets = new Array();
  18276. // Observables
  18277. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  18278. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  18279. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  18280. _this.onRestoreStateObservable = new BABYLON.Observable();
  18281. // Cache
  18282. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  18283. _this._projectionMatrix = new BABYLON.Matrix();
  18284. _this._doNotComputeProjectionMatrix = false;
  18285. _this._postProcesses = new Array();
  18286. _this._transformMatrix = BABYLON.Matrix.Zero();
  18287. _this._activeMeshes = new BABYLON.SmartArray(256);
  18288. _this._globalPosition = BABYLON.Vector3.Zero();
  18289. _this._refreshFrustumPlanes = true;
  18290. _this.getScene().addCamera(_this);
  18291. if (!_this.getScene().activeCamera) {
  18292. _this.getScene().activeCamera = _this;
  18293. }
  18294. _this.position = position;
  18295. return _this;
  18296. }
  18297. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  18298. get: function () {
  18299. return Camera._PERSPECTIVE_CAMERA;
  18300. },
  18301. enumerable: true,
  18302. configurable: true
  18303. });
  18304. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  18305. get: function () {
  18306. return Camera._ORTHOGRAPHIC_CAMERA;
  18307. },
  18308. enumerable: true,
  18309. configurable: true
  18310. });
  18311. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  18312. /**
  18313. * This is the default FOV mode for perspective cameras.
  18314. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  18315. *
  18316. */
  18317. get: function () {
  18318. return Camera._FOVMODE_VERTICAL_FIXED;
  18319. },
  18320. enumerable: true,
  18321. configurable: true
  18322. });
  18323. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  18324. /**
  18325. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  18326. *
  18327. */
  18328. get: function () {
  18329. return Camera._FOVMODE_HORIZONTAL_FIXED;
  18330. },
  18331. enumerable: true,
  18332. configurable: true
  18333. });
  18334. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  18335. get: function () {
  18336. return Camera._RIG_MODE_NONE;
  18337. },
  18338. enumerable: true,
  18339. configurable: true
  18340. });
  18341. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  18342. get: function () {
  18343. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  18344. },
  18345. enumerable: true,
  18346. configurable: true
  18347. });
  18348. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  18349. get: function () {
  18350. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  18351. },
  18352. enumerable: true,
  18353. configurable: true
  18354. });
  18355. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  18356. get: function () {
  18357. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18358. },
  18359. enumerable: true,
  18360. configurable: true
  18361. });
  18362. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  18363. get: function () {
  18364. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  18365. },
  18366. enumerable: true,
  18367. configurable: true
  18368. });
  18369. Object.defineProperty(Camera, "RIG_MODE_VR", {
  18370. get: function () {
  18371. return Camera._RIG_MODE_VR;
  18372. },
  18373. enumerable: true,
  18374. configurable: true
  18375. });
  18376. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  18377. get: function () {
  18378. return Camera._RIG_MODE_WEBVR;
  18379. },
  18380. enumerable: true,
  18381. configurable: true
  18382. });
  18383. /**
  18384. * Store current camera state (fov, position, etc..)
  18385. */
  18386. Camera.prototype.storeState = function () {
  18387. this._stateStored = true;
  18388. this._storedFov = this.fov;
  18389. return this;
  18390. };
  18391. /**
  18392. * Restores the camera state values if it has been stored. You must call storeState() first
  18393. */
  18394. Camera.prototype._restoreStateValues = function () {
  18395. if (!this._stateStored) {
  18396. return false;
  18397. }
  18398. this.fov = this._storedFov;
  18399. return true;
  18400. };
  18401. /**
  18402. * Restored camera state. You must call storeState() first
  18403. */
  18404. Camera.prototype.restoreState = function () {
  18405. if (this._restoreStateValues()) {
  18406. this.onRestoreStateObservable.notifyObservers(this);
  18407. return true;
  18408. }
  18409. return false;
  18410. };
  18411. Camera.prototype.getClassName = function () {
  18412. return "Camera";
  18413. };
  18414. /**
  18415. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18416. */
  18417. Camera.prototype.toString = function (fullDetails) {
  18418. var ret = "Name: " + this.name;
  18419. ret += ", type: " + this.getClassName();
  18420. if (this.animations) {
  18421. for (var i = 0; i < this.animations.length; i++) {
  18422. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18423. }
  18424. }
  18425. if (fullDetails) {
  18426. }
  18427. return ret;
  18428. };
  18429. Object.defineProperty(Camera.prototype, "globalPosition", {
  18430. get: function () {
  18431. return this._globalPosition;
  18432. },
  18433. enumerable: true,
  18434. configurable: true
  18435. });
  18436. Camera.prototype.getActiveMeshes = function () {
  18437. return this._activeMeshes;
  18438. };
  18439. Camera.prototype.isActiveMesh = function (mesh) {
  18440. return (this._activeMeshes.indexOf(mesh) !== -1);
  18441. };
  18442. //Cache
  18443. Camera.prototype._initCache = function () {
  18444. _super.prototype._initCache.call(this);
  18445. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18446. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18447. this._cache.mode = undefined;
  18448. this._cache.minZ = undefined;
  18449. this._cache.maxZ = undefined;
  18450. this._cache.fov = undefined;
  18451. this._cache.fovMode = undefined;
  18452. this._cache.aspectRatio = undefined;
  18453. this._cache.orthoLeft = undefined;
  18454. this._cache.orthoRight = undefined;
  18455. this._cache.orthoBottom = undefined;
  18456. this._cache.orthoTop = undefined;
  18457. this._cache.renderWidth = undefined;
  18458. this._cache.renderHeight = undefined;
  18459. };
  18460. Camera.prototype._updateCache = function (ignoreParentClass) {
  18461. if (!ignoreParentClass) {
  18462. _super.prototype._updateCache.call(this);
  18463. }
  18464. this._cache.position.copyFrom(this.position);
  18465. this._cache.upVector.copyFrom(this.upVector);
  18466. };
  18467. // Synchronized
  18468. Camera.prototype._isSynchronized = function () {
  18469. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  18470. };
  18471. Camera.prototype._isSynchronizedViewMatrix = function () {
  18472. if (!_super.prototype._isSynchronized.call(this))
  18473. return false;
  18474. return this._cache.position.equals(this.position)
  18475. && this._cache.upVector.equals(this.upVector)
  18476. && this.isSynchronizedWithParent();
  18477. };
  18478. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  18479. var check = this._cache.mode === this.mode
  18480. && this._cache.minZ === this.minZ
  18481. && this._cache.maxZ === this.maxZ;
  18482. if (!check) {
  18483. return false;
  18484. }
  18485. var engine = this.getEngine();
  18486. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18487. check = this._cache.fov === this.fov
  18488. && this._cache.fovMode === this.fovMode
  18489. && this._cache.aspectRatio === engine.getAspectRatio(this);
  18490. }
  18491. else {
  18492. check = this._cache.orthoLeft === this.orthoLeft
  18493. && this._cache.orthoRight === this.orthoRight
  18494. && this._cache.orthoBottom === this.orthoBottom
  18495. && this._cache.orthoTop === this.orthoTop
  18496. && this._cache.renderWidth === engine.getRenderWidth()
  18497. && this._cache.renderHeight === engine.getRenderHeight();
  18498. }
  18499. return check;
  18500. };
  18501. // Controls
  18502. Camera.prototype.attachControl = function (element, noPreventDefault) {
  18503. };
  18504. Camera.prototype.detachControl = function (element) {
  18505. };
  18506. Camera.prototype.update = function () {
  18507. this._checkInputs();
  18508. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18509. this._updateRigCameras();
  18510. }
  18511. };
  18512. Camera.prototype._checkInputs = function () {
  18513. this.onAfterCheckInputsObservable.notifyObservers(this);
  18514. };
  18515. Object.defineProperty(Camera.prototype, "rigCameras", {
  18516. get: function () {
  18517. return this._rigCameras;
  18518. },
  18519. enumerable: true,
  18520. configurable: true
  18521. });
  18522. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18523. get: function () {
  18524. return this._rigPostProcess;
  18525. },
  18526. enumerable: true,
  18527. configurable: true
  18528. });
  18529. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18530. // invalidate framebuffer
  18531. if (this._postProcesses.length > 0) {
  18532. this._postProcesses[0].markTextureDirty();
  18533. }
  18534. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18535. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18536. var cam = this._rigCameras[i];
  18537. var rigPostProcess = cam._rigPostProcess;
  18538. // for VR rig, there does not have to be a post process
  18539. if (rigPostProcess) {
  18540. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18541. if (isPass) {
  18542. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18543. cam.isIntermediate = this._postProcesses.length === 0;
  18544. }
  18545. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18546. rigPostProcess.markTextureDirty();
  18547. }
  18548. else {
  18549. cam._postProcesses = this._postProcesses.slice(0);
  18550. }
  18551. }
  18552. };
  18553. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18554. if (insertAt === void 0) { insertAt = null; }
  18555. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18556. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18557. return 0;
  18558. }
  18559. if (insertAt == null || insertAt < 0) {
  18560. this._postProcesses.push(postProcess);
  18561. }
  18562. else {
  18563. this._postProcesses.splice(insertAt, 0, postProcess);
  18564. }
  18565. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18566. return this._postProcesses.indexOf(postProcess);
  18567. };
  18568. Camera.prototype.detachPostProcess = function (postProcess) {
  18569. var idx = this._postProcesses.indexOf(postProcess);
  18570. if (idx !== -1) {
  18571. this._postProcesses.splice(idx, 1);
  18572. }
  18573. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18574. };
  18575. Camera.prototype.getWorldMatrix = function () {
  18576. if (!this._worldMatrix) {
  18577. this._worldMatrix = BABYLON.Matrix.Identity();
  18578. }
  18579. var viewMatrix = this.getViewMatrix();
  18580. viewMatrix.invertToRef(this._worldMatrix);
  18581. return this._worldMatrix;
  18582. };
  18583. Camera.prototype._getViewMatrix = function () {
  18584. return BABYLON.Matrix.Identity();
  18585. };
  18586. Camera.prototype.getViewMatrix = function (force) {
  18587. if (!force && this._isSynchronizedViewMatrix()) {
  18588. return this._computedViewMatrix;
  18589. }
  18590. this.updateCache();
  18591. this._computedViewMatrix = this._getViewMatrix();
  18592. this._currentRenderId = this.getScene().getRenderId();
  18593. this._refreshFrustumPlanes = true;
  18594. if (!this.parent || !this.parent.getWorldMatrix) {
  18595. this._globalPosition.copyFrom(this.position);
  18596. }
  18597. else {
  18598. if (!this._worldMatrix) {
  18599. this._worldMatrix = BABYLON.Matrix.Identity();
  18600. }
  18601. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18602. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18603. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18604. this._computedViewMatrix.invert();
  18605. this._markSyncedWithParent();
  18606. }
  18607. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18608. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18609. }
  18610. this.onViewMatrixChangedObservable.notifyObservers(this);
  18611. return this._computedViewMatrix;
  18612. };
  18613. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18614. this._doNotComputeProjectionMatrix = true;
  18615. if (projection !== undefined) {
  18616. this._projectionMatrix = projection;
  18617. }
  18618. };
  18619. ;
  18620. Camera.prototype.unfreezeProjectionMatrix = function () {
  18621. this._doNotComputeProjectionMatrix = false;
  18622. };
  18623. ;
  18624. Camera.prototype.getProjectionMatrix = function (force) {
  18625. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18626. return this._projectionMatrix;
  18627. }
  18628. // Cache
  18629. this._cache.mode = this.mode;
  18630. this._cache.minZ = this.minZ;
  18631. this._cache.maxZ = this.maxZ;
  18632. // Matrix
  18633. this._refreshFrustumPlanes = true;
  18634. var engine = this.getEngine();
  18635. var scene = this.getScene();
  18636. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18637. this._cache.fov = this.fov;
  18638. this._cache.fovMode = this.fovMode;
  18639. this._cache.aspectRatio = engine.getAspectRatio(this);
  18640. if (this.minZ <= 0) {
  18641. this.minZ = 0.1;
  18642. }
  18643. if (scene.useRightHandedSystem) {
  18644. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18645. }
  18646. else {
  18647. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18648. }
  18649. }
  18650. else {
  18651. var halfWidth = engine.getRenderWidth() / 2.0;
  18652. var halfHeight = engine.getRenderHeight() / 2.0;
  18653. if (scene.useRightHandedSystem) {
  18654. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18655. }
  18656. else {
  18657. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18658. }
  18659. this._cache.orthoLeft = this.orthoLeft;
  18660. this._cache.orthoRight = this.orthoRight;
  18661. this._cache.orthoBottom = this.orthoBottom;
  18662. this._cache.orthoTop = this.orthoTop;
  18663. this._cache.renderWidth = engine.getRenderWidth();
  18664. this._cache.renderHeight = engine.getRenderHeight();
  18665. }
  18666. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18667. return this._projectionMatrix;
  18668. };
  18669. Camera.prototype.getTranformationMatrix = function () {
  18670. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18671. return this._transformMatrix;
  18672. };
  18673. Camera.prototype.updateFrustumPlanes = function () {
  18674. if (!this._refreshFrustumPlanes) {
  18675. return;
  18676. }
  18677. this.getTranformationMatrix();
  18678. if (!this._frustumPlanes) {
  18679. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18680. }
  18681. else {
  18682. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18683. }
  18684. this._refreshFrustumPlanes = false;
  18685. };
  18686. Camera.prototype.isInFrustum = function (target) {
  18687. this.updateFrustumPlanes();
  18688. return target.isInFrustum(this._frustumPlanes);
  18689. };
  18690. Camera.prototype.isCompletelyInFrustum = function (target) {
  18691. this.updateFrustumPlanes();
  18692. return target.isCompletelyInFrustum(this._frustumPlanes);
  18693. };
  18694. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18695. if (length === void 0) { length = 100; }
  18696. if (!transform) {
  18697. transform = this.getWorldMatrix();
  18698. }
  18699. if (!origin) {
  18700. origin = this.position;
  18701. }
  18702. var forward = new BABYLON.Vector3(0, 0, 1);
  18703. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18704. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18705. return new BABYLON.Ray(origin, direction, length);
  18706. };
  18707. Camera.prototype.dispose = function () {
  18708. // Observables
  18709. this.onViewMatrixChangedObservable.clear();
  18710. this.onProjectionMatrixChangedObservable.clear();
  18711. this.onAfterCheckInputsObservable.clear();
  18712. this.onRestoreStateObservable.clear();
  18713. // Inputs
  18714. if (this.inputs) {
  18715. this.inputs.clear();
  18716. }
  18717. // Animations
  18718. this.getScene().stopAnimation(this);
  18719. // Remove from scene
  18720. this.getScene().removeCamera(this);
  18721. while (this._rigCameras.length > 0) {
  18722. var camera = this._rigCameras.pop();
  18723. if (camera) {
  18724. camera.dispose();
  18725. }
  18726. }
  18727. // Postprocesses
  18728. if (this._rigPostProcess) {
  18729. this._rigPostProcess.dispose(this);
  18730. this._rigPostProcess = null;
  18731. this._postProcesses = [];
  18732. }
  18733. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18734. this._rigPostProcess = null;
  18735. this._postProcesses = [];
  18736. }
  18737. else {
  18738. var i = this._postProcesses.length;
  18739. while (--i >= 0) {
  18740. this._postProcesses[i].dispose(this);
  18741. }
  18742. }
  18743. // Render targets
  18744. var i = this.customRenderTargets.length;
  18745. while (--i >= 0) {
  18746. this.customRenderTargets[i].dispose();
  18747. }
  18748. this.customRenderTargets = [];
  18749. // Active Meshes
  18750. this._activeMeshes.dispose();
  18751. _super.prototype.dispose.call(this);
  18752. };
  18753. Object.defineProperty(Camera.prototype, "leftCamera", {
  18754. // ---- Camera rigs section ----
  18755. get: function () {
  18756. if (this._rigCameras.length < 1) {
  18757. return null;
  18758. }
  18759. return this._rigCameras[0];
  18760. },
  18761. enumerable: true,
  18762. configurable: true
  18763. });
  18764. Object.defineProperty(Camera.prototype, "rightCamera", {
  18765. get: function () {
  18766. if (this._rigCameras.length < 2) {
  18767. return null;
  18768. }
  18769. return this._rigCameras[1];
  18770. },
  18771. enumerable: true,
  18772. configurable: true
  18773. });
  18774. Camera.prototype.getLeftTarget = function () {
  18775. if (this._rigCameras.length < 1) {
  18776. return null;
  18777. }
  18778. return this._rigCameras[0].getTarget();
  18779. };
  18780. Camera.prototype.getRightTarget = function () {
  18781. if (this._rigCameras.length < 2) {
  18782. return null;
  18783. }
  18784. return this._rigCameras[1].getTarget();
  18785. };
  18786. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18787. if (this.cameraRigMode === mode) {
  18788. return;
  18789. }
  18790. while (this._rigCameras.length > 0) {
  18791. var camera = this._rigCameras.pop();
  18792. if (camera) {
  18793. camera.dispose();
  18794. }
  18795. }
  18796. this.cameraRigMode = mode;
  18797. this._cameraRigParams = {};
  18798. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18799. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18800. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18801. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18802. // create the rig cameras, unless none
  18803. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18804. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18805. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18806. if (leftCamera && rightCamera) {
  18807. this._rigCameras.push(leftCamera);
  18808. this._rigCameras.push(rightCamera);
  18809. }
  18810. }
  18811. switch (this.cameraRigMode) {
  18812. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18813. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18814. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18815. break;
  18816. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18817. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18818. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18819. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18820. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18821. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18822. break;
  18823. case Camera.RIG_MODE_VR:
  18824. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18825. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18826. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18827. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18828. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18829. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18830. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18831. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18832. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18833. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18834. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18835. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18836. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18837. if (metrics.compensateDistortion) {
  18838. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18839. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18840. }
  18841. break;
  18842. case Camera.RIG_MODE_WEBVR:
  18843. if (rigParams.vrDisplay) {
  18844. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18845. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18846. //Left eye
  18847. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18848. this._rigCameras[0].setCameraRigParameter("left", true);
  18849. //leaving this for future reference
  18850. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18851. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18852. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18853. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18854. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18855. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18856. this._rigCameras[0].parent = this;
  18857. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18858. //Right eye
  18859. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18860. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18861. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18862. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18863. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18864. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18865. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18866. this._rigCameras[1].parent = this;
  18867. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18868. if (Camera.UseAlternateWebVRRendering) {
  18869. this._rigCameras[1]._skipRendering = true;
  18870. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18871. }
  18872. }
  18873. break;
  18874. }
  18875. this._cascadePostProcessesToRigCams();
  18876. this.update();
  18877. };
  18878. Camera.prototype._getVRProjectionMatrix = function () {
  18879. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18880. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18881. return this._projectionMatrix;
  18882. };
  18883. Camera.prototype._updateCameraRotationMatrix = function () {
  18884. //Here for WebVR
  18885. };
  18886. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18887. //Here for WebVR
  18888. };
  18889. /**
  18890. * This function MUST be overwritten by the different WebVR cameras available.
  18891. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18892. */
  18893. Camera.prototype._getWebVRProjectionMatrix = function () {
  18894. return BABYLON.Matrix.Identity();
  18895. };
  18896. /**
  18897. * This function MUST be overwritten by the different WebVR cameras available.
  18898. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18899. */
  18900. Camera.prototype._getWebVRViewMatrix = function () {
  18901. return BABYLON.Matrix.Identity();
  18902. };
  18903. Camera.prototype.setCameraRigParameter = function (name, value) {
  18904. if (!this._cameraRigParams) {
  18905. this._cameraRigParams = {};
  18906. }
  18907. this._cameraRigParams[name] = value;
  18908. //provisionnally:
  18909. if (name === "interaxialDistance") {
  18910. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18911. }
  18912. };
  18913. /**
  18914. * needs to be overridden by children so sub has required properties to be copied
  18915. */
  18916. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18917. return null;
  18918. };
  18919. /**
  18920. * May need to be overridden by children
  18921. */
  18922. Camera.prototype._updateRigCameras = function () {
  18923. for (var i = 0; i < this._rigCameras.length; i++) {
  18924. this._rigCameras[i].minZ = this.minZ;
  18925. this._rigCameras[i].maxZ = this.maxZ;
  18926. this._rigCameras[i].fov = this.fov;
  18927. }
  18928. // only update viewport when ANAGLYPH
  18929. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18930. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18931. }
  18932. };
  18933. Camera.prototype._setupInputs = function () {
  18934. };
  18935. Camera.prototype.serialize = function () {
  18936. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18937. // Type
  18938. serializationObject.type = this.getClassName();
  18939. // Parent
  18940. if (this.parent) {
  18941. serializationObject.parentId = this.parent.id;
  18942. }
  18943. if (this.inputs) {
  18944. this.inputs.serialize(serializationObject);
  18945. }
  18946. // Animations
  18947. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18948. serializationObject.ranges = this.serializeAnimationRanges();
  18949. return serializationObject;
  18950. };
  18951. Camera.prototype.clone = function (name) {
  18952. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18953. };
  18954. Camera.prototype.getDirection = function (localAxis) {
  18955. var result = BABYLON.Vector3.Zero();
  18956. this.getDirectionToRef(localAxis, result);
  18957. return result;
  18958. };
  18959. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18960. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18961. };
  18962. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18963. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18964. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18965. switch (type) {
  18966. case "ArcRotateCamera":
  18967. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18968. case "DeviceOrientationCamera":
  18969. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18970. case "FollowCamera":
  18971. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18972. case "ArcFollowCamera":
  18973. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18974. case "GamepadCamera":
  18975. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18976. case "TouchCamera":
  18977. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18978. case "VirtualJoysticksCamera":
  18979. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18980. case "WebVRFreeCamera":
  18981. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18982. case "WebVRGamepadCamera":
  18983. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18984. case "VRDeviceOrientationFreeCamera":
  18985. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18986. case "VRDeviceOrientationGamepadCamera":
  18987. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18988. case "AnaglyphArcRotateCamera":
  18989. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18990. case "AnaglyphFreeCamera":
  18991. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18992. case "AnaglyphGamepadCamera":
  18993. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18994. case "AnaglyphUniversalCamera":
  18995. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18996. case "StereoscopicArcRotateCamera":
  18997. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18998. case "StereoscopicFreeCamera":
  18999. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19000. case "StereoscopicGamepadCamera":
  19001. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19002. case "StereoscopicUniversalCamera":
  19003. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19004. case "FreeCamera":// Forcing Universal here
  19005. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19006. default:// Universal Camera is the default value
  19007. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19008. }
  19009. };
  19010. Camera.prototype.computeWorldMatrix = function () {
  19011. return this.getWorldMatrix();
  19012. };
  19013. Camera.Parse = function (parsedCamera, scene) {
  19014. var type = parsedCamera.type;
  19015. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  19016. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  19017. // Parent
  19018. if (parsedCamera.parentId) {
  19019. camera._waitingParentId = parsedCamera.parentId;
  19020. }
  19021. //If camera has an input manager, let it parse inputs settings
  19022. if (camera.inputs) {
  19023. camera.inputs.parse(parsedCamera);
  19024. camera._setupInputs();
  19025. }
  19026. if (camera.setPosition) {
  19027. camera.position.copyFromFloats(0, 0, 0);
  19028. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  19029. }
  19030. // Target
  19031. if (parsedCamera.target) {
  19032. if (camera.setTarget) {
  19033. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19034. }
  19035. }
  19036. // Apply 3d rig, when found
  19037. if (parsedCamera.cameraRigMode) {
  19038. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19039. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19040. }
  19041. // Animations
  19042. if (parsedCamera.animations) {
  19043. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19044. var parsedAnimation = parsedCamera.animations[animationIndex];
  19045. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19046. }
  19047. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  19048. }
  19049. if (parsedCamera.autoAnimate) {
  19050. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  19051. }
  19052. return camera;
  19053. };
  19054. // Statics
  19055. Camera._PERSPECTIVE_CAMERA = 0;
  19056. Camera._ORTHOGRAPHIC_CAMERA = 1;
  19057. Camera._FOVMODE_VERTICAL_FIXED = 0;
  19058. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  19059. Camera._RIG_MODE_NONE = 0;
  19060. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  19061. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  19062. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  19063. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  19064. Camera._RIG_MODE_VR = 20;
  19065. Camera._RIG_MODE_WEBVR = 21;
  19066. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  19067. Camera.UseAlternateWebVRRendering = false;
  19068. __decorate([
  19069. BABYLON.serializeAsVector3()
  19070. ], Camera.prototype, "position", void 0);
  19071. __decorate([
  19072. BABYLON.serializeAsVector3()
  19073. ], Camera.prototype, "upVector", void 0);
  19074. __decorate([
  19075. BABYLON.serialize()
  19076. ], Camera.prototype, "orthoLeft", void 0);
  19077. __decorate([
  19078. BABYLON.serialize()
  19079. ], Camera.prototype, "orthoRight", void 0);
  19080. __decorate([
  19081. BABYLON.serialize()
  19082. ], Camera.prototype, "orthoBottom", void 0);
  19083. __decorate([
  19084. BABYLON.serialize()
  19085. ], Camera.prototype, "orthoTop", void 0);
  19086. __decorate([
  19087. BABYLON.serialize()
  19088. ], Camera.prototype, "fov", void 0);
  19089. __decorate([
  19090. BABYLON.serialize()
  19091. ], Camera.prototype, "minZ", void 0);
  19092. __decorate([
  19093. BABYLON.serialize()
  19094. ], Camera.prototype, "maxZ", void 0);
  19095. __decorate([
  19096. BABYLON.serialize()
  19097. ], Camera.prototype, "inertia", void 0);
  19098. __decorate([
  19099. BABYLON.serialize()
  19100. ], Camera.prototype, "mode", void 0);
  19101. __decorate([
  19102. BABYLON.serialize()
  19103. ], Camera.prototype, "layerMask", void 0);
  19104. __decorate([
  19105. BABYLON.serialize()
  19106. ], Camera.prototype, "fovMode", void 0);
  19107. __decorate([
  19108. BABYLON.serialize()
  19109. ], Camera.prototype, "cameraRigMode", void 0);
  19110. __decorate([
  19111. BABYLON.serialize()
  19112. ], Camera.prototype, "interaxialDistance", void 0);
  19113. __decorate([
  19114. BABYLON.serialize()
  19115. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  19116. return Camera;
  19117. }(BABYLON.Node));
  19118. BABYLON.Camera = Camera;
  19119. })(BABYLON || (BABYLON = {}));
  19120. //# sourceMappingURL=babylon.camera.js.map
  19121. var BABYLON;
  19122. (function (BABYLON) {
  19123. var RenderingManager = /** @class */ (function () {
  19124. function RenderingManager(scene) {
  19125. this._renderingGroups = new Array();
  19126. this._autoClearDepthStencil = {};
  19127. this._customOpaqueSortCompareFn = {};
  19128. this._customAlphaTestSortCompareFn = {};
  19129. this._customTransparentSortCompareFn = {};
  19130. this._renderinGroupInfo = null;
  19131. this._scene = scene;
  19132. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  19133. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  19134. }
  19135. }
  19136. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  19137. if (depth === void 0) { depth = true; }
  19138. if (stencil === void 0) { stencil = true; }
  19139. if (this._depthStencilBufferAlreadyCleaned) {
  19140. return;
  19141. }
  19142. this._scene.getEngine().clear(null, false, depth, stencil);
  19143. this._depthStencilBufferAlreadyCleaned = true;
  19144. };
  19145. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  19146. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  19147. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  19148. var info = null;
  19149. if (observable) {
  19150. if (!this._renderinGroupInfo) {
  19151. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  19152. }
  19153. info = this._renderinGroupInfo;
  19154. info.scene = this._scene;
  19155. info.camera = this._scene.activeCamera;
  19156. }
  19157. // Dispatch sprites
  19158. if (renderSprites) {
  19159. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  19160. var manager = this._scene.spriteManagers[index];
  19161. this.dispatchSprites(manager);
  19162. }
  19163. }
  19164. // Render
  19165. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19166. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  19167. var renderingGroup = this._renderingGroups[index];
  19168. if (!renderingGroup && !observable)
  19169. continue;
  19170. var renderingGroupMask = 0;
  19171. // Fire PRECLEAR stage
  19172. if (observable && info) {
  19173. renderingGroupMask = Math.pow(2, index);
  19174. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  19175. info.renderingGroupId = index;
  19176. observable.notifyObservers(info, renderingGroupMask);
  19177. }
  19178. // Clear depth/stencil if needed
  19179. if (RenderingManager.AUTOCLEAR) {
  19180. var autoClear = this._autoClearDepthStencil[index];
  19181. if (autoClear && autoClear.autoClear) {
  19182. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  19183. }
  19184. }
  19185. if (observable && info) {
  19186. // Fire PREOPAQUE stage
  19187. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  19188. observable.notifyObservers(info, renderingGroupMask);
  19189. // Fire PRETRANSPARENT stage
  19190. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  19191. observable.notifyObservers(info, renderingGroupMask);
  19192. }
  19193. if (renderingGroup)
  19194. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  19195. // Fire POSTTRANSPARENT stage
  19196. if (observable && info) {
  19197. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  19198. observable.notifyObservers(info, renderingGroupMask);
  19199. }
  19200. }
  19201. };
  19202. RenderingManager.prototype.reset = function () {
  19203. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19204. var renderingGroup = this._renderingGroups[index];
  19205. if (renderingGroup) {
  19206. renderingGroup.prepare();
  19207. }
  19208. }
  19209. };
  19210. RenderingManager.prototype.dispose = function () {
  19211. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19212. var renderingGroup = this._renderingGroups[index];
  19213. if (renderingGroup) {
  19214. renderingGroup.dispose();
  19215. }
  19216. }
  19217. this._renderingGroups.length = 0;
  19218. };
  19219. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  19220. if (this._renderingGroups[renderingGroupId] === undefined) {
  19221. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  19222. }
  19223. };
  19224. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  19225. var renderingGroupId = spriteManager.renderingGroupId || 0;
  19226. this._prepareRenderingGroup(renderingGroupId);
  19227. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  19228. };
  19229. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  19230. var renderingGroupId = particleSystem.renderingGroupId || 0;
  19231. this._prepareRenderingGroup(renderingGroupId);
  19232. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  19233. };
  19234. /**
  19235. * @param subMesh The submesh to dispatch
  19236. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19237. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19238. */
  19239. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  19240. if (mesh === undefined) {
  19241. mesh = subMesh.getMesh();
  19242. }
  19243. var renderingGroupId = mesh.renderingGroupId || 0;
  19244. this._prepareRenderingGroup(renderingGroupId);
  19245. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  19246. };
  19247. /**
  19248. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19249. * This allowed control for front to back rendering or reversly depending of the special needs.
  19250. *
  19251. * @param renderingGroupId The rendering group id corresponding to its index
  19252. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19253. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19254. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19255. */
  19256. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19257. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19258. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19259. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19260. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  19261. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  19262. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  19263. if (this._renderingGroups[renderingGroupId]) {
  19264. var group = this._renderingGroups[renderingGroupId];
  19265. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  19266. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  19267. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19268. }
  19269. };
  19270. /**
  19271. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19272. *
  19273. * @param renderingGroupId The rendering group id corresponding to its index
  19274. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19275. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19276. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19277. */
  19278. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19279. if (depth === void 0) { depth = true; }
  19280. if (stencil === void 0) { stencil = true; }
  19281. this._autoClearDepthStencil[renderingGroupId] = {
  19282. autoClear: autoClearDepthStencil,
  19283. depth: depth,
  19284. stencil: stencil
  19285. };
  19286. };
  19287. /**
  19288. * The max id used for rendering groups (not included)
  19289. */
  19290. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19291. /**
  19292. * The min id used for rendering groups (included)
  19293. */
  19294. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19295. /**
  19296. * Used to globally prevent autoclearing scenes.
  19297. */
  19298. RenderingManager.AUTOCLEAR = true;
  19299. return RenderingManager;
  19300. }());
  19301. BABYLON.RenderingManager = RenderingManager;
  19302. })(BABYLON || (BABYLON = {}));
  19303. //# sourceMappingURL=babylon.renderingManager.js.map
  19304. var BABYLON;
  19305. (function (BABYLON) {
  19306. var RenderingGroup = /** @class */ (function () {
  19307. /**
  19308. * Creates a new rendering group.
  19309. * @param index The rendering group index
  19310. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19311. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19312. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19313. */
  19314. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19315. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19316. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19317. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19318. this.index = index;
  19319. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19320. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19321. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19322. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  19323. this._particleSystems = new BABYLON.SmartArray(256);
  19324. this._spriteManagers = new BABYLON.SmartArray(256);
  19325. this._edgesRenderers = new BABYLON.SmartArray(16);
  19326. this._scene = scene;
  19327. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19328. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19329. this.transparentSortCompareFn = transparentSortCompareFn;
  19330. }
  19331. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19332. /**
  19333. * Set the opaque sort comparison function.
  19334. * If null the sub meshes will be render in the order they were created
  19335. */
  19336. set: function (value) {
  19337. this._opaqueSortCompareFn = value;
  19338. if (value) {
  19339. this._renderOpaque = this.renderOpaqueSorted;
  19340. }
  19341. else {
  19342. this._renderOpaque = RenderingGroup.renderUnsorted;
  19343. }
  19344. },
  19345. enumerable: true,
  19346. configurable: true
  19347. });
  19348. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19349. /**
  19350. * Set the alpha test sort comparison function.
  19351. * If null the sub meshes will be render in the order they were created
  19352. */
  19353. set: function (value) {
  19354. this._alphaTestSortCompareFn = value;
  19355. if (value) {
  19356. this._renderAlphaTest = this.renderAlphaTestSorted;
  19357. }
  19358. else {
  19359. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19360. }
  19361. },
  19362. enumerable: true,
  19363. configurable: true
  19364. });
  19365. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19366. /**
  19367. * Set the transparent sort comparison function.
  19368. * If null the sub meshes will be render in the order they were created
  19369. */
  19370. set: function (value) {
  19371. if (value) {
  19372. this._transparentSortCompareFn = value;
  19373. }
  19374. else {
  19375. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19376. }
  19377. this._renderTransparent = this.renderTransparentSorted;
  19378. },
  19379. enumerable: true,
  19380. configurable: true
  19381. });
  19382. /**
  19383. * Render all the sub meshes contained in the group.
  19384. * @param customRenderFunction Used to override the default render behaviour of the group.
  19385. * @returns true if rendered some submeshes.
  19386. */
  19387. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19388. if (customRenderFunction) {
  19389. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  19390. return;
  19391. }
  19392. var engine = this._scene.getEngine();
  19393. // Depth only
  19394. if (this._depthOnlySubMeshes.length !== 0) {
  19395. engine.setColorWrite(false);
  19396. this._renderAlphaTest(this._depthOnlySubMeshes);
  19397. engine.setColorWrite(true);
  19398. }
  19399. // Opaque
  19400. if (this._opaqueSubMeshes.length !== 0) {
  19401. this._renderOpaque(this._opaqueSubMeshes);
  19402. }
  19403. // Alpha test
  19404. if (this._alphaTestSubMeshes.length !== 0) {
  19405. this._renderAlphaTest(this._alphaTestSubMeshes);
  19406. }
  19407. var stencilState = engine.getStencilBuffer();
  19408. engine.setStencilBuffer(false);
  19409. // Sprites
  19410. if (renderSprites) {
  19411. this._renderSprites();
  19412. }
  19413. // Particles
  19414. if (renderParticles) {
  19415. this._renderParticles(activeMeshes);
  19416. }
  19417. if (this.onBeforeTransparentRendering) {
  19418. this.onBeforeTransparentRendering();
  19419. }
  19420. // Transparent
  19421. if (this._transparentSubMeshes.length !== 0) {
  19422. this._renderTransparent(this._transparentSubMeshes);
  19423. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19424. }
  19425. // Set back stencil to false in case it changes before the edge renderer.
  19426. engine.setStencilBuffer(false);
  19427. // Edges
  19428. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19429. this._edgesRenderers.data[edgesRendererIndex].render();
  19430. }
  19431. // Restore Stencil state.
  19432. engine.setStencilBuffer(stencilState);
  19433. };
  19434. /**
  19435. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19436. * @param subMeshes The submeshes to render
  19437. */
  19438. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19439. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  19440. };
  19441. /**
  19442. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19443. * @param subMeshes The submeshes to render
  19444. */
  19445. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19446. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  19447. };
  19448. /**
  19449. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19450. * @param subMeshes The submeshes to render
  19451. */
  19452. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19453. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  19454. };
  19455. /**
  19456. * Renders the submeshes in a specified order.
  19457. * @param subMeshes The submeshes to sort before render
  19458. * @param sortCompareFn The comparison function use to sort
  19459. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19460. * @param transparent Specifies to activate blending if true
  19461. */
  19462. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  19463. var subIndex = 0;
  19464. var subMesh;
  19465. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  19466. for (; subIndex < subMeshes.length; subIndex++) {
  19467. subMesh = subMeshes.data[subIndex];
  19468. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19469. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19470. }
  19471. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19472. if (sortCompareFn) {
  19473. sortedArray.sort(sortCompareFn);
  19474. }
  19475. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19476. subMesh = sortedArray[subIndex];
  19477. if (transparent) {
  19478. var material = subMesh.getMaterial();
  19479. if (material && material.needDepthPrePass) {
  19480. var engine = material.getScene().getEngine();
  19481. engine.setColorWrite(false);
  19482. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19483. subMesh.render(false);
  19484. engine.setColorWrite(true);
  19485. }
  19486. }
  19487. subMesh.render(transparent);
  19488. }
  19489. };
  19490. /**
  19491. * Renders the submeshes in the order they were dispatched (no sort applied).
  19492. * @param subMeshes The submeshes to render
  19493. */
  19494. RenderingGroup.renderUnsorted = function (subMeshes) {
  19495. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19496. var submesh = subMeshes.data[subIndex];
  19497. submesh.render(false);
  19498. }
  19499. };
  19500. /**
  19501. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19502. * are rendered back to front if in the same alpha index.
  19503. *
  19504. * @param a The first submesh
  19505. * @param b The second submesh
  19506. * @returns The result of the comparison
  19507. */
  19508. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19509. // Alpha index first
  19510. if (a._alphaIndex > b._alphaIndex) {
  19511. return 1;
  19512. }
  19513. if (a._alphaIndex < b._alphaIndex) {
  19514. return -1;
  19515. }
  19516. // Then distance to camera
  19517. return RenderingGroup.backToFrontSortCompare(a, b);
  19518. };
  19519. /**
  19520. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19521. * are rendered back to front.
  19522. *
  19523. * @param a The first submesh
  19524. * @param b The second submesh
  19525. * @returns The result of the comparison
  19526. */
  19527. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19528. // Then distance to camera
  19529. if (a._distanceToCamera < b._distanceToCamera) {
  19530. return 1;
  19531. }
  19532. if (a._distanceToCamera > b._distanceToCamera) {
  19533. return -1;
  19534. }
  19535. return 0;
  19536. };
  19537. /**
  19538. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19539. * are rendered front to back (prevent overdraw).
  19540. *
  19541. * @param a The first submesh
  19542. * @param b The second submesh
  19543. * @returns The result of the comparison
  19544. */
  19545. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19546. // Then distance to camera
  19547. if (a._distanceToCamera < b._distanceToCamera) {
  19548. return -1;
  19549. }
  19550. if (a._distanceToCamera > b._distanceToCamera) {
  19551. return 1;
  19552. }
  19553. return 0;
  19554. };
  19555. /**
  19556. * Resets the different lists of submeshes to prepare a new frame.
  19557. */
  19558. RenderingGroup.prototype.prepare = function () {
  19559. this._opaqueSubMeshes.reset();
  19560. this._transparentSubMeshes.reset();
  19561. this._alphaTestSubMeshes.reset();
  19562. this._depthOnlySubMeshes.reset();
  19563. this._particleSystems.reset();
  19564. this._spriteManagers.reset();
  19565. this._edgesRenderers.reset();
  19566. };
  19567. RenderingGroup.prototype.dispose = function () {
  19568. this._opaqueSubMeshes.dispose();
  19569. this._transparentSubMeshes.dispose();
  19570. this._alphaTestSubMeshes.dispose();
  19571. this._depthOnlySubMeshes.dispose();
  19572. this._particleSystems.dispose();
  19573. this._spriteManagers.dispose();
  19574. this._edgesRenderers.dispose();
  19575. };
  19576. /**
  19577. * Inserts the submesh in its correct queue depending on its material.
  19578. * @param subMesh The submesh to dispatch
  19579. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19580. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19581. */
  19582. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19583. // Get mesh and materials if not provided
  19584. if (mesh === undefined) {
  19585. mesh = subMesh.getMesh();
  19586. }
  19587. if (material === undefined) {
  19588. material = subMesh.getMaterial();
  19589. }
  19590. if (material === null || material === undefined) {
  19591. return;
  19592. }
  19593. if (material.needAlphaBlendingForMesh(mesh)) {
  19594. this._transparentSubMeshes.push(subMesh);
  19595. }
  19596. else if (material.needAlphaTesting()) {
  19597. if (material.needDepthPrePass) {
  19598. this._depthOnlySubMeshes.push(subMesh);
  19599. }
  19600. this._alphaTestSubMeshes.push(subMesh);
  19601. }
  19602. else {
  19603. if (material.needDepthPrePass) {
  19604. this._depthOnlySubMeshes.push(subMesh);
  19605. }
  19606. this._opaqueSubMeshes.push(subMesh); // Opaque
  19607. }
  19608. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19609. this._edgesRenderers.push(mesh._edgesRenderer);
  19610. }
  19611. };
  19612. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19613. this._spriteManagers.push(spriteManager);
  19614. };
  19615. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19616. this._particleSystems.push(particleSystem);
  19617. };
  19618. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19619. if (this._particleSystems.length === 0) {
  19620. return;
  19621. }
  19622. // Particles
  19623. var activeCamera = this._scene.activeCamera;
  19624. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19625. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19626. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19627. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19628. continue;
  19629. }
  19630. var emitter = particleSystem.emitter;
  19631. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19632. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19633. }
  19634. }
  19635. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19636. };
  19637. RenderingGroup.prototype._renderSprites = function () {
  19638. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19639. return;
  19640. }
  19641. // Sprites
  19642. var activeCamera = this._scene.activeCamera;
  19643. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19644. for (var id = 0; id < this._spriteManagers.length; id++) {
  19645. var spriteManager = this._spriteManagers.data[id];
  19646. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19647. spriteManager.render();
  19648. }
  19649. }
  19650. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19651. };
  19652. return RenderingGroup;
  19653. }());
  19654. BABYLON.RenderingGroup = RenderingGroup;
  19655. })(BABYLON || (BABYLON = {}));
  19656. //# sourceMappingURL=babylon.renderingGroup.js.map
  19657. var BABYLON;
  19658. (function (BABYLON) {
  19659. var ClickInfo = /** @class */ (function () {
  19660. function ClickInfo() {
  19661. this._singleClick = false;
  19662. this._doubleClick = false;
  19663. this._hasSwiped = false;
  19664. this._ignore = false;
  19665. }
  19666. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19667. get: function () {
  19668. return this._singleClick;
  19669. },
  19670. set: function (b) {
  19671. this._singleClick = b;
  19672. },
  19673. enumerable: true,
  19674. configurable: true
  19675. });
  19676. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19677. get: function () {
  19678. return this._doubleClick;
  19679. },
  19680. set: function (b) {
  19681. this._doubleClick = b;
  19682. },
  19683. enumerable: true,
  19684. configurable: true
  19685. });
  19686. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19687. get: function () {
  19688. return this._hasSwiped;
  19689. },
  19690. set: function (b) {
  19691. this._hasSwiped = b;
  19692. },
  19693. enumerable: true,
  19694. configurable: true
  19695. });
  19696. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19697. get: function () {
  19698. return this._ignore;
  19699. },
  19700. set: function (b) {
  19701. this._ignore = b;
  19702. },
  19703. enumerable: true,
  19704. configurable: true
  19705. });
  19706. return ClickInfo;
  19707. }());
  19708. /**
  19709. * This class is used by the onRenderingGroupObservable
  19710. */
  19711. var RenderingGroupInfo = /** @class */ (function () {
  19712. function RenderingGroupInfo() {
  19713. }
  19714. /**
  19715. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19716. * This stage will be fired no matter what
  19717. */
  19718. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19719. /**
  19720. * Called before opaque object are rendered.
  19721. * This stage will be fired only if there's 3D Opaque content to render
  19722. */
  19723. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19724. /**
  19725. * Called after the opaque objects are rendered and before the transparent ones
  19726. * This stage will be fired only if there's 3D transparent content to render
  19727. */
  19728. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19729. /**
  19730. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19731. * This stage will be fired no matter what
  19732. */
  19733. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19734. return RenderingGroupInfo;
  19735. }());
  19736. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19737. /**
  19738. * Represents a scene to be rendered by the engine.
  19739. * @see http://doc.babylonjs.com/page.php?p=21911
  19740. */
  19741. var Scene = /** @class */ (function () {
  19742. /**
  19743. * @constructor
  19744. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19745. */
  19746. function Scene(engine) {
  19747. // Members
  19748. this.autoClear = true;
  19749. this.autoClearDepthAndStencil = true;
  19750. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19751. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19752. this.forceWireframe = false;
  19753. this._forcePointsCloud = false;
  19754. this.forceShowBoundingBoxes = false;
  19755. this.animationsEnabled = true;
  19756. this.useConstantAnimationDeltaTime = false;
  19757. this.constantlyUpdateMeshUnderPointer = false;
  19758. this.hoverCursor = "pointer";
  19759. this.defaultCursor = "";
  19760. /**
  19761. * This is used to call preventDefault() on pointer down
  19762. * in order to block unwanted artifacts like system double clicks
  19763. */
  19764. this.preventDefaultOnPointerDown = true;
  19765. // Metadata
  19766. this.metadata = null;
  19767. /**
  19768. * An event triggered when the scene is disposed.
  19769. * @type {BABYLON.Observable}
  19770. */
  19771. this.onDisposeObservable = new BABYLON.Observable();
  19772. /**
  19773. * An event triggered before rendering the scene (right after animations and physics)
  19774. * @type {BABYLON.Observable}
  19775. */
  19776. this.onBeforeRenderObservable = new BABYLON.Observable();
  19777. /**
  19778. * An event triggered after rendering the scene
  19779. * @type {BABYLON.Observable}
  19780. */
  19781. this.onAfterRenderObservable = new BABYLON.Observable();
  19782. /**
  19783. * An event triggered before animating the scene
  19784. * @type {BABYLON.Observable}
  19785. */
  19786. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19787. /**
  19788. * An event triggered after animations processing
  19789. * @type {BABYLON.Observable}
  19790. */
  19791. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19792. /**
  19793. * An event triggered before draw calls are ready to be sent
  19794. * @type {BABYLON.Observable}
  19795. */
  19796. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19797. /**
  19798. * An event triggered after draw calls have been sent
  19799. * @type {BABYLON.Observable}
  19800. */
  19801. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19802. /**
  19803. * An event triggered when physic simulation is about to be run
  19804. * @type {BABYLON.Observable}
  19805. */
  19806. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19807. /**
  19808. * An event triggered when physic simulation has been done
  19809. * @type {BABYLON.Observable}
  19810. */
  19811. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19812. /**
  19813. * An event triggered when the scene is ready
  19814. * @type {BABYLON.Observable}
  19815. */
  19816. this.onReadyObservable = new BABYLON.Observable();
  19817. /**
  19818. * An event triggered before rendering a camera
  19819. * @type {BABYLON.Observable}
  19820. */
  19821. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19822. /**
  19823. * An event triggered after rendering a camera
  19824. * @type {BABYLON.Observable}
  19825. */
  19826. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19827. /**
  19828. * An event triggered when active meshes evaluation is about to start
  19829. * @type {BABYLON.Observable}
  19830. */
  19831. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19832. /**
  19833. * An event triggered when active meshes evaluation is done
  19834. * @type {BABYLON.Observable}
  19835. */
  19836. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19837. /**
  19838. * An event triggered when particles rendering is about to start
  19839. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19840. * @type {BABYLON.Observable}
  19841. */
  19842. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19843. /**
  19844. * An event triggered when particles rendering is done
  19845. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19846. * @type {BABYLON.Observable}
  19847. */
  19848. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19849. /**
  19850. * An event triggered when sprites rendering is about to start
  19851. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19852. * @type {BABYLON.Observable}
  19853. */
  19854. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19855. /**
  19856. * An event triggered when sprites rendering is done
  19857. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19858. * @type {BABYLON.Observable}
  19859. */
  19860. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19861. /**
  19862. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19863. * @type {BABYLON.Observable}
  19864. */
  19865. this.onDataLoadedObservable = new BABYLON.Observable();
  19866. /**
  19867. * An event triggered when a camera is created
  19868. * @type {BABYLON.Observable}
  19869. */
  19870. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19871. /**
  19872. * An event triggered when a camera is removed
  19873. * @type {BABYLON.Observable}
  19874. */
  19875. this.onCameraRemovedObservable = new BABYLON.Observable();
  19876. /**
  19877. * An event triggered when a light is created
  19878. * @type {BABYLON.Observable}
  19879. */
  19880. this.onNewLightAddedObservable = new BABYLON.Observable();
  19881. /**
  19882. * An event triggered when a light is removed
  19883. * @type {BABYLON.Observable}
  19884. */
  19885. this.onLightRemovedObservable = new BABYLON.Observable();
  19886. /**
  19887. * An event triggered when a geometry is created
  19888. * @type {BABYLON.Observable}
  19889. */
  19890. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19891. /**
  19892. * An event triggered when a geometry is removed
  19893. * @type {BABYLON.Observable}
  19894. */
  19895. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19896. /**
  19897. * An event triggered when a transform node is created
  19898. * @type {BABYLON.Observable}
  19899. */
  19900. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19901. /**
  19902. * An event triggered when a transform node is removed
  19903. * @type {BABYLON.Observable}
  19904. */
  19905. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19906. /**
  19907. * An event triggered when a mesh is created
  19908. * @type {BABYLON.Observable}
  19909. */
  19910. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19911. /**
  19912. * An event triggered when a mesh is removed
  19913. * @type {BABYLON.Observable}
  19914. */
  19915. this.onMeshRemovedObservable = new BABYLON.Observable();
  19916. /**
  19917. * An event triggered when render targets are about to be rendered
  19918. * Can happen multiple times per frame.
  19919. * @type {BABYLON.Observable}
  19920. */
  19921. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19922. /**
  19923. * An event triggered when render targets were rendered.
  19924. * Can happen multiple times per frame.
  19925. * @type {BABYLON.Observable}
  19926. */
  19927. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19928. /**
  19929. * An event triggered before calculating deterministic simulation step
  19930. * @type {BABYLON.Observable}
  19931. */
  19932. this.onBeforeStepObservable = new BABYLON.Observable();
  19933. /**
  19934. * An event triggered after calculating deterministic simulation step
  19935. * @type {BABYLON.Observable}
  19936. */
  19937. this.onAfterStepObservable = new BABYLON.Observable();
  19938. /**
  19939. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19940. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19941. * 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)
  19942. */
  19943. this.onRenderingGroupObservable = new BABYLON.Observable();
  19944. // Animations
  19945. this.animations = [];
  19946. /**
  19947. * 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).
  19948. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19949. */
  19950. this.onPrePointerObservable = new BABYLON.Observable();
  19951. /**
  19952. * Observable event triggered each time an input event is received from the rendering canvas
  19953. */
  19954. this.onPointerObservable = new BABYLON.Observable();
  19955. this._meshPickProceed = false;
  19956. this._currentPickResult = null;
  19957. this._previousPickResult = null;
  19958. this._totalPointersPressed = 0;
  19959. this._doubleClickOccured = false;
  19960. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19961. this.cameraToUseForPointers = null;
  19962. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19963. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19964. this._startingPointerTime = 0;
  19965. this._previousStartingPointerTime = 0;
  19966. // Deterministic lockstep
  19967. this._timeAccumulator = 0;
  19968. this._currentStepId = 0;
  19969. this._currentInternalStep = 0;
  19970. // Keyboard
  19971. /**
  19972. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19973. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19974. */
  19975. this.onPreKeyboardObservable = new BABYLON.Observable();
  19976. /**
  19977. * Observable event triggered each time an keyboard event is received from the hosting window
  19978. */
  19979. this.onKeyboardObservable = new BABYLON.Observable();
  19980. // Coordinate system
  19981. /**
  19982. * use right-handed coordinate system on this scene.
  19983. * @type {boolean}
  19984. */
  19985. this._useRightHandedSystem = false;
  19986. // Fog
  19987. this._fogEnabled = true;
  19988. this._fogMode = Scene.FOGMODE_NONE;
  19989. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19990. this.fogDensity = 0.1;
  19991. this.fogStart = 0;
  19992. this.fogEnd = 1000.0;
  19993. // Lights
  19994. /**
  19995. * is shadow enabled on this scene.
  19996. * @type {boolean}
  19997. */
  19998. this._shadowsEnabled = true;
  19999. /**
  20000. * is light enabled on this scene.
  20001. * @type {boolean}
  20002. */
  20003. this._lightsEnabled = true;
  20004. /**
  20005. * All of the lights added to this scene.
  20006. * @see BABYLON.Light
  20007. * @type {BABYLON.Light[]}
  20008. */
  20009. this.lights = new Array();
  20010. // Cameras
  20011. /** All of the cameras added to this scene. */
  20012. this.cameras = new Array();
  20013. /** All of the active cameras added to this scene. */
  20014. this.activeCameras = new Array();
  20015. // Meshes
  20016. /**
  20017. * All of the tranform nodes added to this scene.
  20018. * @see BABYLON.TransformNode
  20019. * @type {BABYLON.TransformNode[]}
  20020. */
  20021. this.transformNodes = new Array();
  20022. /**
  20023. * All of the (abstract) meshes added to this scene.
  20024. * @see BABYLON.AbstractMesh
  20025. * @type {BABYLON.AbstractMesh[]}
  20026. */
  20027. this.meshes = new Array();
  20028. /**
  20029. * All of the animation groups added to this scene.
  20030. * @see BABYLON.AnimationGroup
  20031. * @type {BABYLON.AnimationGroup[]}
  20032. */
  20033. this.animationGroups = new Array();
  20034. // Geometries
  20035. this._geometries = new Array();
  20036. this.materials = new Array();
  20037. this.multiMaterials = new Array();
  20038. // Textures
  20039. this._texturesEnabled = true;
  20040. this.textures = new Array();
  20041. // Particles
  20042. this.particlesEnabled = true;
  20043. this.particleSystems = new Array();
  20044. // Sprites
  20045. this.spritesEnabled = true;
  20046. this.spriteManagers = new Array();
  20047. // Layers
  20048. this.layers = new Array();
  20049. this.highlightLayers = new Array();
  20050. // Skeletons
  20051. this._skeletonsEnabled = true;
  20052. this.skeletons = new Array();
  20053. // Morph targets
  20054. this.morphTargetManagers = new Array();
  20055. // Lens flares
  20056. this.lensFlaresEnabled = true;
  20057. this.lensFlareSystems = new Array();
  20058. // Collisions
  20059. this.collisionsEnabled = true;
  20060. /** Defines the gravity applied to this scene */
  20061. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20062. // Postprocesses
  20063. this.postProcesses = new Array();
  20064. this.postProcessesEnabled = true;
  20065. // Customs render targets
  20066. this.renderTargetsEnabled = true;
  20067. this.dumpNextRenderTargets = false;
  20068. this.customRenderTargets = new Array();
  20069. // Imported meshes
  20070. this.importedMeshesFiles = new Array();
  20071. // Probes
  20072. this.probesEnabled = true;
  20073. this.reflectionProbes = new Array();
  20074. this._actionManagers = new Array();
  20075. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  20076. // Procedural textures
  20077. this.proceduralTexturesEnabled = true;
  20078. this._proceduralTextures = new Array();
  20079. this.soundTracks = new Array();
  20080. this._audioEnabled = true;
  20081. this._headphone = false;
  20082. // Performance counters
  20083. this._totalVertices = new BABYLON.PerfCounter();
  20084. this._activeIndices = new BABYLON.PerfCounter();
  20085. this._activeParticles = new BABYLON.PerfCounter();
  20086. this._activeBones = new BABYLON.PerfCounter();
  20087. this._animationTime = 0;
  20088. this.animationTimeScale = 1;
  20089. this._renderId = 0;
  20090. this._executeWhenReadyTimeoutId = -1;
  20091. this._intermediateRendering = false;
  20092. this._viewUpdateFlag = -1;
  20093. this._projectionUpdateFlag = -1;
  20094. this._alternateViewUpdateFlag = -1;
  20095. this._alternateProjectionUpdateFlag = -1;
  20096. this._toBeDisposed = new BABYLON.SmartArray(256);
  20097. this._activeRequests = new Array();
  20098. this._pendingData = new Array();
  20099. this._isDisposed = false;
  20100. this.dispatchAllSubMeshesOfActiveMeshes = false;
  20101. this._activeMeshes = new BABYLON.SmartArray(256);
  20102. this._processedMaterials = new BABYLON.SmartArray(256);
  20103. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  20104. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20105. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  20106. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  20107. this._activeAnimatables = new Array();
  20108. this._transformMatrix = BABYLON.Matrix.Zero();
  20109. this._useAlternateCameraConfiguration = false;
  20110. this._alternateRendering = false;
  20111. this.requireLightSorting = false;
  20112. this._activeMeshesFrozen = false;
  20113. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  20114. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20115. this._engine.scenes.push(this);
  20116. this._uid = null;
  20117. this._renderingManager = new BABYLON.RenderingManager(this);
  20118. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20119. if (BABYLON.OutlineRenderer) {
  20120. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  20121. }
  20122. if (BABYLON.Tools.IsWindowObjectExist()) {
  20123. this.attachControl();
  20124. }
  20125. //simplification queue
  20126. if (BABYLON.SimplificationQueue) {
  20127. this.simplificationQueue = new BABYLON.SimplificationQueue();
  20128. }
  20129. //collision coordinator initialization. For now legacy per default.
  20130. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  20131. // Uniform Buffer
  20132. this._createUbo();
  20133. // Default Image processing definition.
  20134. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  20135. }
  20136. Object.defineProperty(Scene, "FOGMODE_NONE", {
  20137. /** The fog is deactivated */
  20138. get: function () {
  20139. return Scene._FOGMODE_NONE;
  20140. },
  20141. enumerable: true,
  20142. configurable: true
  20143. });
  20144. Object.defineProperty(Scene, "FOGMODE_EXP", {
  20145. /** The fog density is following an exponential function */
  20146. get: function () {
  20147. return Scene._FOGMODE_EXP;
  20148. },
  20149. enumerable: true,
  20150. configurable: true
  20151. });
  20152. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  20153. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  20154. get: function () {
  20155. return Scene._FOGMODE_EXP2;
  20156. },
  20157. enumerable: true,
  20158. configurable: true
  20159. });
  20160. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  20161. /** The fog density is following a linear function. */
  20162. get: function () {
  20163. return Scene._FOGMODE_LINEAR;
  20164. },
  20165. enumerable: true,
  20166. configurable: true
  20167. });
  20168. Object.defineProperty(Scene.prototype, "environmentTexture", {
  20169. /**
  20170. * Texture used in all pbr material as the reflection texture.
  20171. * As in the majority of the scene they are the same (exception for multi room and so on),
  20172. * this is easier to reference from here than from all the materials.
  20173. */
  20174. get: function () {
  20175. return this._environmentTexture;
  20176. },
  20177. /**
  20178. * Texture used in all pbr material as the reflection texture.
  20179. * As in the majority of the scene they are the same (exception for multi room and so on),
  20180. * this is easier to set here than in all the materials.
  20181. */
  20182. set: function (value) {
  20183. if (this._environmentTexture === value) {
  20184. return;
  20185. }
  20186. this._environmentTexture = value;
  20187. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20188. },
  20189. enumerable: true,
  20190. configurable: true
  20191. });
  20192. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  20193. /**
  20194. * Default image processing configuration used either in the rendering
  20195. * Forward main pass or through the imageProcessingPostProcess if present.
  20196. * As in the majority of the scene they are the same (exception for multi camera),
  20197. * this is easier to reference from here than from all the materials and post process.
  20198. *
  20199. * No setter as we it is a shared configuration, you can set the values instead.
  20200. */
  20201. get: function () {
  20202. return this._imageProcessingConfiguration;
  20203. },
  20204. enumerable: true,
  20205. configurable: true
  20206. });
  20207. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  20208. get: function () {
  20209. return this._forcePointsCloud;
  20210. },
  20211. set: function (value) {
  20212. if (this._forcePointsCloud === value) {
  20213. return;
  20214. }
  20215. this._forcePointsCloud = value;
  20216. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20217. },
  20218. enumerable: true,
  20219. configurable: true
  20220. });
  20221. Object.defineProperty(Scene.prototype, "onDispose", {
  20222. /** A function to be executed when this scene is disposed. */
  20223. set: function (callback) {
  20224. if (this._onDisposeObserver) {
  20225. this.onDisposeObservable.remove(this._onDisposeObserver);
  20226. }
  20227. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20228. },
  20229. enumerable: true,
  20230. configurable: true
  20231. });
  20232. Object.defineProperty(Scene.prototype, "beforeRender", {
  20233. /** A function to be executed before rendering this scene */
  20234. set: function (callback) {
  20235. if (this._onBeforeRenderObserver) {
  20236. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  20237. }
  20238. if (callback) {
  20239. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  20240. }
  20241. },
  20242. enumerable: true,
  20243. configurable: true
  20244. });
  20245. Object.defineProperty(Scene.prototype, "afterRender", {
  20246. /** A function to be executed after rendering this scene */
  20247. set: function (callback) {
  20248. if (this._onAfterRenderObserver) {
  20249. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  20250. }
  20251. if (callback) {
  20252. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  20253. }
  20254. },
  20255. enumerable: true,
  20256. configurable: true
  20257. });
  20258. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  20259. set: function (callback) {
  20260. if (this._onBeforeCameraRenderObserver) {
  20261. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  20262. }
  20263. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  20264. },
  20265. enumerable: true,
  20266. configurable: true
  20267. });
  20268. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  20269. set: function (callback) {
  20270. if (this._onAfterCameraRenderObserver) {
  20271. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  20272. }
  20273. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  20274. },
  20275. enumerable: true,
  20276. configurable: true
  20277. });
  20278. Object.defineProperty(Scene.prototype, "gamepadManager", {
  20279. get: function () {
  20280. if (!this._gamepadManager) {
  20281. this._gamepadManager = new BABYLON.GamepadManager(this);
  20282. }
  20283. return this._gamepadManager;
  20284. },
  20285. enumerable: true,
  20286. configurable: true
  20287. });
  20288. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  20289. get: function () {
  20290. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  20291. },
  20292. enumerable: true,
  20293. configurable: true
  20294. });
  20295. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  20296. get: function () {
  20297. return this._useRightHandedSystem;
  20298. },
  20299. set: function (value) {
  20300. if (this._useRightHandedSystem === value) {
  20301. return;
  20302. }
  20303. this._useRightHandedSystem = value;
  20304. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20305. },
  20306. enumerable: true,
  20307. configurable: true
  20308. });
  20309. Scene.prototype.setStepId = function (newStepId) {
  20310. this._currentStepId = newStepId;
  20311. };
  20312. ;
  20313. Scene.prototype.getStepId = function () {
  20314. return this._currentStepId;
  20315. };
  20316. ;
  20317. Scene.prototype.getInternalStep = function () {
  20318. return this._currentInternalStep;
  20319. };
  20320. ;
  20321. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20322. get: function () {
  20323. return this._fogEnabled;
  20324. },
  20325. /**
  20326. * is fog enabled on this scene.
  20327. */
  20328. set: function (value) {
  20329. if (this._fogEnabled === value) {
  20330. return;
  20331. }
  20332. this._fogEnabled = value;
  20333. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20334. },
  20335. enumerable: true,
  20336. configurable: true
  20337. });
  20338. Object.defineProperty(Scene.prototype, "fogMode", {
  20339. get: function () {
  20340. return this._fogMode;
  20341. },
  20342. set: function (value) {
  20343. if (this._fogMode === value) {
  20344. return;
  20345. }
  20346. this._fogMode = value;
  20347. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20348. },
  20349. enumerable: true,
  20350. configurable: true
  20351. });
  20352. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20353. get: function () {
  20354. return this._shadowsEnabled;
  20355. },
  20356. set: function (value) {
  20357. if (this._shadowsEnabled === value) {
  20358. return;
  20359. }
  20360. this._shadowsEnabled = value;
  20361. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20362. },
  20363. enumerable: true,
  20364. configurable: true
  20365. });
  20366. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20367. get: function () {
  20368. return this._lightsEnabled;
  20369. },
  20370. set: function (value) {
  20371. if (this._lightsEnabled === value) {
  20372. return;
  20373. }
  20374. this._lightsEnabled = value;
  20375. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20376. },
  20377. enumerable: true,
  20378. configurable: true
  20379. });
  20380. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20381. /** The default material used on meshes when no material is affected */
  20382. get: function () {
  20383. if (!this._defaultMaterial) {
  20384. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20385. }
  20386. return this._defaultMaterial;
  20387. },
  20388. /** The default material used on meshes when no material is affected */
  20389. set: function (value) {
  20390. this._defaultMaterial = value;
  20391. },
  20392. enumerable: true,
  20393. configurable: true
  20394. });
  20395. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20396. get: function () {
  20397. return this._texturesEnabled;
  20398. },
  20399. set: function (value) {
  20400. if (this._texturesEnabled === value) {
  20401. return;
  20402. }
  20403. this._texturesEnabled = value;
  20404. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20405. },
  20406. enumerable: true,
  20407. configurable: true
  20408. });
  20409. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20410. get: function () {
  20411. return this._skeletonsEnabled;
  20412. },
  20413. set: function (value) {
  20414. if (this._skeletonsEnabled === value) {
  20415. return;
  20416. }
  20417. this._skeletonsEnabled = value;
  20418. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20419. },
  20420. enumerable: true,
  20421. configurable: true
  20422. });
  20423. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  20424. get: function () {
  20425. if (!this._postProcessRenderPipelineManager) {
  20426. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20427. }
  20428. return this._postProcessRenderPipelineManager;
  20429. },
  20430. enumerable: true,
  20431. configurable: true
  20432. });
  20433. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  20434. get: function () {
  20435. if (!this._mainSoundTrack) {
  20436. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20437. }
  20438. return this._mainSoundTrack;
  20439. },
  20440. enumerable: true,
  20441. configurable: true
  20442. });
  20443. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  20444. get: function () {
  20445. return this._alternateRendering;
  20446. },
  20447. enumerable: true,
  20448. configurable: true
  20449. });
  20450. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20451. get: function () {
  20452. return this._frustumPlanes;
  20453. },
  20454. enumerable: true,
  20455. configurable: true
  20456. });
  20457. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  20458. /**
  20459. * Gets the current geometry buffer associated to the scene.
  20460. */
  20461. get: function () {
  20462. return this._geometryBufferRenderer;
  20463. },
  20464. /**
  20465. * Sets the current geometry buffer for the scene.
  20466. */
  20467. set: function (geometryBufferRenderer) {
  20468. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  20469. this._geometryBufferRenderer = geometryBufferRenderer;
  20470. }
  20471. },
  20472. enumerable: true,
  20473. configurable: true
  20474. });
  20475. Object.defineProperty(Scene.prototype, "debugLayer", {
  20476. // Properties
  20477. get: function () {
  20478. if (!this._debugLayer) {
  20479. this._debugLayer = new BABYLON.DebugLayer(this);
  20480. }
  20481. return this._debugLayer;
  20482. },
  20483. enumerable: true,
  20484. configurable: true
  20485. });
  20486. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20487. get: function () {
  20488. return this._workerCollisions;
  20489. },
  20490. set: function (enabled) {
  20491. if (!BABYLON.CollisionCoordinatorLegacy) {
  20492. return;
  20493. }
  20494. enabled = (enabled && !!Worker);
  20495. this._workerCollisions = enabled;
  20496. if (this.collisionCoordinator) {
  20497. this.collisionCoordinator.destroy();
  20498. }
  20499. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20500. this.collisionCoordinator.init(this);
  20501. },
  20502. enumerable: true,
  20503. configurable: true
  20504. });
  20505. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20506. get: function () {
  20507. return this._selectionOctree;
  20508. },
  20509. enumerable: true,
  20510. configurable: true
  20511. });
  20512. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20513. /**
  20514. * The mesh that is currently under the pointer.
  20515. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20516. */
  20517. get: function () {
  20518. return this._pointerOverMesh;
  20519. },
  20520. enumerable: true,
  20521. configurable: true
  20522. });
  20523. Object.defineProperty(Scene.prototype, "pointerX", {
  20524. /**
  20525. * Current on-screen X position of the pointer
  20526. * @return {number} X position of the pointer
  20527. */
  20528. get: function () {
  20529. return this._pointerX;
  20530. },
  20531. enumerable: true,
  20532. configurable: true
  20533. });
  20534. Object.defineProperty(Scene.prototype, "pointerY", {
  20535. /**
  20536. * Current on-screen Y position of the pointer
  20537. * @return {number} Y position of the pointer
  20538. */
  20539. get: function () {
  20540. return this._pointerY;
  20541. },
  20542. enumerable: true,
  20543. configurable: true
  20544. });
  20545. Scene.prototype.getCachedMaterial = function () {
  20546. return this._cachedMaterial;
  20547. };
  20548. Scene.prototype.getCachedEffect = function () {
  20549. return this._cachedEffect;
  20550. };
  20551. Scene.prototype.getCachedVisibility = function () {
  20552. return this._cachedVisibility;
  20553. };
  20554. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20555. if (visibility === void 0) { visibility = 1; }
  20556. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20557. };
  20558. Scene.prototype.getBoundingBoxRenderer = function () {
  20559. if (!this._boundingBoxRenderer) {
  20560. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20561. }
  20562. return this._boundingBoxRenderer;
  20563. };
  20564. Scene.prototype.getOutlineRenderer = function () {
  20565. return this._outlineRenderer;
  20566. };
  20567. Scene.prototype.getEngine = function () {
  20568. return this._engine;
  20569. };
  20570. Scene.prototype.getTotalVertices = function () {
  20571. return this._totalVertices.current;
  20572. };
  20573. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20574. get: function () {
  20575. return this._totalVertices;
  20576. },
  20577. enumerable: true,
  20578. configurable: true
  20579. });
  20580. Scene.prototype.getActiveIndices = function () {
  20581. return this._activeIndices.current;
  20582. };
  20583. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20584. get: function () {
  20585. return this._activeIndices;
  20586. },
  20587. enumerable: true,
  20588. configurable: true
  20589. });
  20590. Scene.prototype.getActiveParticles = function () {
  20591. return this._activeParticles.current;
  20592. };
  20593. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20594. get: function () {
  20595. return this._activeParticles;
  20596. },
  20597. enumerable: true,
  20598. configurable: true
  20599. });
  20600. Scene.prototype.getActiveBones = function () {
  20601. return this._activeBones.current;
  20602. };
  20603. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20604. get: function () {
  20605. return this._activeBones;
  20606. },
  20607. enumerable: true,
  20608. configurable: true
  20609. });
  20610. // Stats
  20611. Scene.prototype.getInterFramePerfCounter = function () {
  20612. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20613. return 0;
  20614. };
  20615. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20616. get: function () {
  20617. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20618. return null;
  20619. },
  20620. enumerable: true,
  20621. configurable: true
  20622. });
  20623. Scene.prototype.getLastFrameDuration = function () {
  20624. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20625. return 0;
  20626. };
  20627. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20628. get: function () {
  20629. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20630. return null;
  20631. },
  20632. enumerable: true,
  20633. configurable: true
  20634. });
  20635. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20636. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20637. return 0;
  20638. };
  20639. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20640. get: function () {
  20641. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20642. return null;
  20643. },
  20644. enumerable: true,
  20645. configurable: true
  20646. });
  20647. Scene.prototype.getActiveMeshes = function () {
  20648. return this._activeMeshes;
  20649. };
  20650. Scene.prototype.getRenderTargetsDuration = function () {
  20651. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20652. return 0;
  20653. };
  20654. Scene.prototype.getRenderDuration = function () {
  20655. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20656. return 0;
  20657. };
  20658. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20659. get: function () {
  20660. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20661. return null;
  20662. },
  20663. enumerable: true,
  20664. configurable: true
  20665. });
  20666. Scene.prototype.getParticlesDuration = function () {
  20667. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20668. return 0;
  20669. };
  20670. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20671. get: function () {
  20672. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20673. return null;
  20674. },
  20675. enumerable: true,
  20676. configurable: true
  20677. });
  20678. Scene.prototype.getSpritesDuration = function () {
  20679. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20680. return 0;
  20681. };
  20682. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20683. get: function () {
  20684. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20685. return null;
  20686. },
  20687. enumerable: true,
  20688. configurable: true
  20689. });
  20690. Scene.prototype.getAnimationRatio = function () {
  20691. return this._animationRatio;
  20692. };
  20693. Scene.prototype.getRenderId = function () {
  20694. return this._renderId;
  20695. };
  20696. Scene.prototype.incrementRenderId = function () {
  20697. this._renderId++;
  20698. };
  20699. Scene.prototype._updatePointerPosition = function (evt) {
  20700. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20701. if (!canvasRect) {
  20702. return;
  20703. }
  20704. this._pointerX = evt.clientX - canvasRect.left;
  20705. this._pointerY = evt.clientY - canvasRect.top;
  20706. this._unTranslatedPointerX = this._pointerX;
  20707. this._unTranslatedPointerY = this._pointerY;
  20708. };
  20709. Scene.prototype._createUbo = function () {
  20710. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20711. this._sceneUbo.addUniform("viewProjection", 16);
  20712. this._sceneUbo.addUniform("view", 16);
  20713. };
  20714. Scene.prototype._createAlternateUbo = function () {
  20715. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20716. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20717. this._alternateSceneUbo.addUniform("view", 16);
  20718. };
  20719. // Pointers handling
  20720. /**
  20721. * Use this method to simulate a pointer move on a mesh
  20722. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20723. */
  20724. Scene.prototype.simulatePointerMove = function (pickResult) {
  20725. var evt = new PointerEvent("pointermove");
  20726. return this._processPointerMove(pickResult, evt);
  20727. };
  20728. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20729. var canvas = this._engine.getRenderingCanvas();
  20730. if (!canvas) {
  20731. return this;
  20732. }
  20733. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20734. this.setPointerOverSprite(null);
  20735. this.setPointerOverMesh(pickResult.pickedMesh);
  20736. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20737. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20738. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20739. }
  20740. else {
  20741. canvas.style.cursor = this.hoverCursor;
  20742. }
  20743. }
  20744. else {
  20745. canvas.style.cursor = this.defaultCursor;
  20746. }
  20747. }
  20748. else {
  20749. this.setPointerOverMesh(null);
  20750. // Sprites
  20751. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20752. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20753. this.setPointerOverSprite(pickResult.pickedSprite);
  20754. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20755. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20756. }
  20757. else {
  20758. canvas.style.cursor = this.hoverCursor;
  20759. }
  20760. }
  20761. else {
  20762. this.setPointerOverSprite(null);
  20763. // Restore pointer
  20764. canvas.style.cursor = this.defaultCursor;
  20765. }
  20766. }
  20767. if (pickResult) {
  20768. if (this.onPointerMove) {
  20769. this.onPointerMove(evt, pickResult);
  20770. }
  20771. if (this.onPointerObservable.hasObservers()) {
  20772. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20773. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20774. this.onPointerObservable.notifyObservers(pi, type);
  20775. }
  20776. }
  20777. return this;
  20778. };
  20779. /**
  20780. * Use this method to simulate a pointer down on a mesh
  20781. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20782. */
  20783. Scene.prototype.simulatePointerDown = function (pickResult) {
  20784. var evt = new PointerEvent("pointerdown");
  20785. return this._processPointerDown(pickResult, evt);
  20786. };
  20787. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20788. var _this = this;
  20789. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20790. this._pickedDownMesh = pickResult.pickedMesh;
  20791. var actionManager = pickResult.pickedMesh.actionManager;
  20792. if (actionManager) {
  20793. if (actionManager.hasPickTriggers) {
  20794. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20795. switch (evt.button) {
  20796. case 0:
  20797. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20798. break;
  20799. case 1:
  20800. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20801. break;
  20802. case 2:
  20803. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20804. break;
  20805. }
  20806. }
  20807. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20808. window.setTimeout(function () {
  20809. 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);
  20810. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20811. if (_this._totalPointersPressed !== 0 &&
  20812. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20813. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20814. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20815. _this._startingPointerTime = 0;
  20816. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20817. }
  20818. }
  20819. }, Scene.LongPressDelay);
  20820. }
  20821. }
  20822. }
  20823. if (pickResult) {
  20824. if (this.onPointerDown) {
  20825. this.onPointerDown(evt, pickResult);
  20826. }
  20827. if (this.onPointerObservable.hasObservers()) {
  20828. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20829. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20830. this.onPointerObservable.notifyObservers(pi, type);
  20831. }
  20832. }
  20833. return this;
  20834. };
  20835. /**
  20836. * Use this method to simulate a pointer up on a mesh
  20837. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20838. */
  20839. Scene.prototype.simulatePointerUp = function (pickResult) {
  20840. var evt = new PointerEvent("pointerup");
  20841. var clickInfo = new ClickInfo();
  20842. clickInfo.singleClick = true;
  20843. clickInfo.ignore = true;
  20844. return this._processPointerUp(pickResult, evt, clickInfo);
  20845. };
  20846. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20847. if (pickResult && pickResult && pickResult.pickedMesh) {
  20848. this._pickedUpMesh = pickResult.pickedMesh;
  20849. if (this._pickedDownMesh === this._pickedUpMesh) {
  20850. if (this.onPointerPick) {
  20851. this.onPointerPick(evt, pickResult);
  20852. }
  20853. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20854. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20855. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20856. this.onPointerObservable.notifyObservers(pi, type);
  20857. }
  20858. }
  20859. if (pickResult.pickedMesh.actionManager) {
  20860. if (clickInfo.ignore) {
  20861. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20862. }
  20863. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20864. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20865. }
  20866. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20867. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20868. }
  20869. }
  20870. }
  20871. if (this._pickedDownMesh &&
  20872. this._pickedDownMesh.actionManager &&
  20873. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20874. this._pickedDownMesh !== this._pickedUpMesh) {
  20875. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20876. }
  20877. if (this.onPointerUp) {
  20878. this.onPointerUp(evt, pickResult);
  20879. }
  20880. if (this.onPointerObservable.hasObservers()) {
  20881. if (!clickInfo.ignore) {
  20882. if (!clickInfo.hasSwiped) {
  20883. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20884. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20885. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20886. this.onPointerObservable.notifyObservers(pi, type);
  20887. }
  20888. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20889. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20890. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20891. this.onPointerObservable.notifyObservers(pi, type);
  20892. }
  20893. }
  20894. }
  20895. else {
  20896. var type = BABYLON.PointerEventTypes.POINTERUP;
  20897. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20898. this.onPointerObservable.notifyObservers(pi, type);
  20899. }
  20900. }
  20901. return this;
  20902. };
  20903. /**
  20904. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20905. * @param attachUp defines if you want to attach events to pointerup
  20906. * @param attachDown defines if you want to attach events to pointerdown
  20907. * @param attachMove defines if you want to attach events to pointermove
  20908. */
  20909. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20910. var _this = this;
  20911. if (attachUp === void 0) { attachUp = true; }
  20912. if (attachDown === void 0) { attachDown = true; }
  20913. if (attachMove === void 0) { attachMove = true; }
  20914. this._initActionManager = function (act, clickInfo) {
  20915. if (!_this._meshPickProceed) {
  20916. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20917. _this._currentPickResult = pickResult;
  20918. if (pickResult) {
  20919. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20920. }
  20921. _this._meshPickProceed = true;
  20922. }
  20923. return act;
  20924. };
  20925. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20926. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20927. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20928. btn !== _this._previousButtonPressed) {
  20929. _this._doubleClickOccured = false;
  20930. clickInfo.singleClick = true;
  20931. clickInfo.ignore = false;
  20932. cb(clickInfo, _this._currentPickResult);
  20933. }
  20934. };
  20935. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20936. var clickInfo = new ClickInfo();
  20937. _this._currentPickResult = null;
  20938. var act = null;
  20939. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20940. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20941. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20942. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20943. act = _this._initActionManager(act, clickInfo);
  20944. if (act)
  20945. checkPicking = act.hasPickTriggers;
  20946. }
  20947. if (checkPicking) {
  20948. var btn = evt.button;
  20949. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20950. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20951. if (!clickInfo.hasSwiped) {
  20952. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20953. if (!checkSingleClickImmediately) {
  20954. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20955. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20956. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20957. act = _this._initActionManager(act, clickInfo);
  20958. if (act)
  20959. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20960. }
  20961. }
  20962. if (checkSingleClickImmediately) {
  20963. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20964. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20965. btn !== _this._previousButtonPressed) {
  20966. clickInfo.singleClick = true;
  20967. cb(clickInfo, _this._currentPickResult);
  20968. }
  20969. }
  20970. else {
  20971. // wait that no double click has been raised during the double click delay
  20972. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20973. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20974. }
  20975. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20976. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20977. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20978. act = _this._initActionManager(act, clickInfo);
  20979. if (act)
  20980. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20981. }
  20982. if (checkDoubleClick) {
  20983. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20984. if (btn === _this._previousButtonPressed &&
  20985. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20986. !_this._doubleClickOccured) {
  20987. // pointer has not moved for 2 clicks, it's a double click
  20988. if (!clickInfo.hasSwiped &&
  20989. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20990. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20991. _this._previousStartingPointerTime = 0;
  20992. _this._doubleClickOccured = true;
  20993. clickInfo.doubleClick = true;
  20994. clickInfo.ignore = false;
  20995. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20996. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20997. }
  20998. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20999. cb(clickInfo, _this._currentPickResult);
  21000. }
  21001. else {
  21002. _this._doubleClickOccured = false;
  21003. _this._previousStartingPointerTime = _this._startingPointerTime;
  21004. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21005. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21006. _this._previousButtonPressed = btn;
  21007. if (Scene.ExclusiveDoubleClickMode) {
  21008. if (_this._previousDelayedSimpleClickTimeout) {
  21009. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21010. }
  21011. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21012. cb(clickInfo, _this._previousPickResult);
  21013. }
  21014. else {
  21015. cb(clickInfo, _this._currentPickResult);
  21016. }
  21017. }
  21018. }
  21019. else {
  21020. _this._doubleClickOccured = false;
  21021. _this._previousStartingPointerTime = _this._startingPointerTime;
  21022. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21023. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21024. _this._previousButtonPressed = btn;
  21025. }
  21026. }
  21027. }
  21028. }
  21029. clickInfo.ignore = true;
  21030. cb(clickInfo, _this._currentPickResult);
  21031. };
  21032. this._spritePredicate = function (sprite) {
  21033. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21034. };
  21035. this._onPointerMove = function (evt) {
  21036. _this._updatePointerPosition(evt);
  21037. // PreObservable support
  21038. if (_this.onPrePointerObservable.hasObservers()) {
  21039. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21040. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21041. _this.onPrePointerObservable.notifyObservers(pi, type);
  21042. if (pi.skipOnPointerObservable) {
  21043. return;
  21044. }
  21045. }
  21046. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21047. return;
  21048. }
  21049. if (!_this.pointerMovePredicate) {
  21050. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21051. }
  21052. // Meshes
  21053. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21054. _this._processPointerMove(pickResult, evt);
  21055. };
  21056. this._onPointerDown = function (evt) {
  21057. _this._totalPointersPressed++;
  21058. _this._pickedDownMesh = null;
  21059. _this._meshPickProceed = false;
  21060. _this._updatePointerPosition(evt);
  21061. if (_this.preventDefaultOnPointerDown && canvas) {
  21062. evt.preventDefault();
  21063. canvas.focus();
  21064. }
  21065. // PreObservable support
  21066. if (_this.onPrePointerObservable.hasObservers()) {
  21067. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21068. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21069. _this.onPrePointerObservable.notifyObservers(pi, type);
  21070. if (pi.skipOnPointerObservable) {
  21071. return;
  21072. }
  21073. }
  21074. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21075. return;
  21076. }
  21077. _this._startingPointerPosition.x = _this._pointerX;
  21078. _this._startingPointerPosition.y = _this._pointerY;
  21079. _this._startingPointerTime = new Date().getTime();
  21080. if (!_this.pointerDownPredicate) {
  21081. _this.pointerDownPredicate = function (mesh) {
  21082. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21083. };
  21084. }
  21085. // Meshes
  21086. _this._pickedDownMesh = null;
  21087. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21088. _this._processPointerDown(pickResult, evt);
  21089. // Sprites
  21090. _this._pickedDownSprite = null;
  21091. if (_this.spriteManagers.length > 0) {
  21092. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21093. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21094. if (pickResult.pickedSprite.actionManager) {
  21095. _this._pickedDownSprite = pickResult.pickedSprite;
  21096. switch (evt.button) {
  21097. case 0:
  21098. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21099. break;
  21100. case 1:
  21101. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21102. break;
  21103. case 2:
  21104. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21105. break;
  21106. }
  21107. if (pickResult.pickedSprite.actionManager) {
  21108. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21109. }
  21110. }
  21111. }
  21112. }
  21113. };
  21114. this._onPointerUp = function (evt) {
  21115. if (_this._totalPointersPressed === 0) {
  21116. return; // So we need to test it the pointer down was pressed before.
  21117. }
  21118. _this._totalPointersPressed--;
  21119. _this._pickedUpMesh = null;
  21120. _this._meshPickProceed = false;
  21121. _this._updatePointerPosition(evt);
  21122. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  21123. // PreObservable support
  21124. if (_this.onPrePointerObservable.hasObservers()) {
  21125. if (!clickInfo.ignore) {
  21126. if (!clickInfo.hasSwiped) {
  21127. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21128. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21129. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21130. _this.onPrePointerObservable.notifyObservers(pi, type);
  21131. if (pi.skipOnPointerObservable) {
  21132. return;
  21133. }
  21134. }
  21135. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21136. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21137. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21138. _this.onPrePointerObservable.notifyObservers(pi, type);
  21139. if (pi.skipOnPointerObservable) {
  21140. return;
  21141. }
  21142. }
  21143. }
  21144. }
  21145. else {
  21146. var type = BABYLON.PointerEventTypes.POINTERUP;
  21147. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21148. _this.onPrePointerObservable.notifyObservers(pi, type);
  21149. if (pi.skipOnPointerObservable) {
  21150. return;
  21151. }
  21152. }
  21153. }
  21154. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21155. return;
  21156. }
  21157. if (!_this.pointerUpPredicate) {
  21158. _this.pointerUpPredicate = function (mesh) {
  21159. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21160. };
  21161. }
  21162. // Meshes
  21163. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  21164. _this._initActionManager(null, clickInfo);
  21165. }
  21166. if (!pickResult) {
  21167. pickResult = _this._currentPickResult;
  21168. }
  21169. _this._processPointerUp(pickResult, evt, clickInfo);
  21170. // Sprites
  21171. if (_this.spriteManagers.length > 0) {
  21172. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21173. if (spritePickResult) {
  21174. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  21175. if (spritePickResult.pickedSprite.actionManager) {
  21176. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21177. if (spritePickResult.pickedSprite.actionManager) {
  21178. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  21179. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  21180. }
  21181. }
  21182. }
  21183. }
  21184. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  21185. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  21186. }
  21187. }
  21188. }
  21189. _this._previousPickResult = _this._currentPickResult;
  21190. });
  21191. };
  21192. this._onKeyDown = function (evt) {
  21193. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  21194. if (_this.onPreKeyboardObservable.hasObservers()) {
  21195. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21196. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21197. if (pi.skipOnPointerObservable) {
  21198. return;
  21199. }
  21200. }
  21201. if (_this.onKeyboardObservable.hasObservers()) {
  21202. var pi = new BABYLON.KeyboardInfo(type, evt);
  21203. _this.onKeyboardObservable.notifyObservers(pi, type);
  21204. }
  21205. if (_this.actionManager) {
  21206. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21207. }
  21208. };
  21209. this._onKeyUp = function (evt) {
  21210. var type = BABYLON.KeyboardEventTypes.KEYUP;
  21211. if (_this.onPreKeyboardObservable.hasObservers()) {
  21212. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  21213. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  21214. if (pi.skipOnPointerObservable) {
  21215. return;
  21216. }
  21217. }
  21218. if (_this.onKeyboardObservable.hasObservers()) {
  21219. var pi = new BABYLON.KeyboardInfo(type, evt);
  21220. _this.onKeyboardObservable.notifyObservers(pi, type);
  21221. }
  21222. if (_this.actionManager) {
  21223. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21224. }
  21225. };
  21226. var engine = this.getEngine();
  21227. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  21228. if (!canvas) {
  21229. return;
  21230. }
  21231. canvas.addEventListener("keydown", _this._onKeyDown, false);
  21232. canvas.addEventListener("keyup", _this._onKeyUp, false);
  21233. });
  21234. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  21235. if (!canvas) {
  21236. return;
  21237. }
  21238. canvas.removeEventListener("keydown", _this._onKeyDown);
  21239. canvas.removeEventListener("keyup", _this._onKeyUp);
  21240. });
  21241. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21242. var canvas = this._engine.getRenderingCanvas();
  21243. if (!canvas) {
  21244. return;
  21245. }
  21246. if (attachMove) {
  21247. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  21248. // Wheel
  21249. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  21250. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  21251. }
  21252. if (attachDown) {
  21253. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  21254. }
  21255. if (attachUp) {
  21256. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  21257. }
  21258. canvas.tabIndex = 1;
  21259. };
  21260. Scene.prototype.detachControl = function () {
  21261. var engine = this.getEngine();
  21262. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21263. var canvas = engine.getRenderingCanvas();
  21264. if (!canvas) {
  21265. return;
  21266. }
  21267. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  21268. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  21269. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  21270. if (this._onCanvasBlurObserver) {
  21271. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  21272. }
  21273. if (this._onCanvasFocusObserver) {
  21274. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  21275. }
  21276. // Wheel
  21277. canvas.removeEventListener('mousewheel', this._onPointerMove);
  21278. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  21279. // Keyboard
  21280. canvas.removeEventListener("keydown", this._onKeyDown);
  21281. canvas.removeEventListener("keyup", this._onKeyUp);
  21282. // Observables
  21283. this.onKeyboardObservable.clear();
  21284. this.onPreKeyboardObservable.clear();
  21285. this.onPointerObservable.clear();
  21286. this.onPrePointerObservable.clear();
  21287. };
  21288. /**
  21289. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  21290. * Delay loaded resources are not taking in account
  21291. * @return true if all required resources are ready
  21292. */
  21293. Scene.prototype.isReady = function () {
  21294. if (this._isDisposed) {
  21295. return false;
  21296. }
  21297. if (this._pendingData.length > 0) {
  21298. return false;
  21299. }
  21300. var index;
  21301. var engine = this.getEngine();
  21302. // Geometries
  21303. for (index = 0; index < this._geometries.length; index++) {
  21304. var geometry = this._geometries[index];
  21305. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21306. return false;
  21307. }
  21308. }
  21309. // Meshes
  21310. for (index = 0; index < this.meshes.length; index++) {
  21311. var mesh = this.meshes[index];
  21312. if (!mesh.isEnabled()) {
  21313. continue;
  21314. }
  21315. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  21316. continue;
  21317. }
  21318. if (!mesh.isReady()) {
  21319. return false;
  21320. }
  21321. // Highlight layers
  21322. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  21323. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  21324. var layer = _a[_i];
  21325. if (!layer.hasMesh(mesh)) {
  21326. continue;
  21327. }
  21328. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  21329. var subMesh = _c[_b];
  21330. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  21331. return false;
  21332. }
  21333. }
  21334. }
  21335. }
  21336. return true;
  21337. };
  21338. Scene.prototype.resetCachedMaterial = function () {
  21339. this._cachedMaterial = null;
  21340. this._cachedEffect = null;
  21341. this._cachedVisibility = null;
  21342. };
  21343. Scene.prototype.registerBeforeRender = function (func) {
  21344. this.onBeforeRenderObservable.add(func);
  21345. };
  21346. Scene.prototype.unregisterBeforeRender = function (func) {
  21347. this.onBeforeRenderObservable.removeCallback(func);
  21348. };
  21349. Scene.prototype.registerAfterRender = function (func) {
  21350. this.onAfterRenderObservable.add(func);
  21351. };
  21352. Scene.prototype.unregisterAfterRender = function (func) {
  21353. this.onAfterRenderObservable.removeCallback(func);
  21354. };
  21355. Scene.prototype._executeOnceBeforeRender = function (func) {
  21356. var _this = this;
  21357. var execFunc = function () {
  21358. func();
  21359. setTimeout(function () {
  21360. _this.unregisterBeforeRender(execFunc);
  21361. });
  21362. };
  21363. this.registerBeforeRender(execFunc);
  21364. };
  21365. /**
  21366. * The provided function will run before render once and will be disposed afterwards.
  21367. * A timeout delay can be provided so that the function will be executed in N ms.
  21368. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  21369. * @param func The function to be executed.
  21370. * @param timeout optional delay in ms
  21371. */
  21372. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  21373. var _this = this;
  21374. if (timeout !== undefined) {
  21375. setTimeout(function () {
  21376. _this._executeOnceBeforeRender(func);
  21377. }, timeout);
  21378. }
  21379. else {
  21380. this._executeOnceBeforeRender(func);
  21381. }
  21382. };
  21383. Scene.prototype._addPendingData = function (data) {
  21384. this._pendingData.push(data);
  21385. };
  21386. Scene.prototype._removePendingData = function (data) {
  21387. var wasLoading = this.isLoading;
  21388. var index = this._pendingData.indexOf(data);
  21389. if (index !== -1) {
  21390. this._pendingData.splice(index, 1);
  21391. }
  21392. if (wasLoading && !this.isLoading) {
  21393. this.onDataLoadedObservable.notifyObservers(this);
  21394. }
  21395. };
  21396. Scene.prototype.getWaitingItemsCount = function () {
  21397. return this._pendingData.length;
  21398. };
  21399. Object.defineProperty(Scene.prototype, "isLoading", {
  21400. get: function () {
  21401. return this._pendingData.length > 0;
  21402. },
  21403. enumerable: true,
  21404. configurable: true
  21405. });
  21406. /**
  21407. * Registers a function to be executed when the scene is ready.
  21408. * @param {Function} func - the function to be executed.
  21409. */
  21410. Scene.prototype.executeWhenReady = function (func) {
  21411. var _this = this;
  21412. this.onReadyObservable.add(func);
  21413. if (this._executeWhenReadyTimeoutId !== -1) {
  21414. return;
  21415. }
  21416. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21417. _this._checkIsReady();
  21418. }, 150);
  21419. };
  21420. Scene.prototype._checkIsReady = function () {
  21421. var _this = this;
  21422. if (this.isReady()) {
  21423. this.onReadyObservable.notifyObservers(this);
  21424. this.onReadyObservable.clear();
  21425. this._executeWhenReadyTimeoutId = -1;
  21426. return;
  21427. }
  21428. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21429. _this._checkIsReady();
  21430. }, 150);
  21431. };
  21432. // Animations
  21433. /**
  21434. * Will start the animation sequence of a given target
  21435. * @param target - the target
  21436. * @param {number} from - from which frame should animation start
  21437. * @param {number} to - till which frame should animation run.
  21438. * @param {boolean} [loop] - should the animation loop
  21439. * @param {number} [speedRatio] - the speed in which to run the animation
  21440. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21441. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21442. * Returns {BABYLON.Animatable} the animatable object created for this animation
  21443. * See BABYLON.Animatable
  21444. */
  21445. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21446. if (speedRatio === void 0) { speedRatio = 1.0; }
  21447. if (from > to && speedRatio > 0) {
  21448. speedRatio *= -1;
  21449. }
  21450. this.stopAnimation(target);
  21451. if (!animatable) {
  21452. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21453. }
  21454. // Local animations
  21455. if (target.animations) {
  21456. animatable.appendAnimations(target, target.animations);
  21457. }
  21458. // Children animations
  21459. if (target.getAnimatables) {
  21460. var animatables = target.getAnimatables();
  21461. for (var index = 0; index < animatables.length; index++) {
  21462. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21463. }
  21464. }
  21465. animatable.reset();
  21466. return animatable;
  21467. };
  21468. /**
  21469. * Begin a new animation on a given node
  21470. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21471. * @param {BABYLON.Animation[]} defines the list of animations to start
  21472. * @param {number} from defines the initial value
  21473. * @param {number} to defines the final value
  21474. * @param {boolean} loop defines if you want animation to loop (off by default)
  21475. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21476. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21477. * @returns the list of created animatables
  21478. */
  21479. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21480. if (speedRatio === undefined) {
  21481. speedRatio = 1.0;
  21482. }
  21483. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21484. return animatable;
  21485. };
  21486. /**
  21487. * Begin a new animation on a given node and its hierarchy
  21488. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21489. * @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.
  21490. * @param {BABYLON.Animation[]} defines the list of animations to start
  21491. * @param {number} from defines the initial value
  21492. * @param {number} to defines the final value
  21493. * @param {boolean} loop defines if you want animation to loop (off by default)
  21494. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21495. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21496. * @returns the list of animatables created for all nodes
  21497. */
  21498. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21499. var children = target.getDescendants(directDescendantsOnly);
  21500. var result = [];
  21501. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  21502. var child = children_1[_i];
  21503. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  21504. }
  21505. return result;
  21506. };
  21507. Scene.prototype.getAnimatableByTarget = function (target) {
  21508. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21509. if (this._activeAnimatables[index].target === target) {
  21510. return this._activeAnimatables[index];
  21511. }
  21512. }
  21513. return null;
  21514. };
  21515. Object.defineProperty(Scene.prototype, "animatables", {
  21516. get: function () {
  21517. return this._activeAnimatables;
  21518. },
  21519. enumerable: true,
  21520. configurable: true
  21521. });
  21522. /**
  21523. * Will stop the animation of the given target
  21524. * @param target - the target
  21525. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21526. * @see beginAnimation
  21527. */
  21528. Scene.prototype.stopAnimation = function (target, animationName) {
  21529. var animatable = this.getAnimatableByTarget(target);
  21530. if (animatable) {
  21531. animatable.stop(animationName);
  21532. }
  21533. };
  21534. /**
  21535. * Stops and removes all animations that have been applied to the scene
  21536. */
  21537. Scene.prototype.stopAllAnimations = function () {
  21538. if (this._activeAnimatables) {
  21539. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21540. this._activeAnimatables[i].stop();
  21541. }
  21542. this._activeAnimatables = [];
  21543. }
  21544. };
  21545. Scene.prototype._animate = function () {
  21546. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21547. return;
  21548. }
  21549. // Getting time
  21550. var now = BABYLON.Tools.Now;
  21551. if (!this._animationTimeLast) {
  21552. if (this._pendingData.length > 0) {
  21553. return;
  21554. }
  21555. this._animationTimeLast = now;
  21556. }
  21557. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21558. this._animationTime += deltaTime;
  21559. this._animationTimeLast = now;
  21560. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21561. this._activeAnimatables[index]._animate(this._animationTime);
  21562. }
  21563. };
  21564. // Matrix
  21565. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21566. this._useAlternateCameraConfiguration = active;
  21567. };
  21568. Scene.prototype.getViewMatrix = function () {
  21569. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21570. };
  21571. Scene.prototype.getProjectionMatrix = function () {
  21572. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21573. };
  21574. Scene.prototype.getTransformMatrix = function () {
  21575. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21576. };
  21577. Scene.prototype.setTransformMatrix = function (view, projection) {
  21578. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21579. return;
  21580. }
  21581. this._viewUpdateFlag = view.updateFlag;
  21582. this._projectionUpdateFlag = projection.updateFlag;
  21583. this._viewMatrix = view;
  21584. this._projectionMatrix = projection;
  21585. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21586. // Update frustum
  21587. if (!this._frustumPlanes) {
  21588. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21589. }
  21590. else {
  21591. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21592. }
  21593. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21594. var otherCamera = this.activeCamera._alternateCamera;
  21595. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21596. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21597. }
  21598. if (this._sceneUbo.useUbo) {
  21599. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21600. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21601. this._sceneUbo.update();
  21602. }
  21603. };
  21604. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21605. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21606. return;
  21607. }
  21608. this._alternateViewUpdateFlag = view.updateFlag;
  21609. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21610. this._alternateViewMatrix = view;
  21611. this._alternateProjectionMatrix = projection;
  21612. if (!this._alternateTransformMatrix) {
  21613. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21614. }
  21615. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21616. if (!this._alternateSceneUbo) {
  21617. this._createAlternateUbo();
  21618. }
  21619. if (this._alternateSceneUbo.useUbo) {
  21620. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21621. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21622. this._alternateSceneUbo.update();
  21623. }
  21624. };
  21625. Scene.prototype.getSceneUniformBuffer = function () {
  21626. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21627. };
  21628. // Methods
  21629. Scene.prototype.getUniqueId = function () {
  21630. var result = Scene._uniqueIdCounter;
  21631. Scene._uniqueIdCounter++;
  21632. return result;
  21633. };
  21634. Scene.prototype.addMesh = function (newMesh) {
  21635. this.meshes.push(newMesh);
  21636. //notify the collision coordinator
  21637. if (this.collisionCoordinator) {
  21638. this.collisionCoordinator.onMeshAdded(newMesh);
  21639. }
  21640. newMesh._resyncLightSources();
  21641. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21642. };
  21643. Scene.prototype.removeMesh = function (toRemove) {
  21644. var index = this.meshes.indexOf(toRemove);
  21645. if (index !== -1) {
  21646. // Remove from the scene if mesh found
  21647. this.meshes.splice(index, 1);
  21648. }
  21649. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21650. return index;
  21651. };
  21652. Scene.prototype.addTransformNode = function (newTransformNode) {
  21653. this.transformNodes.push(newTransformNode);
  21654. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21655. };
  21656. Scene.prototype.removeTransformNode = function (toRemove) {
  21657. var index = this.transformNodes.indexOf(toRemove);
  21658. if (index !== -1) {
  21659. // Remove from the scene if found
  21660. this.transformNodes.splice(index, 1);
  21661. }
  21662. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21663. return index;
  21664. };
  21665. Scene.prototype.removeSkeleton = function (toRemove) {
  21666. var index = this.skeletons.indexOf(toRemove);
  21667. if (index !== -1) {
  21668. // Remove from the scene if found
  21669. this.skeletons.splice(index, 1);
  21670. }
  21671. return index;
  21672. };
  21673. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21674. var index = this.morphTargetManagers.indexOf(toRemove);
  21675. if (index !== -1) {
  21676. // Remove from the scene if found
  21677. this.morphTargetManagers.splice(index, 1);
  21678. }
  21679. return index;
  21680. };
  21681. Scene.prototype.removeLight = function (toRemove) {
  21682. var index = this.lights.indexOf(toRemove);
  21683. if (index !== -1) {
  21684. // Remove from meshes
  21685. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21686. var mesh = _a[_i];
  21687. mesh._removeLightSource(toRemove);
  21688. }
  21689. // Remove from the scene if mesh found
  21690. this.lights.splice(index, 1);
  21691. this.sortLightsByPriority();
  21692. }
  21693. this.onLightRemovedObservable.notifyObservers(toRemove);
  21694. return index;
  21695. };
  21696. Scene.prototype.removeCamera = function (toRemove) {
  21697. var index = this.cameras.indexOf(toRemove);
  21698. if (index !== -1) {
  21699. // Remove from the scene if mesh found
  21700. this.cameras.splice(index, 1);
  21701. }
  21702. // Remove from activeCameras
  21703. var index2 = this.activeCameras.indexOf(toRemove);
  21704. if (index2 !== -1) {
  21705. // Remove from the scene if mesh found
  21706. this.activeCameras.splice(index2, 1);
  21707. }
  21708. // Reset the activeCamera
  21709. if (this.activeCamera === toRemove) {
  21710. if (this.cameras.length > 0) {
  21711. this.activeCamera = this.cameras[0];
  21712. }
  21713. else {
  21714. this.activeCamera = null;
  21715. }
  21716. }
  21717. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21718. return index;
  21719. };
  21720. Scene.prototype.removeParticleSystem = function (toRemove) {
  21721. var index = this.particleSystems.indexOf(toRemove);
  21722. if (index !== -1) {
  21723. this.particleSystems.splice(index, 1);
  21724. }
  21725. return index;
  21726. };
  21727. ;
  21728. Scene.prototype.removeAnimation = function (toRemove) {
  21729. var index = this.animations.indexOf(toRemove);
  21730. if (index !== -1) {
  21731. this.animations.splice(index, 1);
  21732. }
  21733. return index;
  21734. };
  21735. ;
  21736. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21737. var index = this.multiMaterials.indexOf(toRemove);
  21738. if (index !== -1) {
  21739. this.multiMaterials.splice(index, 1);
  21740. }
  21741. return index;
  21742. };
  21743. ;
  21744. Scene.prototype.removeMaterial = function (toRemove) {
  21745. var index = this.materials.indexOf(toRemove);
  21746. if (index !== -1) {
  21747. this.materials.splice(index, 1);
  21748. }
  21749. return index;
  21750. };
  21751. ;
  21752. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21753. var index = this.lensFlareSystems.indexOf(toRemove);
  21754. if (index !== -1) {
  21755. this.lensFlareSystems.splice(index, 1);
  21756. }
  21757. return index;
  21758. };
  21759. ;
  21760. Scene.prototype.removeActionManager = function (toRemove) {
  21761. var index = this._actionManagers.indexOf(toRemove);
  21762. if (index !== -1) {
  21763. this._actionManagers.splice(index, 1);
  21764. }
  21765. return index;
  21766. };
  21767. ;
  21768. Scene.prototype.addLight = function (newLight) {
  21769. this.lights.push(newLight);
  21770. this.sortLightsByPriority();
  21771. // Add light to all meshes (To support if the light is removed and then readded)
  21772. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21773. var mesh = _a[_i];
  21774. if (mesh._lightSources.indexOf(newLight) === -1) {
  21775. mesh._lightSources.push(newLight);
  21776. mesh._resyncLightSources();
  21777. }
  21778. }
  21779. this.onNewLightAddedObservable.notifyObservers(newLight);
  21780. };
  21781. Scene.prototype.sortLightsByPriority = function () {
  21782. if (this.requireLightSorting) {
  21783. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21784. }
  21785. };
  21786. Scene.prototype.addCamera = function (newCamera) {
  21787. this.cameras.push(newCamera);
  21788. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21789. };
  21790. Scene.prototype.addSkeleton = function (newSkeleton) {
  21791. this.skeletons.push(newSkeleton);
  21792. };
  21793. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21794. this.particleSystems.push(newParticleSystem);
  21795. };
  21796. Scene.prototype.addAnimation = function (newAnimation) {
  21797. this.animations.push(newAnimation);
  21798. };
  21799. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21800. this.multiMaterials.push(newMultiMaterial);
  21801. };
  21802. Scene.prototype.addMaterial = function (newMaterial) {
  21803. this.materials.push(newMaterial);
  21804. };
  21805. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21806. this.morphTargetManagers.push(newMorphTargetManager);
  21807. };
  21808. Scene.prototype.addGeometry = function (newGeometrie) {
  21809. this._geometries.push(newGeometrie);
  21810. };
  21811. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21812. this.lensFlareSystems.push(newLensFlareSystem);
  21813. };
  21814. Scene.prototype.addActionManager = function (newActionManager) {
  21815. this._actionManagers.push(newActionManager);
  21816. };
  21817. /**
  21818. * Switch active camera
  21819. * @param {Camera} newCamera - new active camera
  21820. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21821. */
  21822. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21823. if (attachControl === void 0) { attachControl = true; }
  21824. var canvas = this._engine.getRenderingCanvas();
  21825. if (!canvas) {
  21826. return;
  21827. }
  21828. if (this.activeCamera) {
  21829. this.activeCamera.detachControl(canvas);
  21830. }
  21831. this.activeCamera = newCamera;
  21832. if (attachControl) {
  21833. newCamera.attachControl(canvas);
  21834. }
  21835. };
  21836. /**
  21837. * sets the active camera of the scene using its ID
  21838. * @param {string} id - the camera's ID
  21839. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21840. * @see activeCamera
  21841. */
  21842. Scene.prototype.setActiveCameraByID = function (id) {
  21843. var camera = this.getCameraByID(id);
  21844. if (camera) {
  21845. this.activeCamera = camera;
  21846. return camera;
  21847. }
  21848. return null;
  21849. };
  21850. /**
  21851. * sets the active camera of the scene using its name
  21852. * @param {string} name - the camera's name
  21853. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21854. * @see activeCamera
  21855. */
  21856. Scene.prototype.setActiveCameraByName = function (name) {
  21857. var camera = this.getCameraByName(name);
  21858. if (camera) {
  21859. this.activeCamera = camera;
  21860. return camera;
  21861. }
  21862. return null;
  21863. };
  21864. /**
  21865. * get an animation group using its name
  21866. * @param {string} the material's name
  21867. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21868. */
  21869. Scene.prototype.getAnimationGroupByName = function (name) {
  21870. for (var index = 0; index < this.animationGroups.length; index++) {
  21871. if (this.animationGroups[index].name === name) {
  21872. return this.animationGroups[index];
  21873. }
  21874. }
  21875. return null;
  21876. };
  21877. /**
  21878. * get a material using its id
  21879. * @param {string} the material's ID
  21880. * @return {BABYLON.Material|null} the material or null if none found.
  21881. */
  21882. Scene.prototype.getMaterialByID = function (id) {
  21883. for (var index = 0; index < this.materials.length; index++) {
  21884. if (this.materials[index].id === id) {
  21885. return this.materials[index];
  21886. }
  21887. }
  21888. return null;
  21889. };
  21890. /**
  21891. * get a material using its name
  21892. * @param {string} the material's name
  21893. * @return {BABYLON.Material|null} the material or null if none found.
  21894. */
  21895. Scene.prototype.getMaterialByName = function (name) {
  21896. for (var index = 0; index < this.materials.length; index++) {
  21897. if (this.materials[index].name === name) {
  21898. return this.materials[index];
  21899. }
  21900. }
  21901. return null;
  21902. };
  21903. Scene.prototype.getLensFlareSystemByName = function (name) {
  21904. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21905. if (this.lensFlareSystems[index].name === name) {
  21906. return this.lensFlareSystems[index];
  21907. }
  21908. }
  21909. return null;
  21910. };
  21911. Scene.prototype.getLensFlareSystemByID = function (id) {
  21912. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21913. if (this.lensFlareSystems[index].id === id) {
  21914. return this.lensFlareSystems[index];
  21915. }
  21916. }
  21917. return null;
  21918. };
  21919. Scene.prototype.getCameraByID = function (id) {
  21920. for (var index = 0; index < this.cameras.length; index++) {
  21921. if (this.cameras[index].id === id) {
  21922. return this.cameras[index];
  21923. }
  21924. }
  21925. return null;
  21926. };
  21927. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21928. for (var index = 0; index < this.cameras.length; index++) {
  21929. if (this.cameras[index].uniqueId === uniqueId) {
  21930. return this.cameras[index];
  21931. }
  21932. }
  21933. return null;
  21934. };
  21935. /**
  21936. * get a camera using its name
  21937. * @param {string} the camera's name
  21938. * @return {BABYLON.Camera|null} the camera or null if none found.
  21939. */
  21940. Scene.prototype.getCameraByName = function (name) {
  21941. for (var index = 0; index < this.cameras.length; index++) {
  21942. if (this.cameras[index].name === name) {
  21943. return this.cameras[index];
  21944. }
  21945. }
  21946. return null;
  21947. };
  21948. /**
  21949. * get a bone using its id
  21950. * @param {string} the bone's id
  21951. * @return {BABYLON.Bone|null} the bone or null if not found
  21952. */
  21953. Scene.prototype.getBoneByID = function (id) {
  21954. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21955. var skeleton = this.skeletons[skeletonIndex];
  21956. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21957. if (skeleton.bones[boneIndex].id === id) {
  21958. return skeleton.bones[boneIndex];
  21959. }
  21960. }
  21961. }
  21962. return null;
  21963. };
  21964. /**
  21965. * get a bone using its id
  21966. * @param {string} the bone's name
  21967. * @return {BABYLON.Bone|null} the bone or null if not found
  21968. */
  21969. Scene.prototype.getBoneByName = function (name) {
  21970. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21971. var skeleton = this.skeletons[skeletonIndex];
  21972. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21973. if (skeleton.bones[boneIndex].name === name) {
  21974. return skeleton.bones[boneIndex];
  21975. }
  21976. }
  21977. }
  21978. return null;
  21979. };
  21980. /**
  21981. * get a light node using its name
  21982. * @param {string} the light's name
  21983. * @return {BABYLON.Light|null} the light or null if none found.
  21984. */
  21985. Scene.prototype.getLightByName = function (name) {
  21986. for (var index = 0; index < this.lights.length; index++) {
  21987. if (this.lights[index].name === name) {
  21988. return this.lights[index];
  21989. }
  21990. }
  21991. return null;
  21992. };
  21993. /**
  21994. * get a light node using its ID
  21995. * @param {string} the light's id
  21996. * @return {BABYLON.Light|null} the light or null if none found.
  21997. */
  21998. Scene.prototype.getLightByID = function (id) {
  21999. for (var index = 0; index < this.lights.length; index++) {
  22000. if (this.lights[index].id === id) {
  22001. return this.lights[index];
  22002. }
  22003. }
  22004. return null;
  22005. };
  22006. /**
  22007. * get a light node using its scene-generated unique ID
  22008. * @param {number} the light's unique id
  22009. * @return {BABYLON.Light|null} the light or null if none found.
  22010. */
  22011. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  22012. for (var index = 0; index < this.lights.length; index++) {
  22013. if (this.lights[index].uniqueId === uniqueId) {
  22014. return this.lights[index];
  22015. }
  22016. }
  22017. return null;
  22018. };
  22019. /**
  22020. * get a particle system by id
  22021. * @param id {number} the particle system id
  22022. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  22023. */
  22024. Scene.prototype.getParticleSystemByID = function (id) {
  22025. for (var index = 0; index < this.particleSystems.length; index++) {
  22026. if (this.particleSystems[index].id === id) {
  22027. return this.particleSystems[index];
  22028. }
  22029. }
  22030. return null;
  22031. };
  22032. /**
  22033. * get a geometry using its ID
  22034. * @param {string} the geometry's id
  22035. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22036. */
  22037. Scene.prototype.getGeometryByID = function (id) {
  22038. for (var index = 0; index < this._geometries.length; index++) {
  22039. if (this._geometries[index].id === id) {
  22040. return this._geometries[index];
  22041. }
  22042. }
  22043. return null;
  22044. };
  22045. /**
  22046. * add a new geometry to this scene.
  22047. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22048. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22049. * @return {boolean} was the geometry added or not
  22050. */
  22051. Scene.prototype.pushGeometry = function (geometry, force) {
  22052. if (!force && this.getGeometryByID(geometry.id)) {
  22053. return false;
  22054. }
  22055. this._geometries.push(geometry);
  22056. //notify the collision coordinator
  22057. if (this.collisionCoordinator) {
  22058. this.collisionCoordinator.onGeometryAdded(geometry);
  22059. }
  22060. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22061. return true;
  22062. };
  22063. /**
  22064. * Removes an existing geometry
  22065. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22066. * @return {boolean} was the geometry removed or not
  22067. */
  22068. Scene.prototype.removeGeometry = function (geometry) {
  22069. var index = this._geometries.indexOf(geometry);
  22070. if (index > -1) {
  22071. this._geometries.splice(index, 1);
  22072. //notify the collision coordinator
  22073. if (this.collisionCoordinator) {
  22074. this.collisionCoordinator.onGeometryDeleted(geometry);
  22075. }
  22076. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22077. return true;
  22078. }
  22079. return false;
  22080. };
  22081. Scene.prototype.getGeometries = function () {
  22082. return this._geometries;
  22083. };
  22084. /**
  22085. * Get the first added mesh found of a given ID
  22086. * @param {string} id - the id to search for
  22087. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22088. */
  22089. Scene.prototype.getMeshByID = function (id) {
  22090. for (var index = 0; index < this.meshes.length; index++) {
  22091. if (this.meshes[index].id === id) {
  22092. return this.meshes[index];
  22093. }
  22094. }
  22095. return null;
  22096. };
  22097. Scene.prototype.getMeshesByID = function (id) {
  22098. return this.meshes.filter(function (m) {
  22099. return m.id === id;
  22100. });
  22101. };
  22102. /**
  22103. * Get the first added transform node found of a given ID
  22104. * @param {string} id - the id to search for
  22105. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  22106. */
  22107. Scene.prototype.getTransformNodeByID = function (id) {
  22108. for (var index = 0; index < this.transformNodes.length; index++) {
  22109. if (this.transformNodes[index].id === id) {
  22110. return this.transformNodes[index];
  22111. }
  22112. }
  22113. return null;
  22114. };
  22115. Scene.prototype.getTransformNodesByID = function (id) {
  22116. return this.transformNodes.filter(function (m) {
  22117. return m.id === id;
  22118. });
  22119. };
  22120. /**
  22121. * Get a mesh with its auto-generated unique id
  22122. * @param {number} uniqueId - the unique id to search for
  22123. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22124. */
  22125. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  22126. for (var index = 0; index < this.meshes.length; index++) {
  22127. if (this.meshes[index].uniqueId === uniqueId) {
  22128. return this.meshes[index];
  22129. }
  22130. }
  22131. return null;
  22132. };
  22133. /**
  22134. * Get a the last added mesh found of a given ID
  22135. * @param {string} id - the id to search for
  22136. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22137. */
  22138. Scene.prototype.getLastMeshByID = function (id) {
  22139. for (var index = this.meshes.length - 1; index >= 0; index--) {
  22140. if (this.meshes[index].id === id) {
  22141. return this.meshes[index];
  22142. }
  22143. }
  22144. return null;
  22145. };
  22146. /**
  22147. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  22148. * @param {string} id - the id to search for
  22149. * @return {BABYLON.Node|null} the node found or null if not found at all.
  22150. */
  22151. Scene.prototype.getLastEntryByID = function (id) {
  22152. var index;
  22153. for (index = this.meshes.length - 1; index >= 0; index--) {
  22154. if (this.meshes[index].id === id) {
  22155. return this.meshes[index];
  22156. }
  22157. }
  22158. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  22159. if (this.transformNodes[index].id === id) {
  22160. return this.transformNodes[index];
  22161. }
  22162. }
  22163. for (index = this.cameras.length - 1; index >= 0; index--) {
  22164. if (this.cameras[index].id === id) {
  22165. return this.cameras[index];
  22166. }
  22167. }
  22168. for (index = this.lights.length - 1; index >= 0; index--) {
  22169. if (this.lights[index].id === id) {
  22170. return this.lights[index];
  22171. }
  22172. }
  22173. return null;
  22174. };
  22175. Scene.prototype.getNodeByID = function (id) {
  22176. var mesh = this.getMeshByID(id);
  22177. if (mesh) {
  22178. return mesh;
  22179. }
  22180. var light = this.getLightByID(id);
  22181. if (light) {
  22182. return light;
  22183. }
  22184. var camera = this.getCameraByID(id);
  22185. if (camera) {
  22186. return camera;
  22187. }
  22188. var bone = this.getBoneByID(id);
  22189. return bone;
  22190. };
  22191. Scene.prototype.getNodeByName = function (name) {
  22192. var mesh = this.getMeshByName(name);
  22193. if (mesh) {
  22194. return mesh;
  22195. }
  22196. var light = this.getLightByName(name);
  22197. if (light) {
  22198. return light;
  22199. }
  22200. var camera = this.getCameraByName(name);
  22201. if (camera) {
  22202. return camera;
  22203. }
  22204. var bone = this.getBoneByName(name);
  22205. return bone;
  22206. };
  22207. Scene.prototype.getMeshByName = function (name) {
  22208. for (var index = 0; index < this.meshes.length; index++) {
  22209. if (this.meshes[index].name === name) {
  22210. return this.meshes[index];
  22211. }
  22212. }
  22213. return null;
  22214. };
  22215. Scene.prototype.getTransformNodeByName = function (name) {
  22216. for (var index = 0; index < this.transformNodes.length; index++) {
  22217. if (this.transformNodes[index].name === name) {
  22218. return this.transformNodes[index];
  22219. }
  22220. }
  22221. return null;
  22222. };
  22223. Scene.prototype.getSoundByName = function (name) {
  22224. var index;
  22225. if (BABYLON.AudioEngine) {
  22226. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  22227. if (this.mainSoundTrack.soundCollection[index].name === name) {
  22228. return this.mainSoundTrack.soundCollection[index];
  22229. }
  22230. }
  22231. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  22232. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  22233. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  22234. return this.soundTracks[sdIndex].soundCollection[index];
  22235. }
  22236. }
  22237. }
  22238. }
  22239. return null;
  22240. };
  22241. Scene.prototype.getLastSkeletonByID = function (id) {
  22242. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  22243. if (this.skeletons[index].id === id) {
  22244. return this.skeletons[index];
  22245. }
  22246. }
  22247. return null;
  22248. };
  22249. Scene.prototype.getSkeletonById = function (id) {
  22250. for (var index = 0; index < this.skeletons.length; index++) {
  22251. if (this.skeletons[index].id === id) {
  22252. return this.skeletons[index];
  22253. }
  22254. }
  22255. return null;
  22256. };
  22257. Scene.prototype.getSkeletonByName = function (name) {
  22258. for (var index = 0; index < this.skeletons.length; index++) {
  22259. if (this.skeletons[index].name === name) {
  22260. return this.skeletons[index];
  22261. }
  22262. }
  22263. return null;
  22264. };
  22265. Scene.prototype.getMorphTargetManagerById = function (id) {
  22266. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  22267. if (this.morphTargetManagers[index].uniqueId === id) {
  22268. return this.morphTargetManagers[index];
  22269. }
  22270. }
  22271. return null;
  22272. };
  22273. Scene.prototype.isActiveMesh = function (mesh) {
  22274. return (this._activeMeshes.indexOf(mesh) !== -1);
  22275. };
  22276. /**
  22277. * Return a the first highlight layer of the scene with a given name.
  22278. * @param name The name of the highlight layer to look for.
  22279. * @return The highlight layer if found otherwise null.
  22280. */
  22281. Scene.prototype.getHighlightLayerByName = function (name) {
  22282. for (var index = 0; index < this.highlightLayers.length; index++) {
  22283. if (this.highlightLayers[index].name === name) {
  22284. return this.highlightLayers[index];
  22285. }
  22286. }
  22287. return null;
  22288. };
  22289. Object.defineProperty(Scene.prototype, "uid", {
  22290. /**
  22291. * Return a unique id as a string which can serve as an identifier for the scene
  22292. */
  22293. get: function () {
  22294. if (!this._uid) {
  22295. this._uid = BABYLON.Tools.RandomId();
  22296. }
  22297. return this._uid;
  22298. },
  22299. enumerable: true,
  22300. configurable: true
  22301. });
  22302. /**
  22303. * Add an externaly attached data from its key.
  22304. * This method call will fail and return false, if such key already exists.
  22305. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  22306. * @param key the unique key that identifies the data
  22307. * @param data the data object to associate to the key for this Engine instance
  22308. * @return true if no such key were already present and the data was added successfully, false otherwise
  22309. */
  22310. Scene.prototype.addExternalData = function (key, data) {
  22311. if (!this._externalData) {
  22312. this._externalData = new BABYLON.StringDictionary();
  22313. }
  22314. return this._externalData.add(key, data);
  22315. };
  22316. /**
  22317. * Get an externaly attached data from its key
  22318. * @param key the unique key that identifies the data
  22319. * @return the associated data, if present (can be null), or undefined if not present
  22320. */
  22321. Scene.prototype.getExternalData = function (key) {
  22322. if (!this._externalData) {
  22323. return null;
  22324. }
  22325. return this._externalData.get(key);
  22326. };
  22327. /**
  22328. * Get an externaly attached data from its key, create it using a factory if it's not already present
  22329. * @param key the unique key that identifies the data
  22330. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  22331. * @return the associated data, can be null if the factory returned null.
  22332. */
  22333. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  22334. if (!this._externalData) {
  22335. this._externalData = new BABYLON.StringDictionary();
  22336. }
  22337. return this._externalData.getOrAddWithFactory(key, factory);
  22338. };
  22339. /**
  22340. * Remove an externaly attached data from the Engine instance
  22341. * @param key the unique key that identifies the data
  22342. * @return true if the data was successfully removed, false if it doesn't exist
  22343. */
  22344. Scene.prototype.removeExternalData = function (key) {
  22345. return this._externalData.remove(key);
  22346. };
  22347. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  22348. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  22349. if (mesh.showSubMeshesBoundingBox) {
  22350. var boundingInfo = subMesh.getBoundingInfo();
  22351. if (boundingInfo !== null && boundingInfo !== undefined) {
  22352. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22353. }
  22354. }
  22355. var material = subMesh.getMaterial();
  22356. if (material !== null && material !== undefined) {
  22357. // Render targets
  22358. if (material.getRenderTargetTextures !== undefined) {
  22359. if (this._processedMaterials.indexOf(material) === -1) {
  22360. this._processedMaterials.push(material);
  22361. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  22362. }
  22363. }
  22364. // Dispatch
  22365. this._activeIndices.addCount(subMesh.indexCount, false);
  22366. this._renderingManager.dispatch(subMesh, mesh, material);
  22367. }
  22368. }
  22369. };
  22370. Scene.prototype._isInIntermediateRendering = function () {
  22371. return this._intermediateRendering;
  22372. };
  22373. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  22374. this._activeMeshCandidateProvider = provider;
  22375. };
  22376. Scene.prototype.getActiveMeshCandidateProvider = function () {
  22377. return this._activeMeshCandidateProvider;
  22378. };
  22379. /**
  22380. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  22381. */
  22382. Scene.prototype.freezeActiveMeshes = function () {
  22383. this._evaluateActiveMeshes();
  22384. this._activeMeshesFrozen = true;
  22385. return this;
  22386. };
  22387. /**
  22388. * Use this function to restart evaluating active meshes on every frame
  22389. */
  22390. Scene.prototype.unfreezeActiveMeshes = function () {
  22391. this._activeMeshesFrozen = false;
  22392. return this;
  22393. };
  22394. Scene.prototype._evaluateActiveMeshes = function () {
  22395. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  22396. return;
  22397. }
  22398. if (!this.activeCamera) {
  22399. return;
  22400. }
  22401. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  22402. this.activeCamera._activeMeshes.reset();
  22403. this._activeMeshes.reset();
  22404. this._renderingManager.reset();
  22405. this._processedMaterials.reset();
  22406. this._activeParticleSystems.reset();
  22407. this._activeSkeletons.reset();
  22408. this._softwareSkinnedMeshes.reset();
  22409. if (this._boundingBoxRenderer) {
  22410. this._boundingBoxRenderer.reset();
  22411. }
  22412. // Meshes
  22413. var meshes;
  22414. var len;
  22415. var checkIsEnabled = true;
  22416. // Determine mesh candidates
  22417. if (this._activeMeshCandidateProvider !== undefined) {
  22418. // Use _activeMeshCandidateProvider
  22419. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  22420. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  22421. if (meshes !== undefined) {
  22422. len = meshes.length;
  22423. }
  22424. else {
  22425. len = 0;
  22426. }
  22427. }
  22428. else if (this._selectionOctree !== undefined) {
  22429. // Octree
  22430. var selection = this._selectionOctree.select(this._frustumPlanes);
  22431. meshes = selection.data;
  22432. len = selection.length;
  22433. }
  22434. else {
  22435. // Full scene traversal
  22436. len = this.meshes.length;
  22437. meshes = this.meshes;
  22438. }
  22439. // Check each mesh
  22440. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  22441. mesh = meshes[meshIndex];
  22442. if (mesh.isBlocked) {
  22443. continue;
  22444. }
  22445. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  22446. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  22447. continue;
  22448. }
  22449. mesh.computeWorldMatrix();
  22450. // Intersections
  22451. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  22452. this._meshesForIntersections.pushNoDuplicate(mesh);
  22453. }
  22454. // Switch to current LOD
  22455. meshLOD = mesh.getLOD(this.activeCamera);
  22456. if (meshLOD === undefined || meshLOD === null) {
  22457. continue;
  22458. }
  22459. mesh._preActivate();
  22460. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  22461. this._activeMeshes.push(mesh);
  22462. this.activeCamera._activeMeshes.push(mesh);
  22463. mesh._activate(this._renderId);
  22464. if (meshLOD !== mesh) {
  22465. meshLOD._activate(this._renderId);
  22466. }
  22467. this._activeMesh(mesh, meshLOD);
  22468. }
  22469. }
  22470. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  22471. // Particle systems
  22472. if (this.particlesEnabled) {
  22473. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  22474. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  22475. var particleSystem = this.particleSystems[particleIndex];
  22476. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  22477. continue;
  22478. }
  22479. var emitter = particleSystem.emitter;
  22480. if (!emitter.position || emitter.isEnabled()) {
  22481. this._activeParticleSystems.push(particleSystem);
  22482. particleSystem.animate();
  22483. this._renderingManager.dispatchParticles(particleSystem);
  22484. }
  22485. }
  22486. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  22487. }
  22488. };
  22489. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22490. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  22491. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22492. mesh.skeleton.prepare();
  22493. }
  22494. if (!mesh.computeBonesUsingShaders) {
  22495. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22496. }
  22497. }
  22498. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22499. var boundingInfo = sourceMesh.getBoundingInfo();
  22500. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22501. }
  22502. if (mesh !== undefined && mesh !== null
  22503. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  22504. // Submeshes Octrees
  22505. var len;
  22506. var subMeshes;
  22507. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  22508. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22509. len = intersections.length;
  22510. subMeshes = intersections.data;
  22511. }
  22512. else {
  22513. subMeshes = mesh.subMeshes;
  22514. len = subMeshes.length;
  22515. }
  22516. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22517. subMesh = subMeshes[subIndex];
  22518. this._evaluateSubMesh(subMesh, mesh);
  22519. }
  22520. }
  22521. };
  22522. Scene.prototype.updateTransformMatrix = function (force) {
  22523. if (!this.activeCamera) {
  22524. return;
  22525. }
  22526. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22527. };
  22528. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22529. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22530. };
  22531. Scene.prototype._renderForCamera = function (camera) {
  22532. if (camera && camera._skipRendering) {
  22533. return;
  22534. }
  22535. var engine = this._engine;
  22536. this.activeCamera = camera;
  22537. if (!this.activeCamera)
  22538. throw new Error("Active camera not set");
  22539. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22540. // Viewport
  22541. engine.setViewport(this.activeCamera.viewport);
  22542. // Camera
  22543. this.resetCachedMaterial();
  22544. this._renderId++;
  22545. this.activeCamera.update();
  22546. this.updateTransformMatrix();
  22547. if (camera._alternateCamera) {
  22548. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22549. this._alternateRendering = true;
  22550. }
  22551. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22552. // Meshes
  22553. this._evaluateActiveMeshes();
  22554. // Software skinning
  22555. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22556. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22557. mesh.applySkeleton(mesh.skeleton);
  22558. }
  22559. // Render targets
  22560. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22561. var needsRestoreFrameBuffer = false;
  22562. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22563. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22564. }
  22565. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22566. this._intermediateRendering = true;
  22567. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22568. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22569. var renderTarget = this._renderTargets.data[renderIndex];
  22570. if (renderTarget._shouldRender()) {
  22571. this._renderId++;
  22572. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22573. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22574. }
  22575. }
  22576. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22577. this._intermediateRendering = false;
  22578. this._renderId++;
  22579. needsRestoreFrameBuffer = true; // Restore back buffer
  22580. }
  22581. // Render HighlightLayer Texture
  22582. var stencilState = this._engine.getStencilBuffer();
  22583. var renderhighlights = false;
  22584. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22585. this._intermediateRendering = true;
  22586. for (var i = 0; i < this.highlightLayers.length; i++) {
  22587. var highlightLayer = this.highlightLayers[i];
  22588. if (highlightLayer.shouldRender() &&
  22589. (!highlightLayer.camera ||
  22590. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22591. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22592. renderhighlights = true;
  22593. var renderTarget = highlightLayer._mainTexture;
  22594. if (renderTarget._shouldRender()) {
  22595. this._renderId++;
  22596. renderTarget.render(false, false);
  22597. needsRestoreFrameBuffer = true;
  22598. }
  22599. }
  22600. }
  22601. this._intermediateRendering = false;
  22602. this._renderId++;
  22603. }
  22604. if (needsRestoreFrameBuffer) {
  22605. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22606. }
  22607. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22608. // Prepare Frame
  22609. this.postProcessManager._prepareFrame();
  22610. // Backgrounds
  22611. var layerIndex;
  22612. var layer;
  22613. if (this.layers.length) {
  22614. engine.setDepthBuffer(false);
  22615. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22616. layer = this.layers[layerIndex];
  22617. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22618. layer.render();
  22619. }
  22620. }
  22621. engine.setDepthBuffer(true);
  22622. }
  22623. // Activate HighlightLayer stencil
  22624. if (renderhighlights) {
  22625. this._engine.setStencilBuffer(true);
  22626. }
  22627. // Render
  22628. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22629. this._renderingManager.render(null, null, true, true);
  22630. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22631. // Restore HighlightLayer stencil
  22632. if (renderhighlights) {
  22633. this._engine.setStencilBuffer(stencilState);
  22634. }
  22635. // Bounding boxes
  22636. if (this._boundingBoxRenderer) {
  22637. this._boundingBoxRenderer.render();
  22638. }
  22639. // Lens flares
  22640. if (this.lensFlaresEnabled) {
  22641. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22642. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22643. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22644. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22645. lensFlareSystem.render();
  22646. }
  22647. }
  22648. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22649. }
  22650. // Foregrounds
  22651. if (this.layers.length) {
  22652. engine.setDepthBuffer(false);
  22653. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22654. layer = this.layers[layerIndex];
  22655. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22656. layer.render();
  22657. }
  22658. }
  22659. engine.setDepthBuffer(true);
  22660. }
  22661. // Highlight Layer
  22662. if (renderhighlights) {
  22663. engine.setDepthBuffer(false);
  22664. for (var i = 0; i < this.highlightLayers.length; i++) {
  22665. if (this.highlightLayers[i].shouldRender()) {
  22666. this.highlightLayers[i].render();
  22667. }
  22668. }
  22669. engine.setDepthBuffer(true);
  22670. }
  22671. // Finalize frame
  22672. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22673. // Reset some special arrays
  22674. this._renderTargets.reset();
  22675. this._alternateRendering = false;
  22676. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22677. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22678. };
  22679. Scene.prototype._processSubCameras = function (camera) {
  22680. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22681. this._renderForCamera(camera);
  22682. return;
  22683. }
  22684. // Update camera
  22685. if (this.activeCamera) {
  22686. this.activeCamera.update();
  22687. }
  22688. // rig cameras
  22689. for (var index = 0; index < camera._rigCameras.length; index++) {
  22690. this._renderForCamera(camera._rigCameras[index]);
  22691. }
  22692. this.activeCamera = camera;
  22693. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22694. };
  22695. Scene.prototype._checkIntersections = function () {
  22696. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22697. var sourceMesh = this._meshesForIntersections.data[index];
  22698. if (!sourceMesh.actionManager) {
  22699. continue;
  22700. }
  22701. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22702. var action = sourceMesh.actionManager.actions[actionIndex];
  22703. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22704. var parameters = action.getTriggerParameter();
  22705. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22706. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22707. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22708. if (areIntersecting && currentIntersectionInProgress === -1) {
  22709. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22710. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22711. sourceMesh._intersectionsInProgress.push(otherMesh);
  22712. }
  22713. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22714. sourceMesh._intersectionsInProgress.push(otherMesh);
  22715. }
  22716. }
  22717. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22718. //They intersected, and now they don't.
  22719. //is this trigger an exit trigger? execute an event.
  22720. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22721. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22722. }
  22723. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22724. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22725. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22726. }
  22727. }
  22728. }
  22729. }
  22730. }
  22731. };
  22732. Scene.prototype.render = function () {
  22733. if (this.isDisposed) {
  22734. return;
  22735. }
  22736. this._activeParticles.fetchNewFrame();
  22737. this._totalVertices.fetchNewFrame();
  22738. this._activeIndices.fetchNewFrame();
  22739. this._activeBones.fetchNewFrame();
  22740. this._meshesForIntersections.reset();
  22741. this.resetCachedMaterial();
  22742. this.onBeforeAnimationsObservable.notifyObservers(this);
  22743. // Actions
  22744. if (this.actionManager) {
  22745. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22746. }
  22747. //Simplification Queue
  22748. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22749. this.simplificationQueue.executeNext();
  22750. }
  22751. if (this._engine.isDeterministicLockStep()) {
  22752. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22753. var defaultFPS = (60.0 / 1000.0);
  22754. var defaultFrameTime = 1000 / 60; // frame time in MS
  22755. if (this._physicsEngine) {
  22756. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22757. }
  22758. var stepsTaken = 0;
  22759. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22760. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22761. internalSteps = Math.min(internalSteps, maxSubSteps);
  22762. do {
  22763. this.onBeforeStepObservable.notifyObservers(this);
  22764. // Animations
  22765. this._animationRatio = defaultFrameTime * defaultFPS;
  22766. this._animate();
  22767. this.onAfterAnimationsObservable.notifyObservers(this);
  22768. // Physics
  22769. if (this._physicsEngine) {
  22770. this.onBeforePhysicsObservable.notifyObservers(this);
  22771. this._physicsEngine._step(defaultFrameTime / 1000);
  22772. this.onAfterPhysicsObservable.notifyObservers(this);
  22773. }
  22774. this.onAfterStepObservable.notifyObservers(this);
  22775. this._currentStepId++;
  22776. stepsTaken++;
  22777. deltaTime -= defaultFrameTime;
  22778. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22779. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22780. }
  22781. else {
  22782. // Animations
  22783. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22784. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22785. this._animate();
  22786. this.onAfterAnimationsObservable.notifyObservers(this);
  22787. // Physics
  22788. if (this._physicsEngine) {
  22789. this.onBeforePhysicsObservable.notifyObservers(this);
  22790. this._physicsEngine._step(deltaTime / 1000.0);
  22791. this.onAfterPhysicsObservable.notifyObservers(this);
  22792. }
  22793. }
  22794. // update gamepad manager
  22795. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22796. this._gamepadManager._checkGamepadsStatus();
  22797. }
  22798. // Before render
  22799. this.onBeforeRenderObservable.notifyObservers(this);
  22800. // Customs render targets
  22801. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22802. var engine = this.getEngine();
  22803. var currentActiveCamera = this.activeCamera;
  22804. if (this.renderTargetsEnabled) {
  22805. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22806. this._intermediateRendering = true;
  22807. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22808. var renderTarget = this.customRenderTargets[customIndex];
  22809. if (renderTarget._shouldRender()) {
  22810. this._renderId++;
  22811. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22812. if (!this.activeCamera)
  22813. throw new Error("Active camera not set");
  22814. // Viewport
  22815. engine.setViewport(this.activeCamera.viewport);
  22816. // Camera
  22817. this.updateTransformMatrix();
  22818. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22819. }
  22820. }
  22821. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22822. this._intermediateRendering = false;
  22823. this._renderId++;
  22824. }
  22825. // Restore back buffer
  22826. if (this.customRenderTargets.length > 0) {
  22827. engine.restoreDefaultFramebuffer();
  22828. }
  22829. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22830. this.activeCamera = currentActiveCamera;
  22831. // Procedural textures
  22832. if (this.proceduralTexturesEnabled) {
  22833. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22834. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22835. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22836. if (proceduralTexture._shouldRender()) {
  22837. proceduralTexture.render();
  22838. }
  22839. }
  22840. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22841. }
  22842. // Clear
  22843. if (this.autoClearDepthAndStencil || this.autoClear) {
  22844. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22845. }
  22846. // Shadows
  22847. if (this.shadowsEnabled) {
  22848. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22849. var light = this.lights[lightIndex];
  22850. var shadowGenerator = light.getShadowGenerator();
  22851. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22852. var shadowMap = (shadowGenerator.getShadowMap());
  22853. if (this.textures.indexOf(shadowMap) !== -1) {
  22854. this._renderTargets.push(shadowMap);
  22855. }
  22856. }
  22857. }
  22858. }
  22859. // Depth renderer
  22860. if (this._depthRenderer) {
  22861. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22862. }
  22863. // Geometry renderer
  22864. if (this._geometryBufferRenderer) {
  22865. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22866. }
  22867. // RenderPipeline
  22868. if (this._postProcessRenderPipelineManager) {
  22869. this._postProcessRenderPipelineManager.update();
  22870. }
  22871. // Multi-cameras?
  22872. if (this.activeCameras.length > 0) {
  22873. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22874. if (cameraIndex > 0) {
  22875. this._engine.clear(null, false, true, true);
  22876. }
  22877. this._processSubCameras(this.activeCameras[cameraIndex]);
  22878. }
  22879. }
  22880. else {
  22881. if (!this.activeCamera) {
  22882. throw new Error("No camera defined");
  22883. }
  22884. this._processSubCameras(this.activeCamera);
  22885. }
  22886. // Intersection checks
  22887. this._checkIntersections();
  22888. // Update the audio listener attached to the camera
  22889. if (BABYLON.AudioEngine) {
  22890. this._updateAudioParameters();
  22891. }
  22892. // After render
  22893. if (this.afterRender) {
  22894. this.afterRender();
  22895. }
  22896. this.onAfterRenderObservable.notifyObservers(this);
  22897. // Cleaning
  22898. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22899. var data = this._toBeDisposed.data[index];
  22900. if (data) {
  22901. data.dispose();
  22902. }
  22903. this._toBeDisposed[index] = null;
  22904. }
  22905. this._toBeDisposed.reset();
  22906. if (this.dumpNextRenderTargets) {
  22907. this.dumpNextRenderTargets = false;
  22908. }
  22909. this._activeBones.addCount(0, true);
  22910. this._activeIndices.addCount(0, true);
  22911. this._activeParticles.addCount(0, true);
  22912. };
  22913. Scene.prototype._updateAudioParameters = function () {
  22914. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22915. return;
  22916. }
  22917. var listeningCamera;
  22918. var audioEngine = BABYLON.Engine.audioEngine;
  22919. if (this.activeCameras.length > 0) {
  22920. listeningCamera = this.activeCameras[0];
  22921. }
  22922. else {
  22923. listeningCamera = this.activeCamera;
  22924. }
  22925. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22926. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22927. // for VR cameras
  22928. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22929. listeningCamera = listeningCamera.rigCameras[0];
  22930. }
  22931. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22932. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22933. cameraDirection.normalize();
  22934. // To avoid some errors on GearVR
  22935. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22936. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22937. }
  22938. var i;
  22939. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22940. var sound = this.mainSoundTrack.soundCollection[i];
  22941. if (sound.useCustomAttenuation) {
  22942. sound.updateDistanceFromListener();
  22943. }
  22944. }
  22945. for (i = 0; i < this.soundTracks.length; i++) {
  22946. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22947. sound = this.soundTracks[i].soundCollection[j];
  22948. if (sound.useCustomAttenuation) {
  22949. sound.updateDistanceFromListener();
  22950. }
  22951. }
  22952. }
  22953. }
  22954. };
  22955. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22956. // Audio
  22957. get: function () {
  22958. return this._audioEnabled;
  22959. },
  22960. set: function (value) {
  22961. this._audioEnabled = value;
  22962. if (BABYLON.AudioEngine) {
  22963. if (this._audioEnabled) {
  22964. this._enableAudio();
  22965. }
  22966. else {
  22967. this._disableAudio();
  22968. }
  22969. }
  22970. },
  22971. enumerable: true,
  22972. configurable: true
  22973. });
  22974. Scene.prototype._disableAudio = function () {
  22975. var i;
  22976. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22977. this.mainSoundTrack.soundCollection[i].pause();
  22978. }
  22979. for (i = 0; i < this.soundTracks.length; i++) {
  22980. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22981. this.soundTracks[i].soundCollection[j].pause();
  22982. }
  22983. }
  22984. };
  22985. Scene.prototype._enableAudio = function () {
  22986. var i;
  22987. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22988. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22989. this.mainSoundTrack.soundCollection[i].play();
  22990. }
  22991. }
  22992. for (i = 0; i < this.soundTracks.length; i++) {
  22993. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22994. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22995. this.soundTracks[i].soundCollection[j].play();
  22996. }
  22997. }
  22998. }
  22999. };
  23000. Object.defineProperty(Scene.prototype, "headphone", {
  23001. get: function () {
  23002. return this._headphone;
  23003. },
  23004. set: function (value) {
  23005. this._headphone = value;
  23006. if (BABYLON.AudioEngine) {
  23007. if (this._headphone) {
  23008. this._switchAudioModeForHeadphones();
  23009. }
  23010. else {
  23011. this._switchAudioModeForNormalSpeakers();
  23012. }
  23013. }
  23014. },
  23015. enumerable: true,
  23016. configurable: true
  23017. });
  23018. Scene.prototype._switchAudioModeForHeadphones = function () {
  23019. this.mainSoundTrack.switchPanningModelToHRTF();
  23020. for (var i = 0; i < this.soundTracks.length; i++) {
  23021. this.soundTracks[i].switchPanningModelToHRTF();
  23022. }
  23023. };
  23024. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  23025. this.mainSoundTrack.switchPanningModelToEqualPower();
  23026. for (var i = 0; i < this.soundTracks.length; i++) {
  23027. this.soundTracks[i].switchPanningModelToEqualPower();
  23028. }
  23029. };
  23030. Scene.prototype.enableDepthRenderer = function () {
  23031. if (this._depthRenderer) {
  23032. return this._depthRenderer;
  23033. }
  23034. this._depthRenderer = new BABYLON.DepthRenderer(this);
  23035. return this._depthRenderer;
  23036. };
  23037. Scene.prototype.disableDepthRenderer = function () {
  23038. if (!this._depthRenderer) {
  23039. return;
  23040. }
  23041. this._depthRenderer.dispose();
  23042. this._depthRenderer = null;
  23043. };
  23044. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  23045. if (ratio === void 0) { ratio = 1; }
  23046. if (this._geometryBufferRenderer) {
  23047. return this._geometryBufferRenderer;
  23048. }
  23049. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  23050. if (!this._geometryBufferRenderer.isSupported) {
  23051. this._geometryBufferRenderer = null;
  23052. }
  23053. return this._geometryBufferRenderer;
  23054. };
  23055. Scene.prototype.disableGeometryBufferRenderer = function () {
  23056. if (!this._geometryBufferRenderer) {
  23057. return;
  23058. }
  23059. this._geometryBufferRenderer.dispose();
  23060. this._geometryBufferRenderer = null;
  23061. };
  23062. Scene.prototype.freezeMaterials = function () {
  23063. for (var i = 0; i < this.materials.length; i++) {
  23064. this.materials[i].freeze();
  23065. }
  23066. };
  23067. Scene.prototype.unfreezeMaterials = function () {
  23068. for (var i = 0; i < this.materials.length; i++) {
  23069. this.materials[i].unfreeze();
  23070. }
  23071. };
  23072. Scene.prototype.dispose = function () {
  23073. this.beforeRender = null;
  23074. this.afterRender = null;
  23075. this.skeletons = [];
  23076. this.morphTargetManagers = [];
  23077. this.importedMeshesFiles = new Array();
  23078. this.stopAllAnimations();
  23079. this.resetCachedMaterial();
  23080. if (this._depthRenderer) {
  23081. this._depthRenderer.dispose();
  23082. }
  23083. if (this._gamepadManager) {
  23084. this._gamepadManager.dispose();
  23085. this._gamepadManager = null;
  23086. }
  23087. // Smart arrays
  23088. if (this.activeCamera) {
  23089. this.activeCamera._activeMeshes.dispose();
  23090. this.activeCamera = null;
  23091. }
  23092. this._activeMeshes.dispose();
  23093. this._renderingManager.dispose();
  23094. this._processedMaterials.dispose();
  23095. this._activeParticleSystems.dispose();
  23096. this._activeSkeletons.dispose();
  23097. this._softwareSkinnedMeshes.dispose();
  23098. this._renderTargets.dispose();
  23099. if (this._boundingBoxRenderer) {
  23100. this._boundingBoxRenderer.dispose();
  23101. }
  23102. this._meshesForIntersections.dispose();
  23103. this._toBeDisposed.dispose();
  23104. // Abort active requests
  23105. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  23106. var request = _a[_i];
  23107. request.abort();
  23108. }
  23109. // Debug layer
  23110. if (this._debugLayer) {
  23111. this._debugLayer.hide();
  23112. }
  23113. // Events
  23114. this.onDisposeObservable.notifyObservers(this);
  23115. this.onDisposeObservable.clear();
  23116. this.onBeforeRenderObservable.clear();
  23117. this.onAfterRenderObservable.clear();
  23118. this.OnBeforeRenderTargetsRenderObservable.clear();
  23119. this.OnAfterRenderTargetsRenderObservable.clear();
  23120. this.onAfterStepObservable.clear();
  23121. this.onBeforeStepObservable.clear();
  23122. this.onBeforeActiveMeshesEvaluationObservable.clear();
  23123. this.onAfterActiveMeshesEvaluationObservable.clear();
  23124. this.onBeforeParticlesRenderingObservable.clear();
  23125. this.onAfterParticlesRenderingObservable.clear();
  23126. this.onBeforeSpritesRenderingObservable.clear();
  23127. this.onAfterSpritesRenderingObservable.clear();
  23128. this.onBeforeDrawPhaseObservable.clear();
  23129. this.onAfterDrawPhaseObservable.clear();
  23130. this.onBeforePhysicsObservable.clear();
  23131. this.onAfterPhysicsObservable.clear();
  23132. this.onBeforeAnimationsObservable.clear();
  23133. this.onAfterAnimationsObservable.clear();
  23134. this.onDataLoadedObservable.clear();
  23135. this.detachControl();
  23136. // Release sounds & sounds tracks
  23137. if (BABYLON.AudioEngine) {
  23138. this.disposeSounds();
  23139. }
  23140. // VR Helper
  23141. if (this.VRHelper) {
  23142. this.VRHelper.dispose();
  23143. }
  23144. // Detach cameras
  23145. var canvas = this._engine.getRenderingCanvas();
  23146. if (canvas) {
  23147. var index;
  23148. for (index = 0; index < this.cameras.length; index++) {
  23149. this.cameras[index].detachControl(canvas);
  23150. }
  23151. }
  23152. // Release animation groups
  23153. while (this.animationGroups.length) {
  23154. this.animationGroups[0].dispose();
  23155. }
  23156. // Release lights
  23157. while (this.lights.length) {
  23158. this.lights[0].dispose();
  23159. }
  23160. // Release meshes
  23161. while (this.meshes.length) {
  23162. this.meshes[0].dispose(true);
  23163. }
  23164. while (this.transformNodes.length) {
  23165. this.removeTransformNode(this.transformNodes[0]);
  23166. }
  23167. // Release cameras
  23168. while (this.cameras.length) {
  23169. this.cameras[0].dispose();
  23170. }
  23171. // Release materials
  23172. if (this.defaultMaterial) {
  23173. this.defaultMaterial.dispose();
  23174. }
  23175. while (this.multiMaterials.length) {
  23176. this.multiMaterials[0].dispose();
  23177. }
  23178. while (this.materials.length) {
  23179. this.materials[0].dispose();
  23180. }
  23181. // Release particles
  23182. while (this.particleSystems.length) {
  23183. this.particleSystems[0].dispose();
  23184. }
  23185. // Release sprites
  23186. while (this.spriteManagers.length) {
  23187. this.spriteManagers[0].dispose();
  23188. }
  23189. // Release postProcesses
  23190. while (this.postProcesses.length) {
  23191. this.postProcesses[0].dispose();
  23192. }
  23193. // Release layers
  23194. while (this.layers.length) {
  23195. this.layers[0].dispose();
  23196. }
  23197. while (this.highlightLayers.length) {
  23198. this.highlightLayers[0].dispose();
  23199. }
  23200. // Release textures
  23201. while (this.textures.length) {
  23202. this.textures[0].dispose();
  23203. }
  23204. // Release UBO
  23205. this._sceneUbo.dispose();
  23206. if (this._alternateSceneUbo) {
  23207. this._alternateSceneUbo.dispose();
  23208. }
  23209. // Post-processes
  23210. this.postProcessManager.dispose();
  23211. if (this._postProcessRenderPipelineManager) {
  23212. this._postProcessRenderPipelineManager.dispose();
  23213. }
  23214. // Physics
  23215. if (this._physicsEngine) {
  23216. this.disablePhysicsEngine();
  23217. }
  23218. // Remove from engine
  23219. index = this._engine.scenes.indexOf(this);
  23220. if (index > -1) {
  23221. this._engine.scenes.splice(index, 1);
  23222. }
  23223. this._engine.wipeCaches(true);
  23224. this._isDisposed = true;
  23225. };
  23226. Object.defineProperty(Scene.prototype, "isDisposed", {
  23227. get: function () {
  23228. return this._isDisposed;
  23229. },
  23230. enumerable: true,
  23231. configurable: true
  23232. });
  23233. // Release sounds & sounds tracks
  23234. Scene.prototype.disposeSounds = function () {
  23235. if (!this._mainSoundTrack) {
  23236. return;
  23237. }
  23238. this.mainSoundTrack.dispose();
  23239. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  23240. this.soundTracks[scIndex].dispose();
  23241. }
  23242. };
  23243. // Octrees
  23244. Scene.prototype.getWorldExtends = function () {
  23245. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23246. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  23247. for (var index = 0; index < this.meshes.length; index++) {
  23248. var mesh = this.meshes[index];
  23249. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  23250. continue;
  23251. }
  23252. mesh.computeWorldMatrix(true);
  23253. var boundingInfo = mesh.getBoundingInfo();
  23254. var minBox = boundingInfo.boundingBox.minimumWorld;
  23255. var maxBox = boundingInfo.boundingBox.maximumWorld;
  23256. BABYLON.Tools.CheckExtends(minBox, min, max);
  23257. BABYLON.Tools.CheckExtends(maxBox, min, max);
  23258. }
  23259. return {
  23260. min: min,
  23261. max: max
  23262. };
  23263. };
  23264. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  23265. if (maxCapacity === void 0) { maxCapacity = 64; }
  23266. if (maxDepth === void 0) { maxDepth = 2; }
  23267. if (!this._selectionOctree) {
  23268. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  23269. }
  23270. var worldExtends = this.getWorldExtends();
  23271. // Update octree
  23272. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  23273. return this._selectionOctree;
  23274. };
  23275. // Picking
  23276. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  23277. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23278. var result = BABYLON.Ray.Zero();
  23279. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  23280. return result;
  23281. };
  23282. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  23283. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23284. var engine = this._engine;
  23285. if (!camera) {
  23286. if (!this.activeCamera)
  23287. throw new Error("Active camera not set");
  23288. camera = this.activeCamera;
  23289. }
  23290. var cameraViewport = camera.viewport;
  23291. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23292. // Moving coordinates to local viewport world
  23293. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23294. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23295. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  23296. return this;
  23297. };
  23298. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  23299. var result = BABYLON.Ray.Zero();
  23300. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  23301. return result;
  23302. };
  23303. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  23304. if (!BABYLON.PickingInfo) {
  23305. return this;
  23306. }
  23307. var engine = this._engine;
  23308. if (!camera) {
  23309. if (!this.activeCamera)
  23310. throw new Error("Active camera not set");
  23311. camera = this.activeCamera;
  23312. }
  23313. var cameraViewport = camera.viewport;
  23314. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23315. var identity = BABYLON.Matrix.Identity();
  23316. // Moving coordinates to local viewport world
  23317. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23318. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23319. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  23320. return this;
  23321. };
  23322. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  23323. if (!BABYLON.PickingInfo) {
  23324. return null;
  23325. }
  23326. var pickingInfo = null;
  23327. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23328. var mesh = this.meshes[meshIndex];
  23329. if (predicate) {
  23330. if (!predicate(mesh)) {
  23331. continue;
  23332. }
  23333. }
  23334. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23335. continue;
  23336. }
  23337. var world = mesh.getWorldMatrix();
  23338. var ray = rayFunction(world);
  23339. var result = mesh.intersects(ray, fastCheck);
  23340. if (!result || !result.hit)
  23341. continue;
  23342. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23343. continue;
  23344. pickingInfo = result;
  23345. if (fastCheck) {
  23346. break;
  23347. }
  23348. }
  23349. return pickingInfo || new BABYLON.PickingInfo();
  23350. };
  23351. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  23352. if (!BABYLON.PickingInfo) {
  23353. return null;
  23354. }
  23355. var pickingInfos = new Array();
  23356. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23357. var mesh = this.meshes[meshIndex];
  23358. if (predicate) {
  23359. if (!predicate(mesh)) {
  23360. continue;
  23361. }
  23362. }
  23363. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23364. continue;
  23365. }
  23366. var world = mesh.getWorldMatrix();
  23367. var ray = rayFunction(world);
  23368. var result = mesh.intersects(ray, false);
  23369. if (!result || !result.hit)
  23370. continue;
  23371. pickingInfos.push(result);
  23372. }
  23373. return pickingInfos;
  23374. };
  23375. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  23376. if (!BABYLON.PickingInfo) {
  23377. return null;
  23378. }
  23379. var pickingInfo = null;
  23380. if (!camera) {
  23381. if (!this.activeCamera) {
  23382. return null;
  23383. }
  23384. camera = this.activeCamera;
  23385. }
  23386. if (this.spriteManagers.length > 0) {
  23387. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  23388. var spriteManager = this.spriteManagers[spriteIndex];
  23389. if (!spriteManager.isPickable) {
  23390. continue;
  23391. }
  23392. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  23393. if (!result || !result.hit)
  23394. continue;
  23395. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23396. continue;
  23397. pickingInfo = result;
  23398. if (fastCheck) {
  23399. break;
  23400. }
  23401. }
  23402. }
  23403. return pickingInfo || new BABYLON.PickingInfo();
  23404. };
  23405. /** Launch a ray to try to pick a mesh in the scene
  23406. * @param x position on screen
  23407. * @param y position on screen
  23408. * @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
  23409. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23410. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23411. */
  23412. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  23413. var _this = this;
  23414. if (!BABYLON.PickingInfo) {
  23415. return null;
  23416. }
  23417. return this._internalPick(function (world) {
  23418. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  23419. return _this._tempPickingRay;
  23420. }, predicate, fastCheck);
  23421. };
  23422. /** Launch a ray to try to pick a sprite in the scene
  23423. * @param x position on screen
  23424. * @param y position on screen
  23425. * @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
  23426. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23427. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23428. */
  23429. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  23430. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  23431. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  23432. };
  23433. /** Use the given ray to pick a mesh in the scene
  23434. * @param ray The ray to use to pick meshes
  23435. * @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
  23436. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23437. */
  23438. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  23439. var _this = this;
  23440. return this._internalPick(function (world) {
  23441. if (!_this._pickWithRayInverseMatrix) {
  23442. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23443. }
  23444. world.invertToRef(_this._pickWithRayInverseMatrix);
  23445. if (!_this._cachedRayForTransform) {
  23446. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23447. }
  23448. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23449. return _this._cachedRayForTransform;
  23450. }, predicate, fastCheck);
  23451. };
  23452. /**
  23453. * Launch a ray to try to pick a mesh in the scene
  23454. * @param x X position on screen
  23455. * @param y Y position on screen
  23456. * @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
  23457. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23458. */
  23459. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  23460. var _this = this;
  23461. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  23462. };
  23463. /**
  23464. * Launch a ray to try to pick a mesh in the scene
  23465. * @param ray Ray to use
  23466. * @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
  23467. */
  23468. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  23469. var _this = this;
  23470. return this._internalMultiPick(function (world) {
  23471. if (!_this._pickWithRayInverseMatrix) {
  23472. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23473. }
  23474. world.invertToRef(_this._pickWithRayInverseMatrix);
  23475. if (!_this._cachedRayForTransform) {
  23476. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23477. }
  23478. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23479. return _this._cachedRayForTransform;
  23480. }, predicate);
  23481. };
  23482. Scene.prototype.setPointerOverMesh = function (mesh) {
  23483. if (this._pointerOverMesh === mesh) {
  23484. return;
  23485. }
  23486. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23487. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23488. }
  23489. this._pointerOverMesh = mesh;
  23490. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23491. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23492. }
  23493. };
  23494. Scene.prototype.getPointerOverMesh = function () {
  23495. return this._pointerOverMesh;
  23496. };
  23497. Scene.prototype.setPointerOverSprite = function (sprite) {
  23498. if (this._pointerOverSprite === sprite) {
  23499. return;
  23500. }
  23501. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23502. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23503. }
  23504. this._pointerOverSprite = sprite;
  23505. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23506. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23507. }
  23508. };
  23509. Scene.prototype.getPointerOverSprite = function () {
  23510. return this._pointerOverSprite;
  23511. };
  23512. // Physics
  23513. Scene.prototype.getPhysicsEngine = function () {
  23514. return this._physicsEngine;
  23515. };
  23516. /**
  23517. * Enables physics to the current scene
  23518. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23519. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23520. * @return {boolean} was the physics engine initialized
  23521. */
  23522. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23523. if (gravity === void 0) { gravity = null; }
  23524. if (this._physicsEngine) {
  23525. return true;
  23526. }
  23527. try {
  23528. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23529. return true;
  23530. }
  23531. catch (e) {
  23532. BABYLON.Tools.Error(e.message);
  23533. return false;
  23534. }
  23535. };
  23536. Scene.prototype.disablePhysicsEngine = function () {
  23537. if (!this._physicsEngine) {
  23538. return;
  23539. }
  23540. this._physicsEngine.dispose();
  23541. this._physicsEngine = null;
  23542. };
  23543. Scene.prototype.isPhysicsEnabled = function () {
  23544. return this._physicsEngine !== undefined;
  23545. };
  23546. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23547. var mesh = compound.parts[0].mesh;
  23548. if (mesh.physicsImpostor) {
  23549. mesh.physicsImpostor.dispose();
  23550. mesh.physicsImpostor = null;
  23551. }
  23552. };
  23553. // Misc.
  23554. Scene.prototype._rebuildGeometries = function () {
  23555. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23556. var geometry = _a[_i];
  23557. geometry._rebuild();
  23558. }
  23559. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23560. var mesh = _c[_b];
  23561. mesh._rebuild();
  23562. }
  23563. if (this.postProcessManager) {
  23564. this.postProcessManager._rebuild();
  23565. }
  23566. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23567. var layer = _e[_d];
  23568. layer._rebuild();
  23569. }
  23570. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23571. var highlightLayer = _g[_f];
  23572. highlightLayer._rebuild();
  23573. }
  23574. if (this._boundingBoxRenderer) {
  23575. this._boundingBoxRenderer._rebuild();
  23576. }
  23577. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23578. var system = _j[_h];
  23579. system.rebuild();
  23580. }
  23581. if (this._postProcessRenderPipelineManager) {
  23582. this._postProcessRenderPipelineManager._rebuild();
  23583. }
  23584. };
  23585. Scene.prototype._rebuildTextures = function () {
  23586. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23587. var texture = _a[_i];
  23588. texture._rebuild();
  23589. }
  23590. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23591. };
  23592. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23593. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23594. if (replace === void 0) { replace = false; }
  23595. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23596. // Dispose existing camera or light in replace mode.
  23597. if (replace) {
  23598. if (this.activeCamera) {
  23599. this.activeCamera.dispose();
  23600. this.activeCamera = null;
  23601. }
  23602. if (this.lights) {
  23603. for (var i = 0; i < this.lights.length; i++) {
  23604. this.lights[i].dispose();
  23605. }
  23606. }
  23607. }
  23608. // Light
  23609. if (this.lights.length === 0) {
  23610. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23611. }
  23612. // Camera
  23613. if (!this.activeCamera) {
  23614. var worldExtends = this.getWorldExtends();
  23615. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23616. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23617. var camera;
  23618. var radius = worldSize.length() * 1.5;
  23619. if (createArcRotateCamera) {
  23620. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23621. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23622. arcRotateCamera.wheelPrecision = 100 / radius;
  23623. camera = arcRotateCamera;
  23624. }
  23625. else {
  23626. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23627. freeCamera.setTarget(worldCenter);
  23628. camera = freeCamera;
  23629. }
  23630. camera.minZ = radius * 0.01;
  23631. camera.maxZ = radius * 1000;
  23632. camera.speed = radius * 0.2;
  23633. this.activeCamera = camera;
  23634. var canvas = this.getEngine().getRenderingCanvas();
  23635. if (attachCameraControls && canvas) {
  23636. camera.attachControl(canvas);
  23637. }
  23638. }
  23639. };
  23640. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23641. if (pbr === void 0) { pbr = false; }
  23642. if (scale === void 0) { scale = 1000; }
  23643. if (blur === void 0) { blur = 0; }
  23644. if (environmentTexture) {
  23645. this.environmentTexture = environmentTexture;
  23646. }
  23647. if (!this.environmentTexture) {
  23648. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23649. return null;
  23650. }
  23651. // Skybox
  23652. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23653. if (pbr) {
  23654. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23655. hdrSkyboxMaterial.backFaceCulling = false;
  23656. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23657. if (hdrSkyboxMaterial.reflectionTexture) {
  23658. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23659. }
  23660. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23661. hdrSkyboxMaterial.disableLighting = true;
  23662. hdrSkyboxMaterial.twoSidedLighting = true;
  23663. hdrSkybox.infiniteDistance = true;
  23664. hdrSkybox.material = hdrSkyboxMaterial;
  23665. }
  23666. else {
  23667. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23668. skyboxMaterial.backFaceCulling = false;
  23669. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23670. if (skyboxMaterial.reflectionTexture) {
  23671. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23672. }
  23673. skyboxMaterial.disableLighting = true;
  23674. hdrSkybox.infiniteDistance = true;
  23675. hdrSkybox.material = skyboxMaterial;
  23676. }
  23677. return hdrSkybox;
  23678. };
  23679. Scene.prototype.createDefaultEnvironment = function (options) {
  23680. if (BABYLON.EnvironmentHelper) {
  23681. return new BABYLON.EnvironmentHelper(options, this);
  23682. }
  23683. return null;
  23684. };
  23685. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23686. if (webVROptions === void 0) { webVROptions = {}; }
  23687. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23688. };
  23689. // Tags
  23690. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23691. if (tagsQuery === undefined) {
  23692. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23693. return list;
  23694. }
  23695. var listByTags = [];
  23696. forEach = forEach || (function (item) { return; });
  23697. for (var i in list) {
  23698. var item = list[i];
  23699. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23700. listByTags.push(item);
  23701. forEach(item);
  23702. }
  23703. }
  23704. return listByTags;
  23705. };
  23706. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23707. return this._getByTags(this.meshes, tagsQuery, forEach);
  23708. };
  23709. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23710. return this._getByTags(this.cameras, tagsQuery, forEach);
  23711. };
  23712. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23713. return this._getByTags(this.lights, tagsQuery, forEach);
  23714. };
  23715. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23716. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23717. };
  23718. /**
  23719. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23720. * This allowed control for front to back rendering or reversly depending of the special needs.
  23721. *
  23722. * @param renderingGroupId The rendering group id corresponding to its index
  23723. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23724. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23725. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23726. */
  23727. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23728. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23729. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23730. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23731. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23732. };
  23733. /**
  23734. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23735. *
  23736. * @param renderingGroupId The rendering group id corresponding to its index
  23737. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23738. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23739. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23740. */
  23741. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23742. if (depth === void 0) { depth = true; }
  23743. if (stencil === void 0) { stencil = true; }
  23744. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23745. };
  23746. /**
  23747. * Will flag all materials as dirty to trigger new shader compilation
  23748. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23749. */
  23750. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23751. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23752. var material = _a[_i];
  23753. if (predicate && !predicate(material)) {
  23754. continue;
  23755. }
  23756. material.markAsDirty(flag);
  23757. }
  23758. };
  23759. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23760. var _this = this;
  23761. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23762. this._activeRequests.push(request);
  23763. request.onCompleteObservable.add(function (request) {
  23764. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23765. });
  23766. return request;
  23767. };
  23768. /** @ignore */
  23769. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  23770. var _this = this;
  23771. return new Promise(function (resolve, reject) {
  23772. _this._loadFile(url, function (data) {
  23773. resolve(data);
  23774. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  23775. reject(exception);
  23776. });
  23777. });
  23778. };
  23779. // Statics
  23780. Scene._FOGMODE_NONE = 0;
  23781. Scene._FOGMODE_EXP = 1;
  23782. Scene._FOGMODE_EXP2 = 2;
  23783. Scene._FOGMODE_LINEAR = 3;
  23784. Scene._uniqueIdCounter = 0;
  23785. Scene.MinDeltaTime = 1.0;
  23786. Scene.MaxDeltaTime = 1000.0;
  23787. /** The distance in pixel that you have to move to prevent some events */
  23788. Scene.DragMovementThreshold = 10; // in pixels
  23789. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23790. Scene.LongPressDelay = 500; // in milliseconds
  23791. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23792. Scene.DoubleClickDelay = 300; // in milliseconds
  23793. /** If you need to check double click without raising a single click at first click, enable this flag */
  23794. Scene.ExclusiveDoubleClickMode = false;
  23795. return Scene;
  23796. }());
  23797. BABYLON.Scene = Scene;
  23798. })(BABYLON || (BABYLON = {}));
  23799. //# sourceMappingURL=babylon.scene.js.map
  23800. var BABYLON;
  23801. (function (BABYLON) {
  23802. /**
  23803. * Set of assets to keep when moving a scene into an asset container.
  23804. */
  23805. var KeepAssets = /** @class */ (function () {
  23806. function KeepAssets() {
  23807. /**
  23808. * Cameras to keep.
  23809. */
  23810. this.cameras = new Array();
  23811. /**
  23812. * Lights to keep.
  23813. */
  23814. this.lights = new Array();
  23815. /**
  23816. * Meshes to keep.
  23817. */
  23818. this.meshes = new Array();
  23819. /**
  23820. * Skeletons to keep.
  23821. */
  23822. this.skeletons = new Array();
  23823. /**
  23824. * ParticleSystems to keep.
  23825. */
  23826. this.particleSystems = new Array();
  23827. /**
  23828. * Animations to keep.
  23829. */
  23830. this.animations = new Array();
  23831. /**
  23832. * MultiMaterials to keep.
  23833. */
  23834. this.multiMaterials = new Array();
  23835. /**
  23836. * Materials to keep.
  23837. */
  23838. this.materials = new Array();
  23839. /**
  23840. * MorphTargetManagers to keep.
  23841. */
  23842. this.morphTargetManagers = new Array();
  23843. /**
  23844. * Geometries to keep.
  23845. */
  23846. this.geometries = new Array();
  23847. /**
  23848. * TransformNodes to keep.
  23849. */
  23850. this.transformNodes = new Array();
  23851. /**
  23852. * LensFlareSystems to keep.
  23853. */
  23854. this.lensFlareSystems = new Array();
  23855. /**
  23856. * ShadowGenerators to keep.
  23857. */
  23858. this.shadowGenerators = new Array();
  23859. /**
  23860. * ActionManagers to keep.
  23861. */
  23862. this.actionManagers = new Array();
  23863. /**
  23864. * Sounds to keep.
  23865. */
  23866. this.sounds = new Array();
  23867. }
  23868. return KeepAssets;
  23869. }());
  23870. BABYLON.KeepAssets = KeepAssets;
  23871. /**
  23872. * Container with a set of assets that can be added or removed from a scene.
  23873. */
  23874. var AssetContainer = /** @class */ (function () {
  23875. /**
  23876. * Instantiates an AssetContainer.
  23877. * @param scene The scene the AssetContainer belongs to.
  23878. */
  23879. function AssetContainer(scene) {
  23880. // Objects
  23881. /**
  23882. * Cameras populated in the container.
  23883. */
  23884. this.cameras = new Array();
  23885. /**
  23886. * Lights populated in the container.
  23887. */
  23888. this.lights = new Array();
  23889. /**
  23890. * Meshes populated in the container.
  23891. */
  23892. this.meshes = new Array();
  23893. /**
  23894. * Skeletons populated in the container.
  23895. */
  23896. this.skeletons = new Array();
  23897. /**
  23898. * ParticleSystems populated in the container.
  23899. */
  23900. this.particleSystems = new Array();
  23901. /**
  23902. * Animations populated in the container.
  23903. */
  23904. this.animations = new Array();
  23905. /**
  23906. * MultiMaterials populated in the container.
  23907. */
  23908. this.multiMaterials = new Array();
  23909. /**
  23910. * Materials populated in the container.
  23911. */
  23912. this.materials = new Array();
  23913. /**
  23914. * MorphTargetManagers populated in the container.
  23915. */
  23916. this.morphTargetManagers = new Array();
  23917. /**
  23918. * Geometries populated in the container.
  23919. */
  23920. this.geometries = new Array();
  23921. /**
  23922. * TransformNodes populated in the container.
  23923. */
  23924. this.transformNodes = new Array();
  23925. /**
  23926. * LensFlareSystems populated in the container.
  23927. */
  23928. this.lensFlareSystems = new Array();
  23929. /**
  23930. * ShadowGenerators populated in the container.
  23931. */
  23932. this.shadowGenerators = new Array();
  23933. /**
  23934. * ActionManagers populated in the container.
  23935. */
  23936. this.actionManagers = new Array();
  23937. /**
  23938. * Sounds populated in the container.
  23939. */
  23940. this.sounds = new Array();
  23941. this.scene = scene;
  23942. }
  23943. /**
  23944. * Adds all the assets from the container to the scene.
  23945. */
  23946. AssetContainer.prototype.addAllToScene = function () {
  23947. var _this = this;
  23948. this.cameras.forEach(function (o) {
  23949. _this.scene.addCamera(o);
  23950. });
  23951. this.lights.forEach(function (o) {
  23952. _this.scene.addLight(o);
  23953. });
  23954. this.meshes.forEach(function (o) {
  23955. _this.scene.addMesh(o);
  23956. });
  23957. this.skeletons.forEach(function (o) {
  23958. _this.scene.addSkeleton(o);
  23959. });
  23960. this.particleSystems.forEach(function (o) {
  23961. _this.scene.addParticleSystem(o);
  23962. });
  23963. this.animations.forEach(function (o) {
  23964. _this.scene.addAnimation(o);
  23965. });
  23966. this.multiMaterials.forEach(function (o) {
  23967. _this.scene.addMultiMaterial(o);
  23968. });
  23969. this.materials.forEach(function (o) {
  23970. _this.scene.addMaterial(o);
  23971. });
  23972. this.morphTargetManagers.forEach(function (o) {
  23973. _this.scene.addMorphTargetManager(o);
  23974. });
  23975. this.geometries.forEach(function (o) {
  23976. _this.scene.addGeometry(o);
  23977. });
  23978. this.transformNodes.forEach(function (o) {
  23979. _this.scene.addTransformNode(o);
  23980. });
  23981. this.lensFlareSystems.forEach(function (o) {
  23982. _this.scene.addLensFlareSystem(o);
  23983. });
  23984. this.actionManagers.forEach(function (o) {
  23985. _this.scene.addActionManager(o);
  23986. });
  23987. this.sounds.forEach(function (o) {
  23988. o.play();
  23989. o.autoplay = true;
  23990. _this.scene.mainSoundTrack.AddSound(o);
  23991. });
  23992. };
  23993. /**
  23994. * Removes all the assets in the container from the scene
  23995. */
  23996. AssetContainer.prototype.removeAllFromScene = function () {
  23997. var _this = this;
  23998. this.cameras.forEach(function (o) {
  23999. _this.scene.removeCamera(o);
  24000. });
  24001. this.lights.forEach(function (o) {
  24002. _this.scene.removeLight(o);
  24003. });
  24004. this.meshes.forEach(function (o) {
  24005. _this.scene.removeMesh(o);
  24006. });
  24007. this.skeletons.forEach(function (o) {
  24008. _this.scene.removeSkeleton(o);
  24009. });
  24010. this.particleSystems.forEach(function (o) {
  24011. _this.scene.removeParticleSystem(o);
  24012. });
  24013. this.animations.forEach(function (o) {
  24014. _this.scene.removeAnimation(o);
  24015. });
  24016. this.multiMaterials.forEach(function (o) {
  24017. _this.scene.removeMultiMaterial(o);
  24018. });
  24019. this.materials.forEach(function (o) {
  24020. _this.scene.removeMaterial(o);
  24021. });
  24022. this.morphTargetManagers.forEach(function (o) {
  24023. _this.scene.removeMorphTargetManager(o);
  24024. });
  24025. this.geometries.forEach(function (o) {
  24026. _this.scene.removeGeometry(o);
  24027. });
  24028. this.transformNodes.forEach(function (o) {
  24029. _this.scene.removeTransformNode(o);
  24030. });
  24031. this.lensFlareSystems.forEach(function (o) {
  24032. _this.scene.removeLensFlareSystem(o);
  24033. });
  24034. this.actionManagers.forEach(function (o) {
  24035. _this.scene.removeActionManager(o);
  24036. });
  24037. this.sounds.forEach(function (o) {
  24038. o.stop();
  24039. o.autoplay = false;
  24040. _this.scene.mainSoundTrack.RemoveSound(o);
  24041. });
  24042. };
  24043. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  24044. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  24045. var asset = sourceAssets_1[_i];
  24046. var move = true;
  24047. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  24048. var keepAsset = keepAssets_1[_a];
  24049. if (asset === keepAsset) {
  24050. move = false;
  24051. break;
  24052. }
  24053. }
  24054. if (move) {
  24055. targetAssets.push(asset);
  24056. }
  24057. }
  24058. };
  24059. /**
  24060. * Removes all the assets contained in the scene and adds them to the container.
  24061. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  24062. */
  24063. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  24064. if (keepAssets === undefined) {
  24065. keepAssets = new KeepAssets();
  24066. }
  24067. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  24068. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  24069. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  24070. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  24071. Array.prototype.push.apply(this.actionManagers, this.scene._actionManagers);
  24072. Array.prototype.push.apply(this.animations, this.scene.animations);
  24073. Array.prototype.push.apply(this.lensFlareSystems, this.scene.lensFlareSystems);
  24074. Array.prototype.push.apply(this.lights, this.scene.lights);
  24075. Array.prototype.push.apply(this.morphTargetManagers, this.scene.morphTargetManagers);
  24076. Array.prototype.push.apply(this.multiMaterials, this.scene.multiMaterials);
  24077. Array.prototype.push.apply(this.skeletons, this.scene.skeletons);
  24078. Array.prototype.push.apply(this.particleSystems, this.scene.particleSystems);
  24079. Array.prototype.push.apply(this.sounds, this.scene.mainSoundTrack.soundCollection);
  24080. Array.prototype.push.apply(this.transformNodes, this.scene.transformNodes);
  24081. this.removeAllFromScene();
  24082. };
  24083. return AssetContainer;
  24084. }());
  24085. BABYLON.AssetContainer = AssetContainer;
  24086. })(BABYLON || (BABYLON = {}));
  24087. //# sourceMappingURL=babylon.assetContainer.js.map
  24088. var BABYLON;
  24089. (function (BABYLON) {
  24090. var Buffer = /** @class */ (function () {
  24091. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  24092. if (instanced === void 0) { instanced = false; }
  24093. if (engine instanceof BABYLON.Mesh) {
  24094. this._engine = engine.getScene().getEngine();
  24095. }
  24096. else {
  24097. this._engine = engine;
  24098. }
  24099. this._updatable = updatable;
  24100. this._data = data;
  24101. this._strideSize = stride;
  24102. if (!postponeInternalCreation) {
  24103. this.create();
  24104. }
  24105. this._instanced = instanced;
  24106. this._instanceDivisor = instanced ? 1 : 0;
  24107. }
  24108. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  24109. // a lot of these parameters are ignored as they are overriden by the buffer
  24110. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  24111. };
  24112. // Properties
  24113. Buffer.prototype.isUpdatable = function () {
  24114. return this._updatable;
  24115. };
  24116. Buffer.prototype.getData = function () {
  24117. return this._data;
  24118. };
  24119. Buffer.prototype.getBuffer = function () {
  24120. return this._buffer;
  24121. };
  24122. Buffer.prototype.getStrideSize = function () {
  24123. return this._strideSize;
  24124. };
  24125. Buffer.prototype.getIsInstanced = function () {
  24126. return this._instanced;
  24127. };
  24128. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  24129. get: function () {
  24130. return this._instanceDivisor;
  24131. },
  24132. set: function (value) {
  24133. this._instanceDivisor = value;
  24134. if (value == 0) {
  24135. this._instanced = false;
  24136. }
  24137. else {
  24138. this._instanced = true;
  24139. }
  24140. },
  24141. enumerable: true,
  24142. configurable: true
  24143. });
  24144. // Methods
  24145. Buffer.prototype.create = function (data) {
  24146. if (data === void 0) { data = null; }
  24147. if (!data && this._buffer) {
  24148. return; // nothing to do
  24149. }
  24150. data = data || this._data;
  24151. if (!data) {
  24152. return;
  24153. }
  24154. if (!this._buffer) {
  24155. if (this._updatable) {
  24156. this._buffer = this._engine.createDynamicVertexBuffer(data);
  24157. this._data = data;
  24158. }
  24159. else {
  24160. this._buffer = this._engine.createVertexBuffer(data);
  24161. }
  24162. }
  24163. else if (this._updatable) {
  24164. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  24165. this._data = data;
  24166. }
  24167. };
  24168. Buffer.prototype._rebuild = function () {
  24169. this._buffer = null;
  24170. this.create(this._data);
  24171. };
  24172. Buffer.prototype.update = function (data) {
  24173. this.create(data);
  24174. };
  24175. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  24176. if (!this._buffer) {
  24177. return;
  24178. }
  24179. if (this._updatable) {
  24180. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  24181. this._data = null;
  24182. }
  24183. };
  24184. Buffer.prototype.dispose = function () {
  24185. if (!this._buffer) {
  24186. return;
  24187. }
  24188. if (this._engine._releaseBuffer(this._buffer)) {
  24189. this._buffer = null;
  24190. }
  24191. };
  24192. return Buffer;
  24193. }());
  24194. BABYLON.Buffer = Buffer;
  24195. })(BABYLON || (BABYLON = {}));
  24196. //# sourceMappingURL=babylon.buffer.js.map
  24197. var BABYLON;
  24198. (function (BABYLON) {
  24199. var VertexBuffer = /** @class */ (function () {
  24200. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  24201. if (!stride) {
  24202. // Deduce stride from kind
  24203. switch (kind) {
  24204. case VertexBuffer.PositionKind:
  24205. stride = 3;
  24206. break;
  24207. case VertexBuffer.NormalKind:
  24208. stride = 3;
  24209. break;
  24210. case VertexBuffer.UVKind:
  24211. case VertexBuffer.UV2Kind:
  24212. case VertexBuffer.UV3Kind:
  24213. case VertexBuffer.UV4Kind:
  24214. case VertexBuffer.UV5Kind:
  24215. case VertexBuffer.UV6Kind:
  24216. stride = 2;
  24217. break;
  24218. case VertexBuffer.TangentKind:
  24219. case VertexBuffer.ColorKind:
  24220. stride = 4;
  24221. break;
  24222. case VertexBuffer.MatricesIndicesKind:
  24223. case VertexBuffer.MatricesIndicesExtraKind:
  24224. stride = 4;
  24225. break;
  24226. case VertexBuffer.MatricesWeightsKind:
  24227. case VertexBuffer.MatricesWeightsExtraKind:
  24228. default:
  24229. stride = 4;
  24230. break;
  24231. }
  24232. }
  24233. if (data instanceof BABYLON.Buffer) {
  24234. if (!stride) {
  24235. stride = data.getStrideSize();
  24236. }
  24237. this._buffer = data;
  24238. this._ownsBuffer = false;
  24239. }
  24240. else {
  24241. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  24242. this._ownsBuffer = true;
  24243. }
  24244. this._stride = stride;
  24245. this._offset = offset ? offset : 0;
  24246. this._size = size ? size : stride;
  24247. this._kind = kind;
  24248. }
  24249. VertexBuffer.prototype._rebuild = function () {
  24250. if (!this._buffer) {
  24251. return;
  24252. }
  24253. this._buffer._rebuild();
  24254. };
  24255. /**
  24256. * Returns the kind of the VertexBuffer (string).
  24257. */
  24258. VertexBuffer.prototype.getKind = function () {
  24259. return this._kind;
  24260. };
  24261. // Properties
  24262. /**
  24263. * Boolean : is the VertexBuffer updatable ?
  24264. */
  24265. VertexBuffer.prototype.isUpdatable = function () {
  24266. return this._buffer.isUpdatable();
  24267. };
  24268. /**
  24269. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  24270. */
  24271. VertexBuffer.prototype.getData = function () {
  24272. return this._buffer.getData();
  24273. };
  24274. /**
  24275. * Returns the WebGLBuffer associated to the VertexBuffer.
  24276. */
  24277. VertexBuffer.prototype.getBuffer = function () {
  24278. return this._buffer.getBuffer();
  24279. };
  24280. /**
  24281. * Returns the stride of the VertexBuffer (integer).
  24282. */
  24283. VertexBuffer.prototype.getStrideSize = function () {
  24284. return this._stride;
  24285. };
  24286. /**
  24287. * Returns the offset (integer).
  24288. */
  24289. VertexBuffer.prototype.getOffset = function () {
  24290. return this._offset;
  24291. };
  24292. /**
  24293. * Returns the VertexBuffer total size (integer).
  24294. */
  24295. VertexBuffer.prototype.getSize = function () {
  24296. return this._size;
  24297. };
  24298. /**
  24299. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  24300. */
  24301. VertexBuffer.prototype.getIsInstanced = function () {
  24302. return this._buffer.getIsInstanced();
  24303. };
  24304. /**
  24305. * Returns the instancing divisor, zero for non-instanced (integer).
  24306. */
  24307. VertexBuffer.prototype.getInstanceDivisor = function () {
  24308. return this._buffer.instanceDivisor;
  24309. };
  24310. // Methods
  24311. /**
  24312. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  24313. * Returns the created WebGLBuffer.
  24314. */
  24315. VertexBuffer.prototype.create = function (data) {
  24316. return this._buffer.create(data);
  24317. };
  24318. /**
  24319. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24320. * This function will create a new buffer if the current one is not updatable
  24321. * Returns the updated WebGLBuffer.
  24322. */
  24323. VertexBuffer.prototype.update = function (data) {
  24324. return this._buffer.update(data);
  24325. };
  24326. /**
  24327. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24328. * Returns the directly updated WebGLBuffer.
  24329. */
  24330. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  24331. return this._buffer.updateDirectly(data, offset);
  24332. };
  24333. /**
  24334. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  24335. */
  24336. VertexBuffer.prototype.dispose = function () {
  24337. if (this._ownsBuffer) {
  24338. this._buffer.dispose();
  24339. }
  24340. };
  24341. Object.defineProperty(VertexBuffer, "PositionKind", {
  24342. get: function () {
  24343. return VertexBuffer._PositionKind;
  24344. },
  24345. enumerable: true,
  24346. configurable: true
  24347. });
  24348. Object.defineProperty(VertexBuffer, "NormalKind", {
  24349. get: function () {
  24350. return VertexBuffer._NormalKind;
  24351. },
  24352. enumerable: true,
  24353. configurable: true
  24354. });
  24355. Object.defineProperty(VertexBuffer, "TangentKind", {
  24356. get: function () {
  24357. return VertexBuffer._TangentKind;
  24358. },
  24359. enumerable: true,
  24360. configurable: true
  24361. });
  24362. Object.defineProperty(VertexBuffer, "UVKind", {
  24363. get: function () {
  24364. return VertexBuffer._UVKind;
  24365. },
  24366. enumerable: true,
  24367. configurable: true
  24368. });
  24369. Object.defineProperty(VertexBuffer, "UV2Kind", {
  24370. get: function () {
  24371. return VertexBuffer._UV2Kind;
  24372. },
  24373. enumerable: true,
  24374. configurable: true
  24375. });
  24376. Object.defineProperty(VertexBuffer, "UV3Kind", {
  24377. get: function () {
  24378. return VertexBuffer._UV3Kind;
  24379. },
  24380. enumerable: true,
  24381. configurable: true
  24382. });
  24383. Object.defineProperty(VertexBuffer, "UV4Kind", {
  24384. get: function () {
  24385. return VertexBuffer._UV4Kind;
  24386. },
  24387. enumerable: true,
  24388. configurable: true
  24389. });
  24390. Object.defineProperty(VertexBuffer, "UV5Kind", {
  24391. get: function () {
  24392. return VertexBuffer._UV5Kind;
  24393. },
  24394. enumerable: true,
  24395. configurable: true
  24396. });
  24397. Object.defineProperty(VertexBuffer, "UV6Kind", {
  24398. get: function () {
  24399. return VertexBuffer._UV6Kind;
  24400. },
  24401. enumerable: true,
  24402. configurable: true
  24403. });
  24404. Object.defineProperty(VertexBuffer, "ColorKind", {
  24405. get: function () {
  24406. return VertexBuffer._ColorKind;
  24407. },
  24408. enumerable: true,
  24409. configurable: true
  24410. });
  24411. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  24412. get: function () {
  24413. return VertexBuffer._MatricesIndicesKind;
  24414. },
  24415. enumerable: true,
  24416. configurable: true
  24417. });
  24418. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  24419. get: function () {
  24420. return VertexBuffer._MatricesWeightsKind;
  24421. },
  24422. enumerable: true,
  24423. configurable: true
  24424. });
  24425. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  24426. get: function () {
  24427. return VertexBuffer._MatricesIndicesExtraKind;
  24428. },
  24429. enumerable: true,
  24430. configurable: true
  24431. });
  24432. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  24433. get: function () {
  24434. return VertexBuffer._MatricesWeightsExtraKind;
  24435. },
  24436. enumerable: true,
  24437. configurable: true
  24438. });
  24439. // Enums
  24440. VertexBuffer._PositionKind = "position";
  24441. VertexBuffer._NormalKind = "normal";
  24442. VertexBuffer._TangentKind = "tangent";
  24443. VertexBuffer._UVKind = "uv";
  24444. VertexBuffer._UV2Kind = "uv2";
  24445. VertexBuffer._UV3Kind = "uv3";
  24446. VertexBuffer._UV4Kind = "uv4";
  24447. VertexBuffer._UV5Kind = "uv5";
  24448. VertexBuffer._UV6Kind = "uv6";
  24449. VertexBuffer._ColorKind = "color";
  24450. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  24451. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  24452. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  24453. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  24454. return VertexBuffer;
  24455. }());
  24456. BABYLON.VertexBuffer = VertexBuffer;
  24457. })(BABYLON || (BABYLON = {}));
  24458. //# sourceMappingURL=babylon.vertexBuffer.js.map
  24459. var BABYLON;
  24460. (function (BABYLON) {
  24461. /**
  24462. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  24463. */
  24464. var DummyInternalTextureTracker = /** @class */ (function () {
  24465. function DummyInternalTextureTracker() {
  24466. /**
  24467. * Gets or set the previous tracker in the list
  24468. */
  24469. this.previous = null;
  24470. /**
  24471. * Gets or set the next tracker in the list
  24472. */
  24473. this.next = null;
  24474. }
  24475. return DummyInternalTextureTracker;
  24476. }());
  24477. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  24478. })(BABYLON || (BABYLON = {}));
  24479. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  24480. var BABYLON;
  24481. (function (BABYLON) {
  24482. /**
  24483. * Class used to store data associated with WebGL texture data for the engine
  24484. * This class should not be used directly
  24485. */
  24486. var InternalTexture = /** @class */ (function () {
  24487. /**
  24488. * Creates a new InternalTexture
  24489. * @param engine defines the engine to use
  24490. * @param dataSource defines the type of data that will be used
  24491. */
  24492. function InternalTexture(engine, dataSource) {
  24493. /**
  24494. * Observable called when the texture is loaded
  24495. */
  24496. this.onLoadedObservable = new BABYLON.Observable();
  24497. /**
  24498. * Gets or set the previous tracker in the list
  24499. */
  24500. this.previous = null;
  24501. /**
  24502. * Gets or set the next tracker in the list
  24503. */
  24504. this.next = null;
  24505. // Private
  24506. /** @ignore */
  24507. this._initialSlot = -1;
  24508. /** @ignore */
  24509. this._designatedSlot = -1;
  24510. /** @ignore */
  24511. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  24512. /** @ignore */
  24513. this._references = 1;
  24514. this._engine = engine;
  24515. this._dataSource = dataSource;
  24516. this._webGLTexture = engine._createTexture();
  24517. }
  24518. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  24519. /**
  24520. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  24521. */
  24522. get: function () {
  24523. return this._dataSource;
  24524. },
  24525. enumerable: true,
  24526. configurable: true
  24527. });
  24528. /**
  24529. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  24530. */
  24531. InternalTexture.prototype.incrementReferences = function () {
  24532. this._references++;
  24533. };
  24534. /**
  24535. * Change the size of the texture (not the size of the content)
  24536. * @param width defines the new width
  24537. * @param height defines the new height
  24538. * @param depth defines the new depth (1 by default)
  24539. */
  24540. InternalTexture.prototype.updateSize = function (width, height, depth) {
  24541. if (depth === void 0) { depth = 1; }
  24542. this.width = width;
  24543. this.height = height;
  24544. this.depth = depth;
  24545. this.baseWidth = width;
  24546. this.baseHeight = height;
  24547. this.baseDepth = depth;
  24548. this._size = width * height * depth;
  24549. };
  24550. /** @ignore */
  24551. InternalTexture.prototype._rebuild = function () {
  24552. var _this = this;
  24553. var proxy;
  24554. this.isReady = false;
  24555. this._cachedCoordinatesMode = null;
  24556. this._cachedWrapU = null;
  24557. this._cachedWrapV = null;
  24558. this._cachedAnisotropicFilteringLevel = null;
  24559. switch (this._dataSource) {
  24560. case InternalTexture.DATASOURCE_TEMP:
  24561. return;
  24562. case InternalTexture.DATASOURCE_URL:
  24563. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  24564. _this.isReady = true;
  24565. }, null, this._buffer, undefined, this.format);
  24566. proxy._swapAndDie(this);
  24567. return;
  24568. case InternalTexture.DATASOURCE_RAW:
  24569. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24570. proxy._swapAndDie(this);
  24571. this.isReady = true;
  24572. return;
  24573. case InternalTexture.DATASOURCE_RAW3D:
  24574. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24575. proxy._swapAndDie(this);
  24576. this.isReady = true;
  24577. return;
  24578. case InternalTexture.DATASOURCE_DYNAMIC:
  24579. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  24580. proxy._swapAndDie(this);
  24581. // The engine will make sure to update content so no need to flag it as isReady = true
  24582. return;
  24583. case InternalTexture.DATASOURCE_RENDERTARGET:
  24584. var options = new BABYLON.RenderTargetCreationOptions();
  24585. options.generateDepthBuffer = this._generateDepthBuffer;
  24586. options.generateMipMaps = this.generateMipMaps;
  24587. options.generateStencilBuffer = this._generateStencilBuffer;
  24588. options.samplingMode = this.samplingMode;
  24589. options.type = this.type;
  24590. if (this.isCube) {
  24591. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  24592. }
  24593. else {
  24594. var size = {
  24595. width: this.width,
  24596. height: this.height
  24597. };
  24598. proxy = this._engine.createRenderTargetTexture(size, options);
  24599. }
  24600. proxy._swapAndDie(this);
  24601. this.isReady = true;
  24602. return;
  24603. case InternalTexture.DATASOURCE_CUBE:
  24604. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  24605. _this.isReady = true;
  24606. }, null, this.format, this._extension);
  24607. proxy._swapAndDie(this);
  24608. return;
  24609. case InternalTexture.DATASOURCE_CUBERAW:
  24610. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24611. proxy._swapAndDie(this);
  24612. this.isReady = true;
  24613. return;
  24614. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  24615. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  24616. if (proxy) {
  24617. proxy._swapAndDie(_this);
  24618. }
  24619. _this.isReady = true;
  24620. }, null, this.format, this._extension);
  24621. return;
  24622. }
  24623. };
  24624. InternalTexture.prototype._swapAndDie = function (target) {
  24625. target._webGLTexture = this._webGLTexture;
  24626. if (this._framebuffer) {
  24627. target._framebuffer = this._framebuffer;
  24628. }
  24629. if (this._depthStencilBuffer) {
  24630. target._depthStencilBuffer = this._depthStencilBuffer;
  24631. }
  24632. if (this._lodTextureHigh) {
  24633. if (target._lodTextureHigh) {
  24634. target._lodTextureHigh.dispose();
  24635. }
  24636. target._lodTextureHigh = this._lodTextureHigh;
  24637. }
  24638. if (this._lodTextureMid) {
  24639. if (target._lodTextureMid) {
  24640. target._lodTextureMid.dispose();
  24641. }
  24642. target._lodTextureMid = this._lodTextureMid;
  24643. }
  24644. if (this._lodTextureLow) {
  24645. if (target._lodTextureLow) {
  24646. target._lodTextureLow.dispose();
  24647. }
  24648. target._lodTextureLow = this._lodTextureLow;
  24649. }
  24650. var cache = this._engine.getLoadedTexturesCache();
  24651. var index = cache.indexOf(this);
  24652. if (index !== -1) {
  24653. cache.splice(index, 1);
  24654. }
  24655. };
  24656. /**
  24657. * Dispose the current allocated resources
  24658. */
  24659. InternalTexture.prototype.dispose = function () {
  24660. if (!this._webGLTexture) {
  24661. return;
  24662. }
  24663. this._references--;
  24664. if (this._references === 0) {
  24665. this._engine._releaseTexture(this);
  24666. this._webGLTexture = null;
  24667. this.previous = null;
  24668. this.next = null;
  24669. }
  24670. };
  24671. /**
  24672. * The source of the texture data is unknown
  24673. */
  24674. InternalTexture.DATASOURCE_UNKNOWN = 0;
  24675. /**
  24676. * Texture data comes from an URL
  24677. */
  24678. InternalTexture.DATASOURCE_URL = 1;
  24679. /**
  24680. * Texture data is only used for temporary storage
  24681. */
  24682. InternalTexture.DATASOURCE_TEMP = 2;
  24683. /**
  24684. * Texture data comes from raw data (ArrayBuffer)
  24685. */
  24686. InternalTexture.DATASOURCE_RAW = 3;
  24687. /**
  24688. * Texture content is dynamic (video or dynamic texture)
  24689. */
  24690. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24691. /**
  24692. * Texture content is generated by rendering to it
  24693. */
  24694. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24695. /**
  24696. * Texture content is part of a multi render target process
  24697. */
  24698. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24699. /**
  24700. * Texture data comes from a cube data file
  24701. */
  24702. InternalTexture.DATASOURCE_CUBE = 7;
  24703. /**
  24704. * Texture data comes from a raw cube data
  24705. */
  24706. InternalTexture.DATASOURCE_CUBERAW = 8;
  24707. /**
  24708. * Texture data come from a prefiltered cube data file
  24709. */
  24710. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24711. /**
  24712. * Texture content is raw 3D data
  24713. */
  24714. InternalTexture.DATASOURCE_RAW3D = 10;
  24715. return InternalTexture;
  24716. }());
  24717. BABYLON.InternalTexture = InternalTexture;
  24718. })(BABYLON || (BABYLON = {}));
  24719. //# sourceMappingURL=babylon.internalTexture.js.map
  24720. var BABYLON;
  24721. (function (BABYLON) {
  24722. var BaseTexture = /** @class */ (function () {
  24723. function BaseTexture(scene) {
  24724. this._hasAlpha = false;
  24725. this.getAlphaFromRGB = false;
  24726. this.level = 1;
  24727. this.coordinatesIndex = 0;
  24728. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24729. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24730. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24731. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  24732. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  24733. this.isCube = false;
  24734. this.is3D = false;
  24735. this.gammaSpace = true;
  24736. this.invertZ = false;
  24737. this.lodLevelInAlpha = false;
  24738. this.lodGenerationOffset = 0.0;
  24739. this.lodGenerationScale = 0.8;
  24740. this.isRenderTarget = false;
  24741. this.animations = new Array();
  24742. /**
  24743. * An event triggered when the texture is disposed.
  24744. * @type {BABYLON.Observable}
  24745. */
  24746. this.onDisposeObservable = new BABYLON.Observable();
  24747. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24748. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24749. if (this._scene) {
  24750. this._scene.textures.push(this);
  24751. }
  24752. this._uid = null;
  24753. }
  24754. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  24755. get: function () {
  24756. return this._hasAlpha;
  24757. },
  24758. set: function (value) {
  24759. if (this._hasAlpha === value) {
  24760. return;
  24761. }
  24762. this._hasAlpha = value;
  24763. if (this._scene) {
  24764. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  24765. }
  24766. },
  24767. enumerable: true,
  24768. configurable: true
  24769. });
  24770. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  24771. get: function () {
  24772. return this._coordinatesMode;
  24773. },
  24774. set: function (value) {
  24775. if (this._coordinatesMode === value) {
  24776. return;
  24777. }
  24778. this._coordinatesMode = value;
  24779. if (this._scene) {
  24780. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24781. }
  24782. },
  24783. enumerable: true,
  24784. configurable: true
  24785. });
  24786. Object.defineProperty(BaseTexture.prototype, "uid", {
  24787. get: function () {
  24788. if (!this._uid) {
  24789. this._uid = BABYLON.Tools.RandomId();
  24790. }
  24791. return this._uid;
  24792. },
  24793. enumerable: true,
  24794. configurable: true
  24795. });
  24796. BaseTexture.prototype.toString = function () {
  24797. return this.name;
  24798. };
  24799. BaseTexture.prototype.getClassName = function () {
  24800. return "BaseTexture";
  24801. };
  24802. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24803. set: function (callback) {
  24804. if (this._onDisposeObserver) {
  24805. this.onDisposeObservable.remove(this._onDisposeObserver);
  24806. }
  24807. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24808. },
  24809. enumerable: true,
  24810. configurable: true
  24811. });
  24812. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  24813. get: function () {
  24814. return true;
  24815. },
  24816. enumerable: true,
  24817. configurable: true
  24818. });
  24819. BaseTexture.prototype.getScene = function () {
  24820. return this._scene;
  24821. };
  24822. BaseTexture.prototype.getTextureMatrix = function () {
  24823. return BABYLON.Matrix.IdentityReadOnly;
  24824. };
  24825. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24826. return BABYLON.Matrix.IdentityReadOnly;
  24827. };
  24828. BaseTexture.prototype.getInternalTexture = function () {
  24829. return this._texture;
  24830. };
  24831. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  24832. return !this.isBlocking || this.isReady();
  24833. };
  24834. BaseTexture.prototype.isReady = function () {
  24835. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24836. this.delayLoad();
  24837. return false;
  24838. }
  24839. if (this._texture) {
  24840. return this._texture.isReady;
  24841. }
  24842. return false;
  24843. };
  24844. BaseTexture.prototype.getSize = function () {
  24845. if (this._texture && this._texture.width) {
  24846. return new BABYLON.Size(this._texture.width, this._texture.height);
  24847. }
  24848. if (this._texture && this._texture._size) {
  24849. return new BABYLON.Size(this._texture._size, this._texture._size);
  24850. }
  24851. return BABYLON.Size.Zero();
  24852. };
  24853. BaseTexture.prototype.getBaseSize = function () {
  24854. if (!this.isReady() || !this._texture)
  24855. return BABYLON.Size.Zero();
  24856. if (this._texture._size) {
  24857. return new BABYLON.Size(this._texture._size, this._texture._size);
  24858. }
  24859. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  24860. };
  24861. BaseTexture.prototype.scale = function (ratio) {
  24862. };
  24863. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24864. get: function () {
  24865. return false;
  24866. },
  24867. enumerable: true,
  24868. configurable: true
  24869. });
  24870. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24871. if (!this._scene) {
  24872. return null;
  24873. }
  24874. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24875. for (var index = 0; index < texturesCache.length; index++) {
  24876. var texturesCacheEntry = texturesCache[index];
  24877. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  24878. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24879. texturesCacheEntry.incrementReferences();
  24880. return texturesCacheEntry;
  24881. }
  24882. }
  24883. }
  24884. return null;
  24885. };
  24886. BaseTexture.prototype._rebuild = function () {
  24887. };
  24888. BaseTexture.prototype.delayLoad = function () {
  24889. };
  24890. BaseTexture.prototype.clone = function () {
  24891. return null;
  24892. };
  24893. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24894. get: function () {
  24895. if (!this._texture) {
  24896. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24897. }
  24898. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24899. },
  24900. enumerable: true,
  24901. configurable: true
  24902. });
  24903. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24904. get: function () {
  24905. if (!this._texture) {
  24906. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24907. }
  24908. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24909. },
  24910. enumerable: true,
  24911. configurable: true
  24912. });
  24913. BaseTexture.prototype.readPixels = function (faceIndex) {
  24914. if (faceIndex === void 0) { faceIndex = 0; }
  24915. if (!this._texture) {
  24916. return null;
  24917. }
  24918. var size = this.getSize();
  24919. var scene = this.getScene();
  24920. if (!scene) {
  24921. return null;
  24922. }
  24923. var engine = scene.getEngine();
  24924. if (this._texture.isCube) {
  24925. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24926. }
  24927. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24928. };
  24929. BaseTexture.prototype.releaseInternalTexture = function () {
  24930. if (this._texture) {
  24931. this._texture.dispose();
  24932. this._texture = null;
  24933. }
  24934. };
  24935. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24936. get: function () {
  24937. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24938. return null;
  24939. }
  24940. if (!this._texture._sphericalPolynomial) {
  24941. this._texture._sphericalPolynomial =
  24942. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24943. }
  24944. return this._texture._sphericalPolynomial;
  24945. },
  24946. set: function (value) {
  24947. if (this._texture) {
  24948. this._texture._sphericalPolynomial = value;
  24949. }
  24950. },
  24951. enumerable: true,
  24952. configurable: true
  24953. });
  24954. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24955. get: function () {
  24956. if (this._texture) {
  24957. return this._texture._lodTextureHigh;
  24958. }
  24959. return null;
  24960. },
  24961. enumerable: true,
  24962. configurable: true
  24963. });
  24964. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24965. get: function () {
  24966. if (this._texture) {
  24967. return this._texture._lodTextureMid;
  24968. }
  24969. return null;
  24970. },
  24971. enumerable: true,
  24972. configurable: true
  24973. });
  24974. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24975. get: function () {
  24976. if (this._texture) {
  24977. return this._texture._lodTextureLow;
  24978. }
  24979. return null;
  24980. },
  24981. enumerable: true,
  24982. configurable: true
  24983. });
  24984. BaseTexture.prototype.dispose = function () {
  24985. if (!this._scene) {
  24986. return;
  24987. }
  24988. // Animations
  24989. this._scene.stopAnimation(this);
  24990. // Remove from scene
  24991. this._scene._removePendingData(this);
  24992. var index = this._scene.textures.indexOf(this);
  24993. if (index >= 0) {
  24994. this._scene.textures.splice(index, 1);
  24995. }
  24996. if (this._texture === undefined) {
  24997. return;
  24998. }
  24999. // Release
  25000. this.releaseInternalTexture();
  25001. // Callback
  25002. this.onDisposeObservable.notifyObservers(this);
  25003. this.onDisposeObservable.clear();
  25004. };
  25005. BaseTexture.prototype.serialize = function () {
  25006. if (!this.name) {
  25007. return null;
  25008. }
  25009. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  25010. // Animations
  25011. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25012. return serializationObject;
  25013. };
  25014. BaseTexture.WhenAllReady = function (textures, callback) {
  25015. var numRemaining = textures.length;
  25016. if (numRemaining === 0) {
  25017. callback();
  25018. return;
  25019. }
  25020. var _loop_1 = function () {
  25021. texture = textures[i];
  25022. if (texture.isReady()) {
  25023. if (--numRemaining === 0) {
  25024. callback();
  25025. }
  25026. }
  25027. else {
  25028. onLoadObservable = texture.onLoadObservable;
  25029. var onLoadCallback_1 = function () {
  25030. onLoadObservable.removeCallback(onLoadCallback_1);
  25031. if (--numRemaining === 0) {
  25032. callback();
  25033. }
  25034. };
  25035. onLoadObservable.add(onLoadCallback_1);
  25036. }
  25037. };
  25038. var texture, onLoadObservable;
  25039. for (var i = 0; i < textures.length; i++) {
  25040. _loop_1();
  25041. }
  25042. };
  25043. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  25044. __decorate([
  25045. BABYLON.serialize()
  25046. ], BaseTexture.prototype, "name", void 0);
  25047. __decorate([
  25048. BABYLON.serialize("hasAlpha")
  25049. ], BaseTexture.prototype, "_hasAlpha", void 0);
  25050. __decorate([
  25051. BABYLON.serialize()
  25052. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  25053. __decorate([
  25054. BABYLON.serialize()
  25055. ], BaseTexture.prototype, "level", void 0);
  25056. __decorate([
  25057. BABYLON.serialize()
  25058. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  25059. __decorate([
  25060. BABYLON.serialize("coordinatesMode")
  25061. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  25062. __decorate([
  25063. BABYLON.serialize()
  25064. ], BaseTexture.prototype, "wrapU", void 0);
  25065. __decorate([
  25066. BABYLON.serialize()
  25067. ], BaseTexture.prototype, "wrapV", void 0);
  25068. __decorate([
  25069. BABYLON.serialize()
  25070. ], BaseTexture.prototype, "wrapR", void 0);
  25071. __decorate([
  25072. BABYLON.serialize()
  25073. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  25074. __decorate([
  25075. BABYLON.serialize()
  25076. ], BaseTexture.prototype, "isCube", void 0);
  25077. __decorate([
  25078. BABYLON.serialize()
  25079. ], BaseTexture.prototype, "is3D", void 0);
  25080. __decorate([
  25081. BABYLON.serialize()
  25082. ], BaseTexture.prototype, "gammaSpace", void 0);
  25083. __decorate([
  25084. BABYLON.serialize()
  25085. ], BaseTexture.prototype, "invertZ", void 0);
  25086. __decorate([
  25087. BABYLON.serialize()
  25088. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  25089. __decorate([
  25090. BABYLON.serialize()
  25091. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  25092. __decorate([
  25093. BABYLON.serialize()
  25094. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  25095. __decorate([
  25096. BABYLON.serialize()
  25097. ], BaseTexture.prototype, "isRenderTarget", void 0);
  25098. return BaseTexture;
  25099. }());
  25100. BABYLON.BaseTexture = BaseTexture;
  25101. })(BABYLON || (BABYLON = {}));
  25102. //# sourceMappingURL=babylon.baseTexture.js.map
  25103. var BABYLON;
  25104. (function (BABYLON) {
  25105. var Texture = /** @class */ (function (_super) {
  25106. __extends(Texture, _super);
  25107. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  25108. if (noMipmap === void 0) { noMipmap = false; }
  25109. if (invertY === void 0) { invertY = true; }
  25110. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25111. if (onLoad === void 0) { onLoad = null; }
  25112. if (onError === void 0) { onError = null; }
  25113. if (buffer === void 0) { buffer = null; }
  25114. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25115. var _this = _super.call(this, scene) || this;
  25116. _this.uOffset = 0;
  25117. _this.vOffset = 0;
  25118. _this.uScale = 1.0;
  25119. _this.vScale = 1.0;
  25120. _this.uAng = 0;
  25121. _this.vAng = 0;
  25122. _this.wAng = 0;
  25123. _this._isBlocking = true;
  25124. _this.name = url || "";
  25125. _this.url = url;
  25126. _this._noMipmap = noMipmap;
  25127. _this._invertY = invertY;
  25128. _this._samplingMode = samplingMode;
  25129. _this._buffer = buffer;
  25130. _this._deleteBuffer = deleteBuffer;
  25131. if (format) {
  25132. _this._format = format;
  25133. }
  25134. scene = _this.getScene();
  25135. if (!scene) {
  25136. return _this;
  25137. }
  25138. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  25139. var load = function () {
  25140. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  25141. _this.onLoadObservable.notifyObservers(_this);
  25142. }
  25143. if (onLoad) {
  25144. onLoad();
  25145. }
  25146. if (!_this.isBlocking && scene) {
  25147. scene.resetCachedMaterial();
  25148. }
  25149. };
  25150. if (!_this.url) {
  25151. _this._delayedOnLoad = load;
  25152. _this._delayedOnError = onError;
  25153. return _this;
  25154. }
  25155. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  25156. if (!_this._texture) {
  25157. if (!scene.useDelayedTextureLoading) {
  25158. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  25159. if (deleteBuffer) {
  25160. delete _this._buffer;
  25161. }
  25162. }
  25163. else {
  25164. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25165. _this._delayedOnLoad = load;
  25166. _this._delayedOnError = onError;
  25167. }
  25168. }
  25169. else {
  25170. if (_this._texture.isReady) {
  25171. BABYLON.Tools.SetImmediate(function () { return load(); });
  25172. }
  25173. else {
  25174. _this._texture.onLoadedObservable.add(load);
  25175. }
  25176. }
  25177. return _this;
  25178. }
  25179. Object.defineProperty(Texture.prototype, "noMipmap", {
  25180. get: function () {
  25181. return this._noMipmap;
  25182. },
  25183. enumerable: true,
  25184. configurable: true
  25185. });
  25186. Object.defineProperty(Texture.prototype, "isBlocking", {
  25187. get: function () {
  25188. return this._isBlocking;
  25189. },
  25190. set: function (value) {
  25191. this._isBlocking = value;
  25192. },
  25193. enumerable: true,
  25194. configurable: true
  25195. });
  25196. Object.defineProperty(Texture.prototype, "samplingMode", {
  25197. get: function () {
  25198. return this._samplingMode;
  25199. },
  25200. enumerable: true,
  25201. configurable: true
  25202. });
  25203. Texture.prototype.updateURL = function (url) {
  25204. this.url = url;
  25205. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25206. this.delayLoad();
  25207. };
  25208. Texture.prototype.delayLoad = function () {
  25209. var _this = this;
  25210. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25211. return;
  25212. }
  25213. var scene = this.getScene();
  25214. if (!scene) {
  25215. return;
  25216. }
  25217. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25218. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  25219. if (!this._texture) {
  25220. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  25221. if (this._deleteBuffer) {
  25222. delete this._buffer;
  25223. }
  25224. }
  25225. else {
  25226. if (this._texture.isReady) {
  25227. BABYLON.Tools.SetImmediate(function () {
  25228. if (!_this._delayedOnLoad) {
  25229. return;
  25230. }
  25231. _this._delayedOnLoad();
  25232. });
  25233. }
  25234. else {
  25235. if (this._delayedOnLoad) {
  25236. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  25237. }
  25238. }
  25239. }
  25240. };
  25241. Texture.prototype.updateSamplingMode = function (samplingMode) {
  25242. if (!this._texture) {
  25243. return;
  25244. }
  25245. var scene = this.getScene();
  25246. if (!scene) {
  25247. return;
  25248. }
  25249. this._samplingMode = samplingMode;
  25250. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  25251. };
  25252. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  25253. x *= this.uScale;
  25254. y *= this.vScale;
  25255. x -= 0.5 * this.uScale;
  25256. y -= 0.5 * this.vScale;
  25257. z -= 0.5;
  25258. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  25259. t.x += 0.5 * this.uScale + this.uOffset;
  25260. t.y += 0.5 * this.vScale + this.vOffset;
  25261. t.z += 0.5;
  25262. };
  25263. Texture.prototype.getTextureMatrix = function () {
  25264. var _this = this;
  25265. if (this.uOffset === this._cachedUOffset &&
  25266. this.vOffset === this._cachedVOffset &&
  25267. this.uScale === this._cachedUScale &&
  25268. this.vScale === this._cachedVScale &&
  25269. this.uAng === this._cachedUAng &&
  25270. this.vAng === this._cachedVAng &&
  25271. this.wAng === this._cachedWAng) {
  25272. return this._cachedTextureMatrix;
  25273. }
  25274. this._cachedUOffset = this.uOffset;
  25275. this._cachedVOffset = this.vOffset;
  25276. this._cachedUScale = this.uScale;
  25277. this._cachedVScale = this.vScale;
  25278. this._cachedUAng = this.uAng;
  25279. this._cachedVAng = this.vAng;
  25280. this._cachedWAng = this.wAng;
  25281. if (!this._cachedTextureMatrix) {
  25282. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25283. this._rowGenerationMatrix = new BABYLON.Matrix();
  25284. this._t0 = BABYLON.Vector3.Zero();
  25285. this._t1 = BABYLON.Vector3.Zero();
  25286. this._t2 = BABYLON.Vector3.Zero();
  25287. }
  25288. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  25289. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  25290. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  25291. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  25292. this._t1.subtractInPlace(this._t0);
  25293. this._t2.subtractInPlace(this._t0);
  25294. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25295. this._cachedTextureMatrix.m[0] = this._t1.x;
  25296. this._cachedTextureMatrix.m[1] = this._t1.y;
  25297. this._cachedTextureMatrix.m[2] = this._t1.z;
  25298. this._cachedTextureMatrix.m[4] = this._t2.x;
  25299. this._cachedTextureMatrix.m[5] = this._t2.y;
  25300. this._cachedTextureMatrix.m[6] = this._t2.z;
  25301. this._cachedTextureMatrix.m[8] = this._t0.x;
  25302. this._cachedTextureMatrix.m[9] = this._t0.y;
  25303. this._cachedTextureMatrix.m[10] = this._t0.z;
  25304. var scene = this.getScene();
  25305. if (!scene) {
  25306. return this._cachedTextureMatrix;
  25307. }
  25308. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25309. return mat.hasTexture(_this);
  25310. });
  25311. return this._cachedTextureMatrix;
  25312. };
  25313. Texture.prototype.getReflectionTextureMatrix = function () {
  25314. var _this = this;
  25315. var scene = this.getScene();
  25316. if (!scene) {
  25317. return this._cachedTextureMatrix;
  25318. }
  25319. if (this.uOffset === this._cachedUOffset &&
  25320. this.vOffset === this._cachedVOffset &&
  25321. this.uScale === this._cachedUScale &&
  25322. this.vScale === this._cachedVScale &&
  25323. this.coordinatesMode === this._cachedCoordinatesMode) {
  25324. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  25325. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  25326. return this._cachedTextureMatrix;
  25327. }
  25328. }
  25329. else {
  25330. return this._cachedTextureMatrix;
  25331. }
  25332. }
  25333. if (!this._cachedTextureMatrix) {
  25334. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25335. }
  25336. if (!this._projectionModeMatrix) {
  25337. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  25338. }
  25339. this._cachedUOffset = this.uOffset;
  25340. this._cachedVOffset = this.vOffset;
  25341. this._cachedUScale = this.uScale;
  25342. this._cachedVScale = this.vScale;
  25343. this._cachedCoordinatesMode = this.coordinatesMode;
  25344. switch (this.coordinatesMode) {
  25345. case Texture.PLANAR_MODE:
  25346. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25347. this._cachedTextureMatrix[0] = this.uScale;
  25348. this._cachedTextureMatrix[5] = this.vScale;
  25349. this._cachedTextureMatrix[12] = this.uOffset;
  25350. this._cachedTextureMatrix[13] = this.vOffset;
  25351. break;
  25352. case Texture.PROJECTION_MODE:
  25353. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  25354. this._projectionModeMatrix.m[0] = 0.5;
  25355. this._projectionModeMatrix.m[5] = -0.5;
  25356. this._projectionModeMatrix.m[10] = 0.0;
  25357. this._projectionModeMatrix.m[12] = 0.5;
  25358. this._projectionModeMatrix.m[13] = 0.5;
  25359. this._projectionModeMatrix.m[14] = 1.0;
  25360. this._projectionModeMatrix.m[15] = 1.0;
  25361. var projectionMatrix = scene.getProjectionMatrix();
  25362. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  25363. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  25364. break;
  25365. default:
  25366. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25367. break;
  25368. }
  25369. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25370. return (mat.getActiveTextures().indexOf(_this) !== -1);
  25371. });
  25372. return this._cachedTextureMatrix;
  25373. };
  25374. Texture.prototype.clone = function () {
  25375. var _this = this;
  25376. return BABYLON.SerializationHelper.Clone(function () {
  25377. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  25378. }, this);
  25379. };
  25380. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  25381. get: function () {
  25382. if (!this._onLoadObservable) {
  25383. this._onLoadObservable = new BABYLON.Observable();
  25384. }
  25385. return this._onLoadObservable;
  25386. },
  25387. enumerable: true,
  25388. configurable: true
  25389. });
  25390. Texture.prototype.serialize = function () {
  25391. var serializationObject = _super.prototype.serialize.call(this);
  25392. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  25393. serializationObject.base64String = this._buffer;
  25394. serializationObject.name = serializationObject.name.replace("data:", "");
  25395. }
  25396. return serializationObject;
  25397. };
  25398. Texture.prototype.getClassName = function () {
  25399. return "Texture";
  25400. };
  25401. Texture.prototype.dispose = function () {
  25402. _super.prototype.dispose.call(this);
  25403. if (this.onLoadObservable) {
  25404. this.onLoadObservable.clear();
  25405. this._onLoadObservable = null;
  25406. }
  25407. this._delayedOnLoad = null;
  25408. this._delayedOnError = null;
  25409. };
  25410. // Statics
  25411. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25412. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25413. if (onLoad === void 0) { onLoad = null; }
  25414. if (onError === void 0) { onError = null; }
  25415. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25416. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  25417. };
  25418. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  25419. if (parsedTexture.customType) {
  25420. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  25421. // Update Sampling Mode
  25422. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  25423. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  25424. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  25425. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  25426. }
  25427. }
  25428. return parsedCustomTexture;
  25429. }
  25430. if (parsedTexture.isCube) {
  25431. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  25432. }
  25433. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  25434. return null;
  25435. }
  25436. var texture = BABYLON.SerializationHelper.Parse(function () {
  25437. var generateMipMaps = true;
  25438. if (parsedTexture.noMipmap) {
  25439. generateMipMaps = false;
  25440. }
  25441. if (parsedTexture.mirrorPlane) {
  25442. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25443. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  25444. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  25445. return mirrorTexture;
  25446. }
  25447. else if (parsedTexture.isRenderTarget) {
  25448. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25449. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  25450. return renderTargetTexture;
  25451. }
  25452. else {
  25453. var texture;
  25454. if (parsedTexture.base64String) {
  25455. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  25456. }
  25457. else {
  25458. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  25459. }
  25460. return texture;
  25461. }
  25462. }, parsedTexture, scene);
  25463. // Update Sampling Mode
  25464. if (parsedTexture.samplingMode) {
  25465. var sampling = parsedTexture.samplingMode;
  25466. if (texture._samplingMode !== sampling) {
  25467. texture.updateSamplingMode(sampling);
  25468. }
  25469. }
  25470. // Animations
  25471. if (parsedTexture.animations) {
  25472. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  25473. var parsedAnimation = parsedTexture.animations[animationIndex];
  25474. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25475. }
  25476. }
  25477. return texture;
  25478. };
  25479. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25480. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25481. if (noMipmap === void 0) { noMipmap = false; }
  25482. if (invertY === void 0) { invertY = true; }
  25483. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25484. if (onLoad === void 0) { onLoad = null; }
  25485. if (onError === void 0) { onError = null; }
  25486. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25487. if (name.substr(0, 5) !== "data:") {
  25488. name = "data:" + name;
  25489. }
  25490. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  25491. };
  25492. // Constants
  25493. Texture.NEAREST_SAMPLINGMODE = 1;
  25494. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  25495. Texture.BILINEAR_SAMPLINGMODE = 2;
  25496. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  25497. Texture.TRILINEAR_SAMPLINGMODE = 3;
  25498. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  25499. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  25500. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  25501. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  25502. Texture.NEAREST_LINEAR = 7;
  25503. Texture.NEAREST_NEAREST = 8;
  25504. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  25505. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  25506. Texture.LINEAR_LINEAR = 11;
  25507. Texture.LINEAR_NEAREST = 12;
  25508. Texture.EXPLICIT_MODE = 0;
  25509. Texture.SPHERICAL_MODE = 1;
  25510. Texture.PLANAR_MODE = 2;
  25511. Texture.CUBIC_MODE = 3;
  25512. Texture.PROJECTION_MODE = 4;
  25513. Texture.SKYBOX_MODE = 5;
  25514. Texture.INVCUBIC_MODE = 6;
  25515. Texture.EQUIRECTANGULAR_MODE = 7;
  25516. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  25517. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  25518. Texture.CLAMP_ADDRESSMODE = 0;
  25519. Texture.WRAP_ADDRESSMODE = 1;
  25520. Texture.MIRROR_ADDRESSMODE = 2;
  25521. __decorate([
  25522. BABYLON.serialize()
  25523. ], Texture.prototype, "url", void 0);
  25524. __decorate([
  25525. BABYLON.serialize()
  25526. ], Texture.prototype, "uOffset", void 0);
  25527. __decorate([
  25528. BABYLON.serialize()
  25529. ], Texture.prototype, "vOffset", void 0);
  25530. __decorate([
  25531. BABYLON.serialize()
  25532. ], Texture.prototype, "uScale", void 0);
  25533. __decorate([
  25534. BABYLON.serialize()
  25535. ], Texture.prototype, "vScale", void 0);
  25536. __decorate([
  25537. BABYLON.serialize()
  25538. ], Texture.prototype, "uAng", void 0);
  25539. __decorate([
  25540. BABYLON.serialize()
  25541. ], Texture.prototype, "vAng", void 0);
  25542. __decorate([
  25543. BABYLON.serialize()
  25544. ], Texture.prototype, "wAng", void 0);
  25545. __decorate([
  25546. BABYLON.serialize()
  25547. ], Texture.prototype, "isBlocking", null);
  25548. return Texture;
  25549. }(BABYLON.BaseTexture));
  25550. BABYLON.Texture = Texture;
  25551. })(BABYLON || (BABYLON = {}));
  25552. //# sourceMappingURL=babylon.texture.js.map
  25553. var BABYLON;
  25554. (function (BABYLON) {
  25555. var _InstancesBatch = /** @class */ (function () {
  25556. function _InstancesBatch() {
  25557. this.mustReturn = false;
  25558. this.visibleInstances = new Array();
  25559. this.renderSelf = new Array();
  25560. }
  25561. return _InstancesBatch;
  25562. }());
  25563. BABYLON._InstancesBatch = _InstancesBatch;
  25564. var Mesh = /** @class */ (function (_super) {
  25565. __extends(Mesh, _super);
  25566. /**
  25567. * @constructor
  25568. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  25569. * @param {Scene} scene The scene to add this mesh to.
  25570. * @param {Node} parent The parent of this mesh, if it has one
  25571. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  25572. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  25573. * When false, achieved by calling a clone(), also passing False.
  25574. * This will make creation of children, recursive.
  25575. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  25576. */
  25577. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  25578. if (scene === void 0) { scene = null; }
  25579. if (parent === void 0) { parent = null; }
  25580. if (source === void 0) { source = null; }
  25581. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25582. var _this = _super.call(this, name, scene) || this;
  25583. // Events
  25584. /**
  25585. * An event triggered before rendering the mesh
  25586. * @type {BABYLON.Observable}
  25587. */
  25588. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25589. /**
  25590. * An event triggered after rendering the mesh
  25591. * @type {BABYLON.Observable}
  25592. */
  25593. _this.onAfterRenderObservable = new BABYLON.Observable();
  25594. /**
  25595. * An event triggered before drawing the mesh
  25596. * @type {BABYLON.Observable}
  25597. */
  25598. _this.onBeforeDrawObservable = new BABYLON.Observable();
  25599. // Members
  25600. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25601. _this.instances = new Array();
  25602. _this._LODLevels = new Array();
  25603. _this._visibleInstances = {};
  25604. _this._renderIdForInstances = new Array();
  25605. _this._batchCache = new _InstancesBatch();
  25606. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  25607. // Use by builder only to know what orientation were the mesh build in.
  25608. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  25609. _this.overrideMaterialSideOrientation = null;
  25610. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  25611. // Will be used to save a source mesh reference, If any
  25612. _this._source = null;
  25613. scene = _this.getScene();
  25614. if (source) {
  25615. // Source mesh
  25616. _this._source = source;
  25617. // Geometry
  25618. if (source._geometry) {
  25619. source._geometry.applyToMesh(_this);
  25620. }
  25621. // Deep copy
  25622. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  25623. // Metadata
  25624. if (source.metadata && source.metadata.clone) {
  25625. _this.metadata = source.metadata.clone();
  25626. }
  25627. else {
  25628. _this.metadata = source.metadata;
  25629. }
  25630. // Tags
  25631. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  25632. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  25633. }
  25634. // Parent
  25635. _this.parent = source.parent;
  25636. // Pivot
  25637. _this.setPivotMatrix(source.getPivotMatrix());
  25638. _this.id = name + "." + source.id;
  25639. // Material
  25640. _this.material = source.material;
  25641. var index;
  25642. if (!doNotCloneChildren) {
  25643. // Children
  25644. var directDescendants = source.getDescendants(true);
  25645. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  25646. var child = directDescendants[index_1];
  25647. if (child.clone) {
  25648. child.clone(name + "." + child.name, _this);
  25649. }
  25650. }
  25651. }
  25652. // Physics clone
  25653. var physicsEngine = _this.getScene().getPhysicsEngine();
  25654. if (clonePhysicsImpostor && physicsEngine) {
  25655. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  25656. if (impostor) {
  25657. _this.physicsImpostor = impostor.clone(_this);
  25658. }
  25659. }
  25660. // Particles
  25661. for (index = 0; index < scene.particleSystems.length; index++) {
  25662. var system = scene.particleSystems[index];
  25663. if (system.emitter === source) {
  25664. system.clone(system.name, _this);
  25665. }
  25666. }
  25667. _this.computeWorldMatrix(true);
  25668. }
  25669. // Parent
  25670. if (parent !== null) {
  25671. _this.parent = parent;
  25672. }
  25673. return _this;
  25674. }
  25675. Object.defineProperty(Mesh, "FRONTSIDE", {
  25676. /**
  25677. * Mesh side orientation : usually the external or front surface
  25678. */
  25679. get: function () {
  25680. return Mesh._FRONTSIDE;
  25681. },
  25682. enumerable: true,
  25683. configurable: true
  25684. });
  25685. Object.defineProperty(Mesh, "BACKSIDE", {
  25686. /**
  25687. * Mesh side orientation : usually the internal or back surface
  25688. */
  25689. get: function () {
  25690. return Mesh._BACKSIDE;
  25691. },
  25692. enumerable: true,
  25693. configurable: true
  25694. });
  25695. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25696. /**
  25697. * Mesh side orientation : both internal and external or front and back surfaces
  25698. */
  25699. get: function () {
  25700. return Mesh._DOUBLESIDE;
  25701. },
  25702. enumerable: true,
  25703. configurable: true
  25704. });
  25705. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25706. /**
  25707. * Mesh side orientation : by default, `FRONTSIDE`
  25708. */
  25709. get: function () {
  25710. return Mesh._DEFAULTSIDE;
  25711. },
  25712. enumerable: true,
  25713. configurable: true
  25714. });
  25715. Object.defineProperty(Mesh, "NO_CAP", {
  25716. /**
  25717. * Mesh cap setting : no cap
  25718. */
  25719. get: function () {
  25720. return Mesh._NO_CAP;
  25721. },
  25722. enumerable: true,
  25723. configurable: true
  25724. });
  25725. Object.defineProperty(Mesh, "CAP_START", {
  25726. /**
  25727. * Mesh cap setting : one cap at the beginning of the mesh
  25728. */
  25729. get: function () {
  25730. return Mesh._CAP_START;
  25731. },
  25732. enumerable: true,
  25733. configurable: true
  25734. });
  25735. Object.defineProperty(Mesh, "CAP_END", {
  25736. /**
  25737. * Mesh cap setting : one cap at the end of the mesh
  25738. */
  25739. get: function () {
  25740. return Mesh._CAP_END;
  25741. },
  25742. enumerable: true,
  25743. configurable: true
  25744. });
  25745. Object.defineProperty(Mesh, "CAP_ALL", {
  25746. /**
  25747. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  25748. */
  25749. get: function () {
  25750. return Mesh._CAP_ALL;
  25751. },
  25752. enumerable: true,
  25753. configurable: true
  25754. });
  25755. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  25756. set: function (callback) {
  25757. if (this._onBeforeDrawObserver) {
  25758. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  25759. }
  25760. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  25761. },
  25762. enumerable: true,
  25763. configurable: true
  25764. });
  25765. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  25766. get: function () {
  25767. return this._morphTargetManager;
  25768. },
  25769. set: function (value) {
  25770. if (this._morphTargetManager === value) {
  25771. return;
  25772. }
  25773. this._morphTargetManager = value;
  25774. this._syncGeometryWithMorphTargetManager();
  25775. },
  25776. enumerable: true,
  25777. configurable: true
  25778. });
  25779. Object.defineProperty(Mesh.prototype, "source", {
  25780. get: function () {
  25781. return this._source;
  25782. },
  25783. enumerable: true,
  25784. configurable: true
  25785. });
  25786. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  25787. get: function () {
  25788. return this._unIndexed;
  25789. },
  25790. set: function (value) {
  25791. if (this._unIndexed !== value) {
  25792. this._unIndexed = value;
  25793. this._markSubMeshesAsAttributesDirty();
  25794. }
  25795. },
  25796. enumerable: true,
  25797. configurable: true
  25798. });
  25799. // Methods
  25800. /**
  25801. * Returns the string "Mesh".
  25802. */
  25803. Mesh.prototype.getClassName = function () {
  25804. return "Mesh";
  25805. };
  25806. /**
  25807. * Returns a string.
  25808. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25809. */
  25810. Mesh.prototype.toString = function (fullDetails) {
  25811. var ret = _super.prototype.toString.call(this, fullDetails);
  25812. ret += ", n vertices: " + this.getTotalVertices();
  25813. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  25814. if (this.animations) {
  25815. for (var i = 0; i < this.animations.length; i++) {
  25816. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  25817. }
  25818. }
  25819. if (fullDetails) {
  25820. if (this._geometry) {
  25821. var ib = this.getIndices();
  25822. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25823. if (vb && ib) {
  25824. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  25825. }
  25826. }
  25827. else {
  25828. ret += ", flat shading: UNKNOWN";
  25829. }
  25830. }
  25831. return ret;
  25832. };
  25833. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  25834. /**
  25835. * True if the mesh has some Levels Of Details (LOD).
  25836. * Returns a boolean.
  25837. */
  25838. get: function () {
  25839. return this._LODLevels.length > 0;
  25840. },
  25841. enumerable: true,
  25842. configurable: true
  25843. });
  25844. /**
  25845. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  25846. * @returns an array of {BABYLON.MeshLODLevel}
  25847. */
  25848. Mesh.prototype.getLODLevels = function () {
  25849. return this._LODLevels;
  25850. };
  25851. Mesh.prototype._sortLODLevels = function () {
  25852. this._LODLevels.sort(function (a, b) {
  25853. if (a.distance < b.distance) {
  25854. return 1;
  25855. }
  25856. if (a.distance > b.distance) {
  25857. return -1;
  25858. }
  25859. return 0;
  25860. });
  25861. };
  25862. /**
  25863. * Add a mesh as LOD level triggered at the given distance.
  25864. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25865. * @param {number} distance The distance from the center of the object to show this level
  25866. * @param {Mesh} mesh The mesh to be added as LOD level
  25867. * @return {Mesh} This mesh (for chaining)
  25868. */
  25869. Mesh.prototype.addLODLevel = function (distance, mesh) {
  25870. if (mesh && mesh._masterMesh) {
  25871. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  25872. return this;
  25873. }
  25874. var level = new BABYLON.MeshLODLevel(distance, mesh);
  25875. this._LODLevels.push(level);
  25876. if (mesh) {
  25877. mesh._masterMesh = this;
  25878. }
  25879. this._sortLODLevels();
  25880. return this;
  25881. };
  25882. /**
  25883. * Returns the LOD level mesh at the passed distance or null if not found.
  25884. * It is related to the method `addLODLevel(distance, mesh)`.
  25885. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25886. * Returns an object Mesh or `null`.
  25887. */
  25888. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  25889. for (var index = 0; index < this._LODLevels.length; index++) {
  25890. var level = this._LODLevels[index];
  25891. if (level.distance === distance) {
  25892. return level.mesh;
  25893. }
  25894. }
  25895. return null;
  25896. };
  25897. /**
  25898. * Remove a mesh from the LOD array
  25899. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25900. * @param {Mesh} mesh The mesh to be removed.
  25901. * @return {Mesh} This mesh (for chaining)
  25902. */
  25903. Mesh.prototype.removeLODLevel = function (mesh) {
  25904. for (var index = 0; index < this._LODLevels.length; index++) {
  25905. if (this._LODLevels[index].mesh === mesh) {
  25906. this._LODLevels.splice(index, 1);
  25907. if (mesh) {
  25908. mesh._masterMesh = null;
  25909. }
  25910. }
  25911. }
  25912. this._sortLODLevels();
  25913. return this;
  25914. };
  25915. /**
  25916. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25917. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25918. */
  25919. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25920. if (!this._LODLevels || this._LODLevels.length === 0) {
  25921. return this;
  25922. }
  25923. var bSphere;
  25924. if (boundingSphere) {
  25925. bSphere = boundingSphere;
  25926. }
  25927. else {
  25928. var boundingInfo = this.getBoundingInfo();
  25929. bSphere = boundingInfo.boundingSphere;
  25930. }
  25931. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25932. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25933. if (this.onLODLevelSelection) {
  25934. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25935. }
  25936. return this;
  25937. }
  25938. for (var index = 0; index < this._LODLevels.length; index++) {
  25939. var level = this._LODLevels[index];
  25940. if (level.distance < distanceToCamera) {
  25941. if (level.mesh) {
  25942. level.mesh._preActivate();
  25943. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25944. }
  25945. if (this.onLODLevelSelection) {
  25946. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25947. }
  25948. return level.mesh;
  25949. }
  25950. }
  25951. if (this.onLODLevelSelection) {
  25952. this.onLODLevelSelection(distanceToCamera, this, this);
  25953. }
  25954. return this;
  25955. };
  25956. Object.defineProperty(Mesh.prototype, "geometry", {
  25957. /**
  25958. * Returns the mesh internal Geometry object.
  25959. */
  25960. get: function () {
  25961. return this._geometry;
  25962. },
  25963. enumerable: true,
  25964. configurable: true
  25965. });
  25966. /**
  25967. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25968. */
  25969. Mesh.prototype.getTotalVertices = function () {
  25970. if (this._geometry === null || this._geometry === undefined) {
  25971. return 0;
  25972. }
  25973. return this._geometry.getTotalVertices();
  25974. };
  25975. /**
  25976. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25977. * 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.
  25978. * You can force the copy with forceCopy === true
  25979. * Returns null if the mesh has no geometry or no vertex buffer.
  25980. * Possible `kind` values :
  25981. * - BABYLON.VertexBuffer.PositionKind
  25982. * - BABYLON.VertexBuffer.UVKind
  25983. * - BABYLON.VertexBuffer.UV2Kind
  25984. * - BABYLON.VertexBuffer.UV3Kind
  25985. * - BABYLON.VertexBuffer.UV4Kind
  25986. * - BABYLON.VertexBuffer.UV5Kind
  25987. * - BABYLON.VertexBuffer.UV6Kind
  25988. * - BABYLON.VertexBuffer.ColorKind
  25989. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25990. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25991. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25992. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25993. */
  25994. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  25995. if (!this._geometry) {
  25996. return null;
  25997. }
  25998. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  25999. };
  26000. /**
  26001. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  26002. * Returns `null` if the mesh has no geometry.
  26003. * Possible `kind` values :
  26004. * - BABYLON.VertexBuffer.PositionKind
  26005. * - BABYLON.VertexBuffer.UVKind
  26006. * - BABYLON.VertexBuffer.UV2Kind
  26007. * - BABYLON.VertexBuffer.UV3Kind
  26008. * - BABYLON.VertexBuffer.UV4Kind
  26009. * - BABYLON.VertexBuffer.UV5Kind
  26010. * - BABYLON.VertexBuffer.UV6Kind
  26011. * - BABYLON.VertexBuffer.ColorKind
  26012. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26013. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26014. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26015. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26016. */
  26017. Mesh.prototype.getVertexBuffer = function (kind) {
  26018. if (!this._geometry) {
  26019. return null;
  26020. }
  26021. return this._geometry.getVertexBuffer(kind);
  26022. };
  26023. /**
  26024. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  26025. * Possible `kind` values :
  26026. * - BABYLON.VertexBuffer.PositionKind
  26027. * - BABYLON.VertexBuffer.UVKind
  26028. * - BABYLON.VertexBuffer.UV2Kind
  26029. * - BABYLON.VertexBuffer.UV3Kind
  26030. * - BABYLON.VertexBuffer.UV4Kind
  26031. * - BABYLON.VertexBuffer.UV5Kind
  26032. * - BABYLON.VertexBuffer.UV6Kind
  26033. * - BABYLON.VertexBuffer.ColorKind
  26034. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26035. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26036. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26037. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26038. */
  26039. Mesh.prototype.isVerticesDataPresent = function (kind) {
  26040. if (!this._geometry) {
  26041. if (this._delayInfo) {
  26042. return this._delayInfo.indexOf(kind) !== -1;
  26043. }
  26044. return false;
  26045. }
  26046. return this._geometry.isVerticesDataPresent(kind);
  26047. };
  26048. /**
  26049. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  26050. * Possible `kind` values :
  26051. * - BABYLON.VertexBuffer.PositionKind
  26052. * - BABYLON.VertexBuffer.UVKind
  26053. * - BABYLON.VertexBuffer.UV2Kind
  26054. * - BABYLON.VertexBuffer.UV3Kind
  26055. * - BABYLON.VertexBuffer.UV4Kind
  26056. * - BABYLON.VertexBuffer.UV5Kind
  26057. * - BABYLON.VertexBuffer.UV6Kind
  26058. * - BABYLON.VertexBuffer.ColorKind
  26059. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26060. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26061. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26062. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26063. */
  26064. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  26065. if (!this._geometry) {
  26066. if (this._delayInfo) {
  26067. return this._delayInfo.indexOf(kind) !== -1;
  26068. }
  26069. return false;
  26070. }
  26071. return this._geometry.isVertexBufferUpdatable(kind);
  26072. };
  26073. /**
  26074. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  26075. * Possible `kind` values :
  26076. * - BABYLON.VertexBuffer.PositionKind
  26077. * - BABYLON.VertexBuffer.UVKind
  26078. * - BABYLON.VertexBuffer.UV2Kind
  26079. * - BABYLON.VertexBuffer.UV3Kind
  26080. * - BABYLON.VertexBuffer.UV4Kind
  26081. * - BABYLON.VertexBuffer.UV5Kind
  26082. * - BABYLON.VertexBuffer.UV6Kind
  26083. * - BABYLON.VertexBuffer.ColorKind
  26084. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26085. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26086. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26087. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26088. */
  26089. Mesh.prototype.getVerticesDataKinds = function () {
  26090. if (!this._geometry) {
  26091. var result = new Array();
  26092. if (this._delayInfo) {
  26093. this._delayInfo.forEach(function (kind, index, array) {
  26094. result.push(kind);
  26095. });
  26096. }
  26097. return result;
  26098. }
  26099. return this._geometry.getVerticesDataKinds();
  26100. };
  26101. /**
  26102. * Returns a positive integer : the total number of indices in this mesh geometry.
  26103. * Returns zero if the mesh has no geometry.
  26104. */
  26105. Mesh.prototype.getTotalIndices = function () {
  26106. if (!this._geometry) {
  26107. return 0;
  26108. }
  26109. return this._geometry.getTotalIndices();
  26110. };
  26111. /**
  26112. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  26113. * 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.
  26114. * Returns an empty array if the mesh has no geometry.
  26115. */
  26116. Mesh.prototype.getIndices = function (copyWhenShared) {
  26117. if (!this._geometry) {
  26118. return [];
  26119. }
  26120. return this._geometry.getIndices(copyWhenShared);
  26121. };
  26122. Object.defineProperty(Mesh.prototype, "isBlocked", {
  26123. get: function () {
  26124. return this._masterMesh !== null && this._masterMesh !== undefined;
  26125. },
  26126. enumerable: true,
  26127. configurable: true
  26128. });
  26129. /**
  26130. * Determine if the current mesh is ready to be rendered
  26131. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  26132. * @returns true if all associated assets are ready (material, textures, shaders)
  26133. */
  26134. Mesh.prototype.isReady = function (forceInstanceSupport) {
  26135. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  26136. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26137. return false;
  26138. }
  26139. if (!_super.prototype.isReady.call(this)) {
  26140. return false;
  26141. }
  26142. if (!this.subMeshes || this.subMeshes.length === 0) {
  26143. return true;
  26144. }
  26145. var engine = this.getEngine();
  26146. var scene = this.getScene();
  26147. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  26148. this.computeWorldMatrix();
  26149. var mat = this.material || scene.defaultMaterial;
  26150. if (mat) {
  26151. if (mat.storeEffectOnSubMeshes) {
  26152. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26153. var subMesh = _a[_i];
  26154. var effectiveMaterial = subMesh.getMaterial();
  26155. if (effectiveMaterial) {
  26156. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26157. return false;
  26158. }
  26159. }
  26160. }
  26161. }
  26162. else {
  26163. if (!mat.isReady(this, hardwareInstancedRendering)) {
  26164. return false;
  26165. }
  26166. }
  26167. }
  26168. // Shadows
  26169. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  26170. var light = _c[_b];
  26171. var generator = light.getShadowGenerator();
  26172. if (generator) {
  26173. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  26174. var subMesh = _e[_d];
  26175. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  26176. return false;
  26177. }
  26178. }
  26179. }
  26180. }
  26181. // LOD
  26182. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  26183. var lod = _g[_f];
  26184. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  26185. return false;
  26186. }
  26187. }
  26188. return true;
  26189. };
  26190. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  26191. /**
  26192. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  26193. * This property is pertinent only for updatable parametric shapes.
  26194. */
  26195. get: function () {
  26196. return this._areNormalsFrozen;
  26197. },
  26198. enumerable: true,
  26199. configurable: true
  26200. });
  26201. /**
  26202. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26203. * It has no effect at all on other shapes.
  26204. * It prevents the mesh normals from being recomputed on next `positions` array update.
  26205. * Returns the Mesh.
  26206. */
  26207. Mesh.prototype.freezeNormals = function () {
  26208. this._areNormalsFrozen = true;
  26209. return this;
  26210. };
  26211. /**
  26212. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  26213. * It has no effect at all on other shapes.
  26214. * It reactivates the mesh normals computation if it was previously frozen.
  26215. * Returns the Mesh.
  26216. */
  26217. Mesh.prototype.unfreezeNormals = function () {
  26218. this._areNormalsFrozen = false;
  26219. return this;
  26220. };
  26221. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  26222. /**
  26223. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  26224. */
  26225. set: function (count) {
  26226. this._overridenInstanceCount = count;
  26227. },
  26228. enumerable: true,
  26229. configurable: true
  26230. });
  26231. // Methods
  26232. Mesh.prototype._preActivate = function () {
  26233. var sceneRenderId = this.getScene().getRenderId();
  26234. if (this._preActivateId === sceneRenderId) {
  26235. return this;
  26236. }
  26237. this._preActivateId = sceneRenderId;
  26238. this._visibleInstances = null;
  26239. return this;
  26240. };
  26241. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  26242. if (this._visibleInstances) {
  26243. this._visibleInstances.intermediateDefaultRenderId = renderId;
  26244. }
  26245. return this;
  26246. };
  26247. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  26248. if (!this._visibleInstances) {
  26249. this._visibleInstances = {};
  26250. this._visibleInstances.defaultRenderId = renderId;
  26251. this._visibleInstances.selfDefaultRenderId = this._renderId;
  26252. }
  26253. if (!this._visibleInstances[renderId]) {
  26254. this._visibleInstances[renderId] = new Array();
  26255. }
  26256. this._visibleInstances[renderId].push(instance);
  26257. return this;
  26258. };
  26259. /**
  26260. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  26261. * This means the mesh underlying bounding box and sphere are recomputed.
  26262. * Returns the Mesh.
  26263. */
  26264. Mesh.prototype.refreshBoundingInfo = function () {
  26265. return this._refreshBoundingInfo(false);
  26266. };
  26267. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  26268. if (this._boundingInfo && this._boundingInfo.isLocked) {
  26269. return this;
  26270. }
  26271. var data = this._getPositionData(applySkeleton);
  26272. if (data) {
  26273. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  26274. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26275. }
  26276. if (this.subMeshes) {
  26277. for (var index = 0; index < this.subMeshes.length; index++) {
  26278. this.subMeshes[index].refreshBoundingInfo();
  26279. }
  26280. }
  26281. this._updateBoundingInfo();
  26282. return this;
  26283. };
  26284. Mesh.prototype._getPositionData = function (applySkeleton) {
  26285. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26286. if (data && applySkeleton && this.skeleton) {
  26287. data = BABYLON.Tools.Slice(data);
  26288. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26289. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26290. if (matricesWeightsData && matricesIndicesData) {
  26291. var needExtras = this.numBoneInfluencers > 4;
  26292. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26293. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26294. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  26295. var tempVector = BABYLON.Tmp.Vector3[0];
  26296. var finalMatrix = BABYLON.Tmp.Matrix[0];
  26297. var tempMatrix = BABYLON.Tmp.Matrix[1];
  26298. var matWeightIdx = 0;
  26299. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  26300. finalMatrix.reset();
  26301. var inf;
  26302. var weight;
  26303. for (inf = 0; inf < 4; inf++) {
  26304. weight = matricesWeightsData[matWeightIdx + inf];
  26305. if (weight <= 0)
  26306. break;
  26307. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26308. finalMatrix.addToSelf(tempMatrix);
  26309. }
  26310. if (needExtras) {
  26311. for (inf = 0; inf < 4; inf++) {
  26312. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26313. if (weight <= 0)
  26314. break;
  26315. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26316. finalMatrix.addToSelf(tempMatrix);
  26317. }
  26318. }
  26319. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  26320. tempVector.toArray(data, index);
  26321. }
  26322. }
  26323. }
  26324. return data;
  26325. };
  26326. Mesh.prototype._createGlobalSubMesh = function (force) {
  26327. var totalVertices = this.getTotalVertices();
  26328. if (!totalVertices || !this.getIndices()) {
  26329. return null;
  26330. }
  26331. // Check if we need to recreate the submeshes
  26332. if (this.subMeshes && this.subMeshes.length > 0) {
  26333. var ib = this.getIndices();
  26334. if (!ib) {
  26335. return null;
  26336. }
  26337. var totalIndices = ib.length;
  26338. var needToRecreate = false;
  26339. if (force) {
  26340. needToRecreate = true;
  26341. }
  26342. else {
  26343. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26344. var submesh = _a[_i];
  26345. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  26346. needToRecreate = true;
  26347. break;
  26348. }
  26349. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  26350. needToRecreate = true;
  26351. break;
  26352. }
  26353. }
  26354. }
  26355. if (!needToRecreate) {
  26356. return this.subMeshes[0];
  26357. }
  26358. }
  26359. this.releaseSubMeshes();
  26360. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  26361. };
  26362. Mesh.prototype.subdivide = function (count) {
  26363. if (count < 1) {
  26364. return;
  26365. }
  26366. var totalIndices = this.getTotalIndices();
  26367. var subdivisionSize = (totalIndices / count) | 0;
  26368. var offset = 0;
  26369. // Ensure that subdivisionSize is a multiple of 3
  26370. while (subdivisionSize % 3 !== 0) {
  26371. subdivisionSize++;
  26372. }
  26373. this.releaseSubMeshes();
  26374. for (var index = 0; index < count; index++) {
  26375. if (offset >= totalIndices) {
  26376. break;
  26377. }
  26378. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  26379. offset += subdivisionSize;
  26380. }
  26381. this.synchronizeInstances();
  26382. };
  26383. /**
  26384. * Sets the vertex data of the mesh geometry for the requested `kind`.
  26385. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  26386. * The `data` are either a numeric array either a Float32Array.
  26387. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  26388. * 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).
  26389. * Note that a new underlying VertexBuffer object is created each call.
  26390. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  26391. *
  26392. * Possible `kind` values :
  26393. * - BABYLON.VertexBuffer.PositionKind
  26394. * - BABYLON.VertexBuffer.UVKind
  26395. * - BABYLON.VertexBuffer.UV2Kind
  26396. * - BABYLON.VertexBuffer.UV3Kind
  26397. * - BABYLON.VertexBuffer.UV4Kind
  26398. * - BABYLON.VertexBuffer.UV5Kind
  26399. * - BABYLON.VertexBuffer.UV6Kind
  26400. * - BABYLON.VertexBuffer.ColorKind
  26401. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26402. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26403. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26404. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26405. *
  26406. * Returns the Mesh.
  26407. */
  26408. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26409. if (updatable === void 0) { updatable = false; }
  26410. if (!this._geometry) {
  26411. var vertexData = new BABYLON.VertexData();
  26412. vertexData.set(data, kind);
  26413. var scene = this.getScene();
  26414. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26415. }
  26416. else {
  26417. this._geometry.setVerticesData(kind, data, updatable, stride);
  26418. }
  26419. return this;
  26420. };
  26421. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  26422. if (updatable === void 0) { updatable = true; }
  26423. var vb = this.getVertexBuffer(kind);
  26424. if (!vb || vb.isUpdatable() === updatable) {
  26425. return;
  26426. }
  26427. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  26428. };
  26429. /**
  26430. * Sets the mesh VertexBuffer.
  26431. * Returns the Mesh.
  26432. */
  26433. Mesh.prototype.setVerticesBuffer = function (buffer) {
  26434. if (!this._geometry) {
  26435. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  26436. }
  26437. this._geometry.setVerticesBuffer(buffer);
  26438. return this;
  26439. };
  26440. /**
  26441. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  26442. * If the mesh has no geometry, it is simply returned as it is.
  26443. * The `data` are either a numeric array either a Float32Array.
  26444. * No new underlying VertexBuffer object is created.
  26445. * 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.
  26446. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  26447. *
  26448. * Possible `kind` values :
  26449. * - BABYLON.VertexBuffer.PositionKind
  26450. * - BABYLON.VertexBuffer.UVKind
  26451. * - BABYLON.VertexBuffer.UV2Kind
  26452. * - BABYLON.VertexBuffer.UV3Kind
  26453. * - BABYLON.VertexBuffer.UV4Kind
  26454. * - BABYLON.VertexBuffer.UV5Kind
  26455. * - BABYLON.VertexBuffer.UV6Kind
  26456. * - BABYLON.VertexBuffer.ColorKind
  26457. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26458. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26459. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26460. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26461. *
  26462. * Returns the Mesh.
  26463. */
  26464. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  26465. if (!this._geometry) {
  26466. return this;
  26467. }
  26468. if (!makeItUnique) {
  26469. this._geometry.updateVerticesData(kind, data, updateExtends);
  26470. }
  26471. else {
  26472. this.makeGeometryUnique();
  26473. this.updateVerticesData(kind, data, updateExtends, false);
  26474. }
  26475. return this;
  26476. };
  26477. /**
  26478. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  26479. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  26480. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  26481. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  26482. * Returns the Mesh.
  26483. */
  26484. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  26485. if (computeNormals === void 0) { computeNormals = true; }
  26486. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26487. if (!positions) {
  26488. return this;
  26489. }
  26490. positionFunction(positions);
  26491. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26492. if (computeNormals) {
  26493. var indices = this.getIndices();
  26494. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26495. if (!normals) {
  26496. return this;
  26497. }
  26498. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  26499. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26500. }
  26501. return this;
  26502. };
  26503. /**
  26504. * Creates a un-shared specific occurence of the geometry for the mesh.
  26505. * Returns the Mesh.
  26506. */
  26507. Mesh.prototype.makeGeometryUnique = function () {
  26508. if (!this._geometry) {
  26509. return this;
  26510. }
  26511. var oldGeometry = this._geometry;
  26512. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  26513. oldGeometry.releaseForMesh(this, true);
  26514. geometry.applyToMesh(this);
  26515. return this;
  26516. };
  26517. /**
  26518. * Sets the mesh indices.
  26519. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  26520. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  26521. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  26522. * This method creates a new index buffer each call.
  26523. * Returns the Mesh.
  26524. */
  26525. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  26526. if (totalVertices === void 0) { totalVertices = null; }
  26527. if (updatable === void 0) { updatable = false; }
  26528. if (!this._geometry) {
  26529. var vertexData = new BABYLON.VertexData();
  26530. vertexData.indices = indices;
  26531. var scene = this.getScene();
  26532. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26533. }
  26534. else {
  26535. this._geometry.setIndices(indices, totalVertices, updatable);
  26536. }
  26537. return this;
  26538. };
  26539. /**
  26540. * Update the current index buffer
  26541. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  26542. * Returns the Mesh.
  26543. */
  26544. Mesh.prototype.updateIndices = function (indices, offset) {
  26545. if (!this._geometry) {
  26546. return this;
  26547. }
  26548. this._geometry.updateIndices(indices, offset);
  26549. return this;
  26550. };
  26551. /**
  26552. * Invert the geometry to move from a right handed system to a left handed one.
  26553. * Returns the Mesh.
  26554. */
  26555. Mesh.prototype.toLeftHanded = function () {
  26556. if (!this._geometry) {
  26557. return this;
  26558. }
  26559. this._geometry.toLeftHanded();
  26560. return this;
  26561. };
  26562. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  26563. if (!this._geometry) {
  26564. return this;
  26565. }
  26566. var engine = this.getScene().getEngine();
  26567. // Wireframe
  26568. var indexToBind;
  26569. if (this._unIndexed) {
  26570. indexToBind = null;
  26571. }
  26572. else {
  26573. switch (fillMode) {
  26574. case BABYLON.Material.PointFillMode:
  26575. indexToBind = null;
  26576. break;
  26577. case BABYLON.Material.WireFrameFillMode:
  26578. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  26579. break;
  26580. default:
  26581. case BABYLON.Material.TriangleFillMode:
  26582. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  26583. break;
  26584. }
  26585. }
  26586. // VBOs
  26587. this._geometry._bind(effect, indexToBind);
  26588. return this;
  26589. };
  26590. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  26591. if (alternate === void 0) { alternate = false; }
  26592. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26593. return this;
  26594. }
  26595. this.onBeforeDrawObservable.notifyObservers(this);
  26596. var scene = this.getScene();
  26597. var engine = scene.getEngine();
  26598. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  26599. // or triangles as points
  26600. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  26601. }
  26602. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  26603. // Triangles as wireframe
  26604. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  26605. }
  26606. else {
  26607. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  26608. }
  26609. if (scene._isAlternateRenderingEnabled && !alternate) {
  26610. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  26611. if (!effect || !scene.activeCamera) {
  26612. return this;
  26613. }
  26614. scene._switchToAlternateCameraConfiguration(true);
  26615. this._effectiveMaterial.bindView(effect);
  26616. this._effectiveMaterial.bindViewProjection(effect);
  26617. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  26618. this._draw(subMesh, fillMode, instancesCount, true);
  26619. engine.setViewport(scene.activeCamera.viewport);
  26620. scene._switchToAlternateCameraConfiguration(false);
  26621. this._effectiveMaterial.bindView(effect);
  26622. this._effectiveMaterial.bindViewProjection(effect);
  26623. }
  26624. return this;
  26625. };
  26626. /**
  26627. * Registers for this mesh a javascript function called just before the rendering process.
  26628. * This function is passed the current mesh.
  26629. * Return the Mesh.
  26630. */
  26631. Mesh.prototype.registerBeforeRender = function (func) {
  26632. this.onBeforeRenderObservable.add(func);
  26633. return this;
  26634. };
  26635. /**
  26636. * Disposes a previously registered javascript function called before the rendering.
  26637. * This function is passed the current mesh.
  26638. * Returns the Mesh.
  26639. */
  26640. Mesh.prototype.unregisterBeforeRender = function (func) {
  26641. this.onBeforeRenderObservable.removeCallback(func);
  26642. return this;
  26643. };
  26644. /**
  26645. * Registers for this mesh a javascript function called just after the rendering is complete.
  26646. * This function is passed the current mesh.
  26647. * Returns the Mesh.
  26648. */
  26649. Mesh.prototype.registerAfterRender = function (func) {
  26650. this.onAfterRenderObservable.add(func);
  26651. return this;
  26652. };
  26653. /**
  26654. * Disposes a previously registered javascript function called after the rendering.
  26655. * This function is passed the current mesh.
  26656. * Return the Mesh.
  26657. */
  26658. Mesh.prototype.unregisterAfterRender = function (func) {
  26659. this.onAfterRenderObservable.removeCallback(func);
  26660. return this;
  26661. };
  26662. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  26663. var scene = this.getScene();
  26664. this._batchCache.mustReturn = false;
  26665. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  26666. this._batchCache.visibleInstances[subMeshId] = null;
  26667. if (this._visibleInstances) {
  26668. var currentRenderId = scene.getRenderId();
  26669. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  26670. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  26671. var selfRenderId = this._renderId;
  26672. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  26673. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  26674. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  26675. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  26676. }
  26677. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  26678. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  26679. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  26680. this._batchCache.mustReturn = true;
  26681. return this._batchCache;
  26682. }
  26683. if (currentRenderId !== selfRenderId) {
  26684. this._batchCache.renderSelf[subMeshId] = false;
  26685. }
  26686. }
  26687. this._renderIdForInstances[subMeshId] = currentRenderId;
  26688. }
  26689. return this._batchCache;
  26690. };
  26691. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  26692. var visibleInstances = batch.visibleInstances[subMesh._id];
  26693. if (!visibleInstances) {
  26694. return this;
  26695. }
  26696. var matricesCount = visibleInstances.length + 1;
  26697. var bufferSize = matricesCount * 16 * 4;
  26698. var currentInstancesBufferSize = this._instancesBufferSize;
  26699. var instancesBuffer = this._instancesBuffer;
  26700. while (this._instancesBufferSize < bufferSize) {
  26701. this._instancesBufferSize *= 2;
  26702. }
  26703. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26704. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26705. }
  26706. var offset = 0;
  26707. var instancesCount = 0;
  26708. var world = this.getWorldMatrix();
  26709. if (batch.renderSelf[subMesh._id]) {
  26710. world.copyToArray(this._instancesData, offset);
  26711. offset += 16;
  26712. instancesCount++;
  26713. }
  26714. if (visibleInstances) {
  26715. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26716. var instance = visibleInstances[instanceIndex];
  26717. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26718. offset += 16;
  26719. instancesCount++;
  26720. }
  26721. }
  26722. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26723. if (instancesBuffer) {
  26724. instancesBuffer.dispose();
  26725. }
  26726. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  26727. this._instancesBuffer = instancesBuffer;
  26728. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  26729. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  26730. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  26731. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  26732. }
  26733. else {
  26734. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  26735. }
  26736. this._bind(subMesh, effect, fillMode);
  26737. this._draw(subMesh, fillMode, instancesCount);
  26738. engine.unbindInstanceAttributes();
  26739. return this;
  26740. };
  26741. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  26742. var scene = this.getScene();
  26743. var engine = scene.getEngine();
  26744. if (hardwareInstancedRendering) {
  26745. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  26746. }
  26747. else {
  26748. if (batch.renderSelf[subMesh._id]) {
  26749. // Draw
  26750. if (onBeforeDraw) {
  26751. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  26752. }
  26753. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  26754. }
  26755. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  26756. if (visibleInstancesForSubMesh) {
  26757. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  26758. var instance = visibleInstancesForSubMesh[instanceIndex];
  26759. // World
  26760. var world = instance.getWorldMatrix();
  26761. if (onBeforeDraw) {
  26762. onBeforeDraw(true, world, effectiveMaterial);
  26763. }
  26764. // Draw
  26765. this._draw(subMesh, fillMode);
  26766. }
  26767. }
  26768. }
  26769. return this;
  26770. };
  26771. /**
  26772. * Triggers the draw call for the mesh.
  26773. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  26774. * Returns the Mesh.
  26775. */
  26776. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  26777. this.checkOcclusionQuery();
  26778. if (this._isOccluded) {
  26779. return this;
  26780. }
  26781. var scene = this.getScene();
  26782. // Managing instances
  26783. var batch = this._getInstancesRenderList(subMesh._id);
  26784. if (batch.mustReturn) {
  26785. return this;
  26786. }
  26787. // Checking geometry state
  26788. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26789. return this;
  26790. }
  26791. this.onBeforeRenderObservable.notifyObservers(this);
  26792. var engine = scene.getEngine();
  26793. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26794. // Material
  26795. var material = subMesh.getMaterial();
  26796. if (!material) {
  26797. return this;
  26798. }
  26799. this._effectiveMaterial = material;
  26800. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26801. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26802. return this;
  26803. }
  26804. }
  26805. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  26806. return this;
  26807. }
  26808. // Alpha mode
  26809. if (enableAlphaMode) {
  26810. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  26811. }
  26812. // Outline - step 1
  26813. var savedDepthWrite = engine.getDepthWrite();
  26814. if (this.renderOutline) {
  26815. engine.setDepthWrite(false);
  26816. scene.getOutlineRenderer().render(subMesh, batch);
  26817. engine.setDepthWrite(savedDepthWrite);
  26818. }
  26819. var effect;
  26820. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26821. effect = subMesh.effect;
  26822. }
  26823. else {
  26824. effect = this._effectiveMaterial.getEffect();
  26825. }
  26826. if (!effect) {
  26827. return this;
  26828. }
  26829. var sideOrientation = this.overrideMaterialSideOrientation;
  26830. if (sideOrientation == null) {
  26831. sideOrientation = this._effectiveMaterial.sideOrientation;
  26832. if (this._getWorldMatrixDeterminant() < 0) {
  26833. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  26834. }
  26835. }
  26836. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  26837. if (this._effectiveMaterial.forceDepthWrite) {
  26838. engine.setDepthWrite(true);
  26839. }
  26840. // Bind
  26841. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  26842. if (!hardwareInstancedRendering) {
  26843. this._bind(subMesh, effect, fillMode);
  26844. }
  26845. var world = this.getWorldMatrix();
  26846. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26847. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  26848. }
  26849. else {
  26850. this._effectiveMaterial.bind(world, this);
  26851. }
  26852. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  26853. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  26854. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26855. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  26856. }
  26857. // Draw
  26858. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26859. // Unbind
  26860. this._effectiveMaterial.unbind();
  26861. // Outline - step 2
  26862. if (this.renderOutline && savedDepthWrite) {
  26863. engine.setDepthWrite(true);
  26864. engine.setColorWrite(false);
  26865. scene.getOutlineRenderer().render(subMesh, batch);
  26866. engine.setColorWrite(true);
  26867. }
  26868. // Overlay
  26869. if (this.renderOverlay) {
  26870. var currentMode = engine.getAlphaMode();
  26871. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26872. scene.getOutlineRenderer().render(subMesh, batch, true);
  26873. engine.setAlphaMode(currentMode);
  26874. }
  26875. this.onAfterRenderObservable.notifyObservers(this);
  26876. return this;
  26877. };
  26878. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  26879. if (isInstance && effectiveMaterial) {
  26880. effectiveMaterial.bindOnlyWorldMatrix(world);
  26881. }
  26882. };
  26883. /**
  26884. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  26885. */
  26886. Mesh.prototype.getEmittedParticleSystems = function () {
  26887. var results = new Array();
  26888. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26889. var particleSystem = this.getScene().particleSystems[index];
  26890. if (particleSystem.emitter === this) {
  26891. results.push(particleSystem);
  26892. }
  26893. }
  26894. return results;
  26895. };
  26896. /**
  26897. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26898. */
  26899. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26900. var results = new Array();
  26901. var descendants = this.getDescendants();
  26902. descendants.push(this);
  26903. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26904. var particleSystem = this.getScene().particleSystems[index];
  26905. var emitter = particleSystem.emitter;
  26906. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26907. results.push(particleSystem);
  26908. }
  26909. }
  26910. return results;
  26911. };
  26912. Mesh.prototype._checkDelayState = function () {
  26913. var scene = this.getScene();
  26914. if (this._geometry) {
  26915. this._geometry.load(scene);
  26916. }
  26917. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26918. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26919. this._queueLoad(scene);
  26920. }
  26921. return this;
  26922. };
  26923. Mesh.prototype._queueLoad = function (scene) {
  26924. var _this = this;
  26925. scene._addPendingData(this);
  26926. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26927. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26928. if (data instanceof ArrayBuffer) {
  26929. _this._delayLoadingFunction(data, _this);
  26930. }
  26931. else {
  26932. _this._delayLoadingFunction(JSON.parse(data), _this);
  26933. }
  26934. _this.instances.forEach(function (instance) {
  26935. instance._syncSubMeshes();
  26936. });
  26937. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26938. scene._removePendingData(_this);
  26939. }, function () { }, scene.database, getBinaryData);
  26940. return this;
  26941. };
  26942. /**
  26943. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26944. */
  26945. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26946. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26947. return false;
  26948. }
  26949. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26950. return false;
  26951. }
  26952. this._checkDelayState();
  26953. return true;
  26954. };
  26955. /**
  26956. * Sets the mesh material by the material or multiMaterial `id` property.
  26957. * The material `id` is a string identifying the material or the multiMaterial.
  26958. * This method returns the Mesh.
  26959. */
  26960. Mesh.prototype.setMaterialByID = function (id) {
  26961. var materials = this.getScene().materials;
  26962. var index;
  26963. for (index = materials.length - 1; index > -1; index--) {
  26964. if (materials[index].id === id) {
  26965. this.material = materials[index];
  26966. return this;
  26967. }
  26968. }
  26969. // Multi
  26970. var multiMaterials = this.getScene().multiMaterials;
  26971. for (index = multiMaterials.length - 1; index > -1; index--) {
  26972. if (multiMaterials[index].id === id) {
  26973. this.material = multiMaterials[index];
  26974. return this;
  26975. }
  26976. }
  26977. return this;
  26978. };
  26979. /**
  26980. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26981. */
  26982. Mesh.prototype.getAnimatables = function () {
  26983. var results = new Array();
  26984. if (this.material) {
  26985. results.push(this.material);
  26986. }
  26987. if (this.skeleton) {
  26988. results.push(this.skeleton);
  26989. }
  26990. return results;
  26991. };
  26992. /**
  26993. * Modifies the mesh geometry according to the passed transformation matrix.
  26994. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  26995. * The mesh normals are modified accordingly the same transformation.
  26996. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  26997. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26998. * Returns the Mesh.
  26999. */
  27000. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  27001. // Position
  27002. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27003. return this;
  27004. }
  27005. var submeshes = this.subMeshes.splice(0);
  27006. this._resetPointsArrayCache();
  27007. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27008. var temp = new Array();
  27009. var index;
  27010. for (index = 0; index < data.length; index += 3) {
  27011. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  27012. }
  27013. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  27014. // Normals
  27015. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27016. return this;
  27017. }
  27018. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27019. temp = [];
  27020. for (index = 0; index < data.length; index += 3) {
  27021. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  27022. }
  27023. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  27024. // flip faces?
  27025. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  27026. this.flipFaces();
  27027. }
  27028. // Restore submeshes
  27029. this.releaseSubMeshes();
  27030. this.subMeshes = submeshes;
  27031. return this;
  27032. };
  27033. /**
  27034. * Modifies the mesh geometry according to its own current World Matrix.
  27035. * The mesh World Matrix is then reset.
  27036. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  27037. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  27038. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27039. * Returns the Mesh.
  27040. */
  27041. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  27042. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  27043. this.scaling.copyFromFloats(1, 1, 1);
  27044. this.position.copyFromFloats(0, 0, 0);
  27045. this.rotation.copyFromFloats(0, 0, 0);
  27046. //only if quaternion is already set
  27047. if (this.rotationQuaternion) {
  27048. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  27049. }
  27050. this._worldMatrix = BABYLON.Matrix.Identity();
  27051. return this;
  27052. };
  27053. Object.defineProperty(Mesh.prototype, "_positions", {
  27054. // Cache
  27055. get: function () {
  27056. if (this._geometry) {
  27057. return this._geometry._positions;
  27058. }
  27059. return null;
  27060. },
  27061. enumerable: true,
  27062. configurable: true
  27063. });
  27064. Mesh.prototype._resetPointsArrayCache = function () {
  27065. if (this._geometry) {
  27066. this._geometry._resetPointsArrayCache();
  27067. }
  27068. return this;
  27069. };
  27070. Mesh.prototype._generatePointsArray = function () {
  27071. if (this._geometry) {
  27072. return this._geometry._generatePointsArray();
  27073. }
  27074. return false;
  27075. };
  27076. /**
  27077. * Returns a new Mesh object generated from the current mesh properties.
  27078. * This method must not get confused with createInstance().
  27079. * The parameter `name` is a string, the name given to the new mesh.
  27080. * The optional parameter `newParent` can be any Node object (default `null`).
  27081. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  27082. * 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.
  27083. */
  27084. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  27085. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27086. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  27087. };
  27088. /**
  27089. * Disposes the Mesh.
  27090. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  27091. * Returns nothing.
  27092. */
  27093. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  27094. var _this = this;
  27095. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  27096. this.morphTargetManager = null;
  27097. if (this._geometry) {
  27098. this._geometry.releaseForMesh(this, true);
  27099. }
  27100. // Sources
  27101. var meshes = this.getScene().meshes;
  27102. meshes.forEach(function (abstractMesh) {
  27103. var mesh = abstractMesh;
  27104. if (mesh._source && mesh._source === _this) {
  27105. mesh._source = null;
  27106. }
  27107. });
  27108. this._source = null;
  27109. // Instances
  27110. if (this._instancesBuffer) {
  27111. this._instancesBuffer.dispose();
  27112. this._instancesBuffer = null;
  27113. }
  27114. while (this.instances.length) {
  27115. this.instances[0].dispose();
  27116. }
  27117. // Highlight layers.
  27118. var highlightLayers = this.getScene().highlightLayers;
  27119. for (var i = 0; i < highlightLayers.length; i++) {
  27120. var highlightLayer = highlightLayers[i];
  27121. if (highlightLayer) {
  27122. highlightLayer.removeMesh(this);
  27123. highlightLayer.removeExcludedMesh(this);
  27124. }
  27125. }
  27126. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  27127. };
  27128. /**
  27129. * Modifies the mesh geometry according to a displacement map.
  27130. * 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.
  27131. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27132. * This method returns nothing.
  27133. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  27134. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27135. * 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.
  27136. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27137. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27138. *
  27139. * Returns the Mesh.
  27140. */
  27141. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  27142. var _this = this;
  27143. var scene = this.getScene();
  27144. var onload = function (img) {
  27145. // Getting height map data
  27146. var canvas = document.createElement("canvas");
  27147. var context = canvas.getContext("2d");
  27148. var heightMapWidth = img.width;
  27149. var heightMapHeight = img.height;
  27150. canvas.width = heightMapWidth;
  27151. canvas.height = heightMapHeight;
  27152. context.drawImage(img, 0, 0);
  27153. // Create VertexData from map data
  27154. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  27155. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  27156. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  27157. //execute success callback, if set
  27158. if (onSuccess) {
  27159. onSuccess(_this);
  27160. }
  27161. };
  27162. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  27163. return this;
  27164. };
  27165. /**
  27166. * Modifies the mesh geometry according to a displacementMap buffer.
  27167. * 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.
  27168. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  27169. * This method returns nothing.
  27170. * 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.
  27171. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  27172. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  27173. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  27174. * The parameter `uvScale` is an optional vector2 used to scale UV.
  27175. *
  27176. * Returns the Mesh.
  27177. */
  27178. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  27179. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  27180. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  27181. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27182. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  27183. return this;
  27184. }
  27185. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27186. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27187. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27188. var position = BABYLON.Vector3.Zero();
  27189. var normal = BABYLON.Vector3.Zero();
  27190. var uv = BABYLON.Vector2.Zero();
  27191. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  27192. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  27193. for (var index = 0; index < positions.length; index += 3) {
  27194. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  27195. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  27196. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  27197. // Compute height
  27198. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  27199. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  27200. var pos = (u + v * heightMapWidth) * 4;
  27201. var r = buffer[pos] / 255.0;
  27202. var g = buffer[pos + 1] / 255.0;
  27203. var b = buffer[pos + 2] / 255.0;
  27204. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27205. normal.normalize();
  27206. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  27207. position = position.add(normal);
  27208. position.toArray(positions, index);
  27209. }
  27210. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  27211. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  27212. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  27213. return this;
  27214. };
  27215. /**
  27216. * Modify the mesh to get a flat shading rendering.
  27217. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  27218. * This method returns the Mesh.
  27219. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  27220. */
  27221. Mesh.prototype.convertToFlatShadedMesh = function () {
  27222. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  27223. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27224. var kinds = this.getVerticesDataKinds();
  27225. var vbs = {};
  27226. var data = {};
  27227. var newdata = {};
  27228. var updatableNormals = false;
  27229. var kindIndex;
  27230. var kind;
  27231. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27232. kind = kinds[kindIndex];
  27233. var vertexBuffer = this.getVertexBuffer(kind);
  27234. if (kind === BABYLON.VertexBuffer.NormalKind) {
  27235. updatableNormals = vertexBuffer.isUpdatable();
  27236. kinds.splice(kindIndex, 1);
  27237. kindIndex--;
  27238. continue;
  27239. }
  27240. vbs[kind] = vertexBuffer;
  27241. data[kind] = vbs[kind].getData();
  27242. newdata[kind] = [];
  27243. }
  27244. // Save previous submeshes
  27245. var previousSubmeshes = this.subMeshes.slice(0);
  27246. var indices = this.getIndices();
  27247. var totalIndices = this.getTotalIndices();
  27248. // Generating unique vertices per face
  27249. var index;
  27250. for (index = 0; index < totalIndices; index++) {
  27251. var vertexIndex = indices[index];
  27252. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27253. kind = kinds[kindIndex];
  27254. var stride = vbs[kind].getStrideSize();
  27255. for (var offset = 0; offset < stride; offset++) {
  27256. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27257. }
  27258. }
  27259. }
  27260. // Updating faces & normal
  27261. var normals = [];
  27262. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  27263. for (index = 0; index < totalIndices; index += 3) {
  27264. indices[index] = index;
  27265. indices[index + 1] = index + 1;
  27266. indices[index + 2] = index + 2;
  27267. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  27268. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  27269. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  27270. var p1p2 = p1.subtract(p2);
  27271. var p3p2 = p3.subtract(p2);
  27272. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  27273. // Store same normals for every vertex
  27274. for (var localIndex = 0; localIndex < 3; localIndex++) {
  27275. normals.push(normal.x);
  27276. normals.push(normal.y);
  27277. normals.push(normal.z);
  27278. }
  27279. }
  27280. this.setIndices(indices);
  27281. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  27282. // Updating vertex buffers
  27283. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27284. kind = kinds[kindIndex];
  27285. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27286. }
  27287. // Updating submeshes
  27288. this.releaseSubMeshes();
  27289. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27290. var previousOne = previousSubmeshes[submeshIndex];
  27291. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27292. }
  27293. this.synchronizeInstances();
  27294. return this;
  27295. };
  27296. /**
  27297. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  27298. * In other words, more vertices, no more indices and a single bigger VBO.
  27299. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  27300. * Returns the Mesh.
  27301. */
  27302. Mesh.prototype.convertToUnIndexedMesh = function () {
  27303. /// <summary>Remove indices by unfolding faces into buffers</summary>
  27304. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27305. var kinds = this.getVerticesDataKinds();
  27306. var vbs = {};
  27307. var data = {};
  27308. var newdata = {};
  27309. var kindIndex;
  27310. var kind;
  27311. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27312. kind = kinds[kindIndex];
  27313. var vertexBuffer = this.getVertexBuffer(kind);
  27314. vbs[kind] = vertexBuffer;
  27315. data[kind] = vbs[kind].getData();
  27316. newdata[kind] = [];
  27317. }
  27318. // Save previous submeshes
  27319. var previousSubmeshes = this.subMeshes.slice(0);
  27320. var indices = this.getIndices();
  27321. var totalIndices = this.getTotalIndices();
  27322. // Generating unique vertices per face
  27323. var index;
  27324. for (index = 0; index < totalIndices; index++) {
  27325. var vertexIndex = indices[index];
  27326. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27327. kind = kinds[kindIndex];
  27328. var stride = vbs[kind].getStrideSize();
  27329. for (var offset = 0; offset < stride; offset++) {
  27330. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27331. }
  27332. }
  27333. }
  27334. // Updating indices
  27335. for (index = 0; index < totalIndices; index += 3) {
  27336. indices[index] = index;
  27337. indices[index + 1] = index + 1;
  27338. indices[index + 2] = index + 2;
  27339. }
  27340. this.setIndices(indices);
  27341. // Updating vertex buffers
  27342. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27343. kind = kinds[kindIndex];
  27344. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27345. }
  27346. // Updating submeshes
  27347. this.releaseSubMeshes();
  27348. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27349. var previousOne = previousSubmeshes[submeshIndex];
  27350. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27351. }
  27352. this._unIndexed = true;
  27353. this.synchronizeInstances();
  27354. return this;
  27355. };
  27356. /**
  27357. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  27358. * This method returns the Mesh.
  27359. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  27360. */
  27361. Mesh.prototype.flipFaces = function (flipNormals) {
  27362. if (flipNormals === void 0) { flipNormals = false; }
  27363. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  27364. var i;
  27365. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  27366. for (i = 0; i < vertex_data.normals.length; i++) {
  27367. vertex_data.normals[i] *= -1;
  27368. }
  27369. }
  27370. if (vertex_data.indices) {
  27371. var temp;
  27372. for (i = 0; i < vertex_data.indices.length; i += 3) {
  27373. // reassign indices
  27374. temp = vertex_data.indices[i + 1];
  27375. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  27376. vertex_data.indices[i + 2] = temp;
  27377. }
  27378. }
  27379. vertex_data.applyToMesh(this);
  27380. return this;
  27381. };
  27382. // Instances
  27383. /**
  27384. * Creates a new InstancedMesh object from the mesh model.
  27385. * An instance shares the same properties and the same material than its model.
  27386. * Only these properties of each instance can then be set individually :
  27387. * - position
  27388. * - rotation
  27389. * - rotationQuaternion
  27390. * - setPivotMatrix
  27391. * - scaling
  27392. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  27393. * Warning : this method is not supported for Line mesh and LineSystem
  27394. */
  27395. Mesh.prototype.createInstance = function (name) {
  27396. return new BABYLON.InstancedMesh(name, this);
  27397. };
  27398. /**
  27399. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  27400. * After this call, all the mesh instances have the same submeshes than the current mesh.
  27401. * This method returns the Mesh.
  27402. */
  27403. Mesh.prototype.synchronizeInstances = function () {
  27404. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  27405. var instance = this.instances[instanceIndex];
  27406. instance._syncSubMeshes();
  27407. }
  27408. return this;
  27409. };
  27410. /**
  27411. * Simplify the mesh according to the given array of settings.
  27412. * Function will return immediately and will simplify async. It returns the Mesh.
  27413. * @param settings a collection of simplification settings.
  27414. * @param parallelProcessing should all levels calculate parallel or one after the other.
  27415. * @param type the type of simplification to run.
  27416. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  27417. */
  27418. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  27419. if (parallelProcessing === void 0) { parallelProcessing = true; }
  27420. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  27421. this.getScene().simplificationQueue.addTask({
  27422. settings: settings,
  27423. parallelProcessing: parallelProcessing,
  27424. mesh: this,
  27425. simplificationType: simplificationType,
  27426. successCallback: successCallback
  27427. });
  27428. return this;
  27429. };
  27430. /**
  27431. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  27432. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  27433. * This should be used together with the simplification to avoid disappearing triangles.
  27434. * Returns the Mesh.
  27435. * @param successCallback an optional success callback to be called after the optimization finished.
  27436. */
  27437. Mesh.prototype.optimizeIndices = function (successCallback) {
  27438. var _this = this;
  27439. var indices = this.getIndices();
  27440. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27441. if (!positions || !indices) {
  27442. return this;
  27443. }
  27444. var vectorPositions = new Array();
  27445. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  27446. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  27447. }
  27448. var dupes = new Array();
  27449. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  27450. var realPos = vectorPositions.length - 1 - iteration;
  27451. var testedPosition = vectorPositions[realPos];
  27452. for (var j = 0; j < realPos; ++j) {
  27453. var againstPosition = vectorPositions[j];
  27454. if (testedPosition.equals(againstPosition)) {
  27455. dupes[realPos] = j;
  27456. break;
  27457. }
  27458. }
  27459. }, function () {
  27460. for (var i = 0; i < indices.length; ++i) {
  27461. indices[i] = dupes[indices[i]] || indices[i];
  27462. }
  27463. //indices are now reordered
  27464. var originalSubMeshes = _this.subMeshes.slice(0);
  27465. _this.setIndices(indices);
  27466. _this.subMeshes = originalSubMeshes;
  27467. if (successCallback) {
  27468. successCallback(_this);
  27469. }
  27470. });
  27471. return this;
  27472. };
  27473. Mesh.prototype.serialize = function (serializationObject) {
  27474. serializationObject.name = this.name;
  27475. serializationObject.id = this.id;
  27476. serializationObject.type = this.getClassName();
  27477. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27478. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27479. }
  27480. serializationObject.position = this.position.asArray();
  27481. if (this.rotationQuaternion) {
  27482. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  27483. }
  27484. else if (this.rotation) {
  27485. serializationObject.rotation = this.rotation.asArray();
  27486. }
  27487. serializationObject.scaling = this.scaling.asArray();
  27488. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  27489. serializationObject.isEnabled = this.isEnabled(false);
  27490. serializationObject.isVisible = this.isVisible;
  27491. serializationObject.infiniteDistance = this.infiniteDistance;
  27492. serializationObject.pickable = this.isPickable;
  27493. serializationObject.receiveShadows = this.receiveShadows;
  27494. serializationObject.billboardMode = this.billboardMode;
  27495. serializationObject.visibility = this.visibility;
  27496. serializationObject.checkCollisions = this.checkCollisions;
  27497. serializationObject.isBlocker = this.isBlocker;
  27498. // Parent
  27499. if (this.parent) {
  27500. serializationObject.parentId = this.parent.id;
  27501. }
  27502. // Geometry
  27503. serializationObject.isUnIndexed = this.isUnIndexed;
  27504. var geometry = this._geometry;
  27505. if (geometry) {
  27506. var geometryId = geometry.id;
  27507. serializationObject.geometryId = geometryId;
  27508. // SubMeshes
  27509. serializationObject.subMeshes = [];
  27510. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  27511. var subMesh = this.subMeshes[subIndex];
  27512. serializationObject.subMeshes.push({
  27513. materialIndex: subMesh.materialIndex,
  27514. verticesStart: subMesh.verticesStart,
  27515. verticesCount: subMesh.verticesCount,
  27516. indexStart: subMesh.indexStart,
  27517. indexCount: subMesh.indexCount
  27518. });
  27519. }
  27520. }
  27521. // Material
  27522. if (this.material) {
  27523. serializationObject.materialId = this.material.id;
  27524. }
  27525. else {
  27526. this.material = null;
  27527. }
  27528. // Morph targets
  27529. if (this.morphTargetManager) {
  27530. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  27531. }
  27532. // Skeleton
  27533. if (this.skeleton) {
  27534. serializationObject.skeletonId = this.skeleton.id;
  27535. }
  27536. // Physics
  27537. //TODO implement correct serialization for physics impostors.
  27538. var impostor = this.getPhysicsImpostor();
  27539. if (impostor) {
  27540. serializationObject.physicsMass = impostor.getParam("mass");
  27541. serializationObject.physicsFriction = impostor.getParam("friction");
  27542. serializationObject.physicsRestitution = impostor.getParam("mass");
  27543. serializationObject.physicsImpostor = impostor.type;
  27544. }
  27545. // Metadata
  27546. if (this.metadata) {
  27547. serializationObject.metadata = this.metadata;
  27548. }
  27549. // Instances
  27550. serializationObject.instances = [];
  27551. for (var index = 0; index < this.instances.length; index++) {
  27552. var instance = this.instances[index];
  27553. var serializationInstance = {
  27554. name: instance.name,
  27555. id: instance.id,
  27556. position: instance.position.asArray(),
  27557. scaling: instance.scaling.asArray()
  27558. };
  27559. if (instance.rotationQuaternion) {
  27560. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  27561. }
  27562. else if (instance.rotation) {
  27563. serializationInstance.rotation = instance.rotation.asArray();
  27564. }
  27565. serializationObject.instances.push(serializationInstance);
  27566. // Animations
  27567. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  27568. serializationInstance.ranges = instance.serializeAnimationRanges();
  27569. }
  27570. //
  27571. // Animations
  27572. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27573. serializationObject.ranges = this.serializeAnimationRanges();
  27574. // Layer mask
  27575. serializationObject.layerMask = this.layerMask;
  27576. // Alpha
  27577. serializationObject.alphaIndex = this.alphaIndex;
  27578. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  27579. // Overlay
  27580. serializationObject.overlayAlpha = this.overlayAlpha;
  27581. serializationObject.overlayColor = this.overlayColor.asArray();
  27582. serializationObject.renderOverlay = this.renderOverlay;
  27583. // Fog
  27584. serializationObject.applyFog = this.applyFog;
  27585. // Action Manager
  27586. if (this.actionManager) {
  27587. serializationObject.actions = this.actionManager.serialize(this.name);
  27588. }
  27589. };
  27590. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  27591. if (!this.geometry) {
  27592. return;
  27593. }
  27594. this._markSubMeshesAsAttributesDirty();
  27595. var morphTargetManager = this._morphTargetManager;
  27596. if (morphTargetManager && morphTargetManager.vertexCount) {
  27597. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  27598. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  27599. this.morphTargetManager = null;
  27600. return;
  27601. }
  27602. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  27603. var morphTarget = morphTargetManager.getActiveTarget(index);
  27604. var positions = morphTarget.getPositions();
  27605. if (!positions) {
  27606. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  27607. return;
  27608. }
  27609. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  27610. var normals = morphTarget.getNormals();
  27611. if (normals) {
  27612. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  27613. }
  27614. var tangents = morphTarget.getTangents();
  27615. if (tangents) {
  27616. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  27617. }
  27618. }
  27619. }
  27620. else {
  27621. var index = 0;
  27622. // Positions
  27623. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  27624. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  27625. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  27626. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  27627. }
  27628. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  27629. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  27630. }
  27631. index++;
  27632. }
  27633. }
  27634. };
  27635. // Statics
  27636. /**
  27637. * Returns a new Mesh object parsed from the source provided.
  27638. * The parameter `parsedMesh` is the source.
  27639. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  27640. */
  27641. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  27642. var mesh;
  27643. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  27644. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  27645. }
  27646. else {
  27647. mesh = new Mesh(parsedMesh.name, scene);
  27648. }
  27649. mesh.id = parsedMesh.id;
  27650. if (BABYLON.Tags) {
  27651. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  27652. }
  27653. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  27654. if (parsedMesh.metadata !== undefined) {
  27655. mesh.metadata = parsedMesh.metadata;
  27656. }
  27657. if (parsedMesh.rotationQuaternion) {
  27658. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  27659. }
  27660. else if (parsedMesh.rotation) {
  27661. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  27662. }
  27663. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  27664. if (parsedMesh.localMatrix) {
  27665. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  27666. }
  27667. else if (parsedMesh.pivotMatrix) {
  27668. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  27669. }
  27670. mesh.setEnabled(parsedMesh.isEnabled);
  27671. mesh.isVisible = parsedMesh.isVisible;
  27672. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  27673. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  27674. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  27675. if (parsedMesh.applyFog !== undefined) {
  27676. mesh.applyFog = parsedMesh.applyFog;
  27677. }
  27678. if (parsedMesh.pickable !== undefined) {
  27679. mesh.isPickable = parsedMesh.pickable;
  27680. }
  27681. if (parsedMesh.alphaIndex !== undefined) {
  27682. mesh.alphaIndex = parsedMesh.alphaIndex;
  27683. }
  27684. mesh.receiveShadows = parsedMesh.receiveShadows;
  27685. mesh.billboardMode = parsedMesh.billboardMode;
  27686. if (parsedMesh.visibility !== undefined) {
  27687. mesh.visibility = parsedMesh.visibility;
  27688. }
  27689. mesh.checkCollisions = parsedMesh.checkCollisions;
  27690. if (parsedMesh.isBlocker !== undefined) {
  27691. mesh.isBlocker = parsedMesh.isBlocker;
  27692. }
  27693. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27694. // freezeWorldMatrix
  27695. if (parsedMesh.freezeWorldMatrix) {
  27696. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27697. }
  27698. // Parent
  27699. if (parsedMesh.parentId) {
  27700. mesh._waitingParentId = parsedMesh.parentId;
  27701. }
  27702. // Actions
  27703. if (parsedMesh.actions !== undefined) {
  27704. mesh._waitingActions = parsedMesh.actions;
  27705. }
  27706. // Overlay
  27707. if (parsedMesh.overlayAlpha !== undefined) {
  27708. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27709. }
  27710. if (parsedMesh.overlayColor !== undefined) {
  27711. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27712. }
  27713. if (parsedMesh.renderOverlay !== undefined) {
  27714. mesh.renderOverlay = parsedMesh.renderOverlay;
  27715. }
  27716. // Geometry
  27717. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27718. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27719. if (parsedMesh.delayLoadingFile) {
  27720. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27721. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27722. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27723. if (parsedMesh._binaryInfo) {
  27724. mesh._binaryInfo = parsedMesh._binaryInfo;
  27725. }
  27726. mesh._delayInfo = [];
  27727. if (parsedMesh.hasUVs) {
  27728. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27729. }
  27730. if (parsedMesh.hasUVs2) {
  27731. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27732. }
  27733. if (parsedMesh.hasUVs3) {
  27734. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27735. }
  27736. if (parsedMesh.hasUVs4) {
  27737. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27738. }
  27739. if (parsedMesh.hasUVs5) {
  27740. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27741. }
  27742. if (parsedMesh.hasUVs6) {
  27743. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27744. }
  27745. if (parsedMesh.hasColors) {
  27746. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27747. }
  27748. if (parsedMesh.hasMatricesIndices) {
  27749. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27750. }
  27751. if (parsedMesh.hasMatricesWeights) {
  27752. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27753. }
  27754. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  27755. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  27756. mesh._checkDelayState();
  27757. }
  27758. }
  27759. else {
  27760. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  27761. }
  27762. // Material
  27763. if (parsedMesh.materialId) {
  27764. mesh.setMaterialByID(parsedMesh.materialId);
  27765. }
  27766. else {
  27767. mesh.material = null;
  27768. }
  27769. // Morph targets
  27770. if (parsedMesh.morphTargetManagerId > -1) {
  27771. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  27772. }
  27773. // Skeleton
  27774. if (parsedMesh.skeletonId > -1) {
  27775. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  27776. if (parsedMesh.numBoneInfluencers) {
  27777. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  27778. }
  27779. }
  27780. // Animations
  27781. if (parsedMesh.animations) {
  27782. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27783. var parsedAnimation = parsedMesh.animations[animationIndex];
  27784. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27785. }
  27786. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  27787. }
  27788. if (parsedMesh.autoAnimate) {
  27789. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  27790. }
  27791. // Layer Mask
  27792. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  27793. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  27794. }
  27795. else {
  27796. mesh.layerMask = 0x0FFFFFFF;
  27797. }
  27798. // Physics
  27799. if (parsedMesh.physicsImpostor) {
  27800. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  27801. mass: parsedMesh.physicsMass,
  27802. friction: parsedMesh.physicsFriction,
  27803. restitution: parsedMesh.physicsRestitution
  27804. }, scene);
  27805. }
  27806. // Instances
  27807. if (parsedMesh.instances) {
  27808. for (var index = 0; index < parsedMesh.instances.length; index++) {
  27809. var parsedInstance = parsedMesh.instances[index];
  27810. var instance = mesh.createInstance(parsedInstance.name);
  27811. if (parsedInstance.id) {
  27812. instance.id = parsedInstance.id;
  27813. }
  27814. if (BABYLON.Tags) {
  27815. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  27816. }
  27817. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  27818. if (parsedInstance.parentId) {
  27819. instance._waitingParentId = parsedInstance.parentId;
  27820. }
  27821. if (parsedInstance.rotationQuaternion) {
  27822. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  27823. }
  27824. else if (parsedInstance.rotation) {
  27825. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  27826. }
  27827. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  27828. instance.checkCollisions = mesh.checkCollisions;
  27829. if (parsedMesh.animations) {
  27830. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27831. parsedAnimation = parsedMesh.animations[animationIndex];
  27832. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27833. }
  27834. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  27835. }
  27836. }
  27837. }
  27838. return mesh;
  27839. };
  27840. /**
  27841. * Creates a ribbon mesh.
  27842. * Please consider using the same method from the MeshBuilder class instead.
  27843. * 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.
  27844. *
  27845. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  27846. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  27847. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  27848. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  27849. * 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.
  27850. * 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.
  27851. * 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
  27852. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27853. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27854. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27855. */
  27856. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  27857. if (closeArray === void 0) { closeArray = false; }
  27858. if (updatable === void 0) { updatable = false; }
  27859. return BABYLON.MeshBuilder.CreateRibbon(name, {
  27860. pathArray: pathArray,
  27861. closeArray: closeArray,
  27862. closePath: closePath,
  27863. offset: offset,
  27864. updatable: updatable,
  27865. sideOrientation: sideOrientation,
  27866. instance: instance
  27867. }, scene);
  27868. };
  27869. /**
  27870. * Creates a plane polygonal mesh. By default, this is a disc.
  27871. * Please consider using the same method from the MeshBuilder class instead.
  27872. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  27873. * 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.
  27874. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27875. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27876. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27877. */
  27878. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  27879. if (scene === void 0) { scene = null; }
  27880. var options = {
  27881. radius: radius,
  27882. tessellation: tessellation,
  27883. sideOrientation: sideOrientation,
  27884. updatable: updatable
  27885. };
  27886. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  27887. };
  27888. /**
  27889. * Creates a box mesh.
  27890. * Please consider using the same method from the MeshBuilder class instead.
  27891. * The parameter `size` sets the size (float) of each box side (default 1).
  27892. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27893. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27894. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27895. */
  27896. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27897. if (scene === void 0) { scene = null; }
  27898. var options = {
  27899. size: size,
  27900. sideOrientation: sideOrientation,
  27901. updatable: updatable
  27902. };
  27903. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27904. };
  27905. /**
  27906. * Creates a sphere mesh.
  27907. * Please consider using the same method from the MeshBuilder class instead.
  27908. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27909. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27910. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27911. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27912. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27913. */
  27914. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27915. var options = {
  27916. segments: segments,
  27917. diameterX: diameter,
  27918. diameterY: diameter,
  27919. diameterZ: diameter,
  27920. sideOrientation: sideOrientation,
  27921. updatable: updatable
  27922. };
  27923. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27924. };
  27925. /**
  27926. * Creates a cylinder or a cone mesh.
  27927. * Please consider using the same method from the MeshBuilder class instead.
  27928. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27929. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27930. * 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.
  27931. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27932. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27933. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27934. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27935. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27936. */
  27937. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27938. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27939. if (scene !== undefined) {
  27940. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27941. updatable = scene;
  27942. }
  27943. scene = subdivisions;
  27944. subdivisions = 1;
  27945. }
  27946. var options = {
  27947. height: height,
  27948. diameterTop: diameterTop,
  27949. diameterBottom: diameterBottom,
  27950. tessellation: tessellation,
  27951. subdivisions: subdivisions,
  27952. sideOrientation: sideOrientation,
  27953. updatable: updatable
  27954. };
  27955. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27956. };
  27957. // Torus (Code from SharpDX.org)
  27958. /**
  27959. * Creates a torus mesh.
  27960. * Please consider using the same method from the MeshBuilder class instead.
  27961. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27962. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27963. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27964. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27965. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27966. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27967. */
  27968. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27969. var options = {
  27970. diameter: diameter,
  27971. thickness: thickness,
  27972. tessellation: tessellation,
  27973. sideOrientation: sideOrientation,
  27974. updatable: updatable
  27975. };
  27976. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27977. };
  27978. /**
  27979. * Creates a torus knot mesh.
  27980. * Please consider using the same method from the MeshBuilder class instead.
  27981. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27982. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27983. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27984. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27985. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27986. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27988. */
  27989. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  27990. var options = {
  27991. radius: radius,
  27992. tube: tube,
  27993. radialSegments: radialSegments,
  27994. tubularSegments: tubularSegments,
  27995. p: p,
  27996. q: q,
  27997. sideOrientation: sideOrientation,
  27998. updatable: updatable
  27999. };
  28000. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  28001. };
  28002. /**
  28003. * Creates a line mesh.
  28004. * Please consider using the same method from the MeshBuilder class instead.
  28005. * 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.
  28006. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28007. * The parameter `points` is an array successive Vector3.
  28008. * 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
  28009. * When updating an instance, remember that only point positions can change, not the number of points.
  28010. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28011. */
  28012. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  28013. if (scene === void 0) { scene = null; }
  28014. if (updatable === void 0) { updatable = false; }
  28015. if (instance === void 0) { instance = null; }
  28016. var options = {
  28017. points: points,
  28018. updatable: updatable,
  28019. instance: instance
  28020. };
  28021. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  28022. };
  28023. /**
  28024. * Creates a dashed line mesh.
  28025. * Please consider using the same method from the MeshBuilder class instead.
  28026. * 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.
  28027. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28028. * The parameter `points` is an array successive Vector3.
  28029. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28030. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28031. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28032. * 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
  28033. * When updating an instance, remember that only point positions can change, not the number of points.
  28034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28035. */
  28036. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  28037. if (scene === void 0) { scene = null; }
  28038. var options = {
  28039. points: points,
  28040. dashSize: dashSize,
  28041. gapSize: gapSize,
  28042. dashNb: dashNb,
  28043. updatable: updatable,
  28044. instance: instance
  28045. };
  28046. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  28047. };
  28048. /**
  28049. * Creates a polygon mesh.
  28050. * Please consider using the same method from the MeshBuilder class instead.
  28051. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  28052. * 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.
  28053. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28054. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28055. * Remember you can only change the shape positions, not their number when updating a polygon.
  28056. */
  28057. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  28058. var options = {
  28059. shape: shape,
  28060. holes: holes,
  28061. updatable: updatable,
  28062. sideOrientation: sideOrientation
  28063. };
  28064. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  28065. };
  28066. /**
  28067. * Creates an extruded polygon mesh, with depth in the Y direction.
  28068. * Please consider using the same method from the MeshBuilder class instead.
  28069. */
  28070. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  28071. var options = {
  28072. shape: shape,
  28073. holes: holes,
  28074. depth: depth,
  28075. updatable: updatable,
  28076. sideOrientation: sideOrientation
  28077. };
  28078. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  28079. };
  28080. /**
  28081. * Creates an extruded shape mesh.
  28082. * 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.
  28083. * Please consider using the same method from the MeshBuilder class instead.
  28084. *
  28085. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28086. * 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
  28087. * extruded along the Z axis.
  28088. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28089. * 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.
  28090. * The parameter `scale` (float, default 1) is the value to scale the shape.
  28091. * 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
  28092. * 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
  28093. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28094. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28095. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28096. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28097. */
  28098. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  28099. if (scene === void 0) { scene = null; }
  28100. var options = {
  28101. shape: shape,
  28102. path: path,
  28103. scale: scale,
  28104. rotation: rotation,
  28105. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28106. sideOrientation: sideOrientation,
  28107. instance: instance,
  28108. updatable: updatable
  28109. };
  28110. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  28111. };
  28112. /**
  28113. * Creates an custom extruded shape mesh.
  28114. * 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.
  28115. * Please consider using the same method from the MeshBuilder class instead.
  28116. *
  28117. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28118. * 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
  28119. * extruded along the Z axis.
  28120. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28121. * 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
  28122. * and the distance of this point from the begining of the path :
  28123. * ```javascript
  28124. * var rotationFunction = function(i, distance) {
  28125. * // do things
  28126. * return rotationValue; }
  28127. * ```
  28128. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  28129. * 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
  28130. * and the distance of this point from the begining of the path :
  28131. * ```javascript
  28132. * var scaleFunction = function(i, distance) {
  28133. * // do things
  28134. * return scaleValue;}
  28135. * ```
  28136. * It must returns a float value that will be the scale value applied to the shape on each path point.
  28137. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  28138. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  28139. * 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
  28140. * 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
  28141. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28142. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28143. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28144. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28145. */
  28146. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  28147. var options = {
  28148. shape: shape,
  28149. path: path,
  28150. scaleFunction: scaleFunction,
  28151. rotationFunction: rotationFunction,
  28152. ribbonCloseArray: ribbonCloseArray,
  28153. ribbonClosePath: ribbonClosePath,
  28154. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  28155. sideOrientation: sideOrientation,
  28156. instance: instance,
  28157. updatable: updatable
  28158. };
  28159. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  28160. };
  28161. /**
  28162. * Creates lathe mesh.
  28163. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  28164. * Please consider using the same method from the MeshBuilder class instead.
  28165. * 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
  28166. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  28167. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  28168. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  28169. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28170. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28171. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28172. */
  28173. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  28174. var options = {
  28175. shape: shape,
  28176. radius: radius,
  28177. tessellation: tessellation,
  28178. sideOrientation: sideOrientation,
  28179. updatable: updatable
  28180. };
  28181. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  28182. };
  28183. /**
  28184. * Creates a plane mesh.
  28185. * Please consider using the same method from the MeshBuilder class instead.
  28186. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  28187. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28188. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28189. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28190. */
  28191. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  28192. var options = {
  28193. size: size,
  28194. width: size,
  28195. height: size,
  28196. sideOrientation: sideOrientation,
  28197. updatable: updatable
  28198. };
  28199. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  28200. };
  28201. /**
  28202. * Creates a ground mesh.
  28203. * Please consider using the same method from the MeshBuilder class instead.
  28204. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  28205. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  28206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28207. */
  28208. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  28209. var options = {
  28210. width: width,
  28211. height: height,
  28212. subdivisions: subdivisions,
  28213. updatable: updatable
  28214. };
  28215. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  28216. };
  28217. /**
  28218. * Creates a tiled ground mesh.
  28219. * Please consider using the same method from the MeshBuilder class instead.
  28220. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  28221. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  28222. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  28223. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  28224. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  28225. * numbers of subdivisions on the ground width and height of each tile.
  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.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  28229. var options = {
  28230. xmin: xmin,
  28231. zmin: zmin,
  28232. xmax: xmax,
  28233. zmax: zmax,
  28234. subdivisions: subdivisions,
  28235. precision: precision,
  28236. updatable: updatable
  28237. };
  28238. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  28239. };
  28240. /**
  28241. * Creates a ground mesh from a height map.
  28242. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  28243. * Please consider using the same method from the MeshBuilder class instead.
  28244. * The parameter `url` sets the URL of the height map image resource.
  28245. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  28246. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  28247. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  28248. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  28249. * 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).
  28250. * This function is passed the newly built mesh :
  28251. * ```javascript
  28252. * function(mesh) { // do things
  28253. * return; }
  28254. * ```
  28255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28256. */
  28257. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  28258. var options = {
  28259. width: width,
  28260. height: height,
  28261. subdivisions: subdivisions,
  28262. minHeight: minHeight,
  28263. maxHeight: maxHeight,
  28264. updatable: updatable,
  28265. onReady: onReady
  28266. };
  28267. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  28268. };
  28269. /**
  28270. * Creates a tube mesh.
  28271. * 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.
  28272. * Please consider using the same method from the MeshBuilder class instead.
  28273. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  28274. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  28275. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  28276. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  28277. * 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.
  28278. * It must return a radius value (positive float) :
  28279. * ```javascript
  28280. * var radiusFunction = function(i, distance) {
  28281. * // do things
  28282. * return radius; }
  28283. * ```
  28284. * 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
  28285. * 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
  28286. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28287. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28288. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28289. */
  28290. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  28291. var options = {
  28292. path: path,
  28293. radius: radius,
  28294. tessellation: tessellation,
  28295. radiusFunction: radiusFunction,
  28296. arc: 1,
  28297. cap: cap,
  28298. updatable: updatable,
  28299. sideOrientation: sideOrientation,
  28300. instance: instance
  28301. };
  28302. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  28303. };
  28304. /**
  28305. * Creates a polyhedron mesh.
  28306. * Please consider using the same method from the MeshBuilder class instead.
  28307. * 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
  28308. * to choose the wanted type.
  28309. * The parameter `size` (positive float, default 1) sets the polygon size.
  28310. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  28311. * 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`.
  28312. * 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
  28313. * 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)`).
  28314. * 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
  28315. * 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.
  28316. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28317. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28318. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28319. */
  28320. Mesh.CreatePolyhedron = function (name, options, scene) {
  28321. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  28322. };
  28323. /**
  28324. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28325. * Please consider using the same method from the MeshBuilder class instead.
  28326. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28327. * 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`).
  28328. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28329. * 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.
  28330. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28331. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28332. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28333. */
  28334. Mesh.CreateIcoSphere = function (name, options, scene) {
  28335. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  28336. };
  28337. /**
  28338. * Creates a decal mesh.
  28339. * Please consider using the same method from the MeshBuilder class instead.
  28340. * 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.
  28341. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  28342. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  28343. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  28344. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  28345. */
  28346. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  28347. var options = {
  28348. position: position,
  28349. normal: normal,
  28350. size: size,
  28351. angle: angle
  28352. };
  28353. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  28354. };
  28355. // Skeletons
  28356. /**
  28357. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28358. */
  28359. Mesh.prototype.setPositionsForCPUSkinning = function () {
  28360. if (!this._sourcePositions) {
  28361. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28362. if (!source) {
  28363. return this._sourcePositions;
  28364. }
  28365. this._sourcePositions = new Float32Array(source);
  28366. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  28367. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  28368. }
  28369. }
  28370. return this._sourcePositions;
  28371. };
  28372. /**
  28373. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28374. */
  28375. Mesh.prototype.setNormalsForCPUSkinning = function () {
  28376. if (!this._sourceNormals) {
  28377. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28378. if (!source) {
  28379. return this._sourceNormals;
  28380. }
  28381. this._sourceNormals = new Float32Array(source);
  28382. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  28383. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  28384. }
  28385. }
  28386. return this._sourceNormals;
  28387. };
  28388. /**
  28389. * Updates the vertex buffer by applying transformation from the bones.
  28390. * Returns the Mesh.
  28391. *
  28392. * @param {skeleton} skeleton to apply
  28393. */
  28394. Mesh.prototype.applySkeleton = function (skeleton) {
  28395. if (!this.geometry) {
  28396. return this;
  28397. }
  28398. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  28399. return this;
  28400. }
  28401. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  28402. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28403. return this;
  28404. }
  28405. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28406. return this;
  28407. }
  28408. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28409. return this;
  28410. }
  28411. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28412. return this;
  28413. }
  28414. if (!this._sourcePositions) {
  28415. var submeshes = this.subMeshes.slice();
  28416. this.setPositionsForCPUSkinning();
  28417. this.subMeshes = submeshes;
  28418. }
  28419. if (!this._sourceNormals) {
  28420. this.setNormalsForCPUSkinning();
  28421. }
  28422. // positionsData checks for not being Float32Array will only pass at most once
  28423. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28424. if (!positionsData) {
  28425. return this;
  28426. }
  28427. if (!(positionsData instanceof Float32Array)) {
  28428. positionsData = new Float32Array(positionsData);
  28429. }
  28430. // normalsData checks for not being Float32Array will only pass at most once
  28431. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28432. if (!normalsData) {
  28433. return this;
  28434. }
  28435. if (!(normalsData instanceof Float32Array)) {
  28436. normalsData = new Float32Array(normalsData);
  28437. }
  28438. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28439. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28440. if (!matricesWeightsData || !matricesIndicesData) {
  28441. return this;
  28442. }
  28443. var needExtras = this.numBoneInfluencers > 4;
  28444. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28445. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28446. var skeletonMatrices = skeleton.getTransformMatrices(this);
  28447. var tempVector3 = BABYLON.Vector3.Zero();
  28448. var finalMatrix = new BABYLON.Matrix();
  28449. var tempMatrix = new BABYLON.Matrix();
  28450. var matWeightIdx = 0;
  28451. var inf;
  28452. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  28453. var weight;
  28454. for (inf = 0; inf < 4; inf++) {
  28455. weight = matricesWeightsData[matWeightIdx + inf];
  28456. if (weight > 0) {
  28457. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28458. finalMatrix.addToSelf(tempMatrix);
  28459. }
  28460. else
  28461. break;
  28462. }
  28463. if (needExtras) {
  28464. for (inf = 0; inf < 4; inf++) {
  28465. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28466. if (weight > 0) {
  28467. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28468. finalMatrix.addToSelf(tempMatrix);
  28469. }
  28470. else
  28471. break;
  28472. }
  28473. }
  28474. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  28475. tempVector3.toArray(positionsData, index);
  28476. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  28477. tempVector3.toArray(normalsData, index);
  28478. finalMatrix.reset();
  28479. }
  28480. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  28481. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  28482. return this;
  28483. };
  28484. // Tools
  28485. /**
  28486. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  28487. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  28488. */
  28489. Mesh.MinMax = function (meshes) {
  28490. var minVector = null;
  28491. var maxVector = null;
  28492. meshes.forEach(function (mesh, index, array) {
  28493. var boundingInfo = mesh.getBoundingInfo();
  28494. var boundingBox = boundingInfo.boundingBox;
  28495. if (!minVector || !maxVector) {
  28496. minVector = boundingBox.minimumWorld;
  28497. maxVector = boundingBox.maximumWorld;
  28498. }
  28499. else {
  28500. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  28501. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  28502. }
  28503. });
  28504. if (!minVector || !maxVector) {
  28505. return {
  28506. min: BABYLON.Vector3.Zero(),
  28507. max: BABYLON.Vector3.Zero()
  28508. };
  28509. }
  28510. return {
  28511. min: minVector,
  28512. max: maxVector
  28513. };
  28514. };
  28515. /**
  28516. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  28517. */
  28518. Mesh.Center = function (meshesOrMinMaxVector) {
  28519. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  28520. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  28521. };
  28522. /**
  28523. * Merge the array of meshes into a single mesh for performance reasons.
  28524. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  28525. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  28526. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  28527. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  28528. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  28529. */
  28530. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  28531. if (disposeSource === void 0) { disposeSource = true; }
  28532. var index;
  28533. if (!allow32BitsIndices) {
  28534. var totalVertices = 0;
  28535. // Counting vertices
  28536. for (index = 0; index < meshes.length; index++) {
  28537. if (meshes[index]) {
  28538. totalVertices += meshes[index].getTotalVertices();
  28539. if (totalVertices > 65536) {
  28540. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  28541. return null;
  28542. }
  28543. }
  28544. }
  28545. }
  28546. // Merge
  28547. var vertexData = null;
  28548. var otherVertexData;
  28549. var indiceArray = new Array();
  28550. var source = null;
  28551. for (index = 0; index < meshes.length; index++) {
  28552. if (meshes[index]) {
  28553. meshes[index].computeWorldMatrix(true);
  28554. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  28555. otherVertexData.transform(meshes[index].getWorldMatrix());
  28556. if (vertexData) {
  28557. vertexData.merge(otherVertexData);
  28558. }
  28559. else {
  28560. vertexData = otherVertexData;
  28561. source = meshes[index];
  28562. }
  28563. if (subdivideWithSubMeshes) {
  28564. indiceArray.push(meshes[index].getTotalIndices());
  28565. }
  28566. }
  28567. }
  28568. source = source;
  28569. if (!meshSubclass) {
  28570. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  28571. }
  28572. vertexData.applyToMesh(meshSubclass);
  28573. // Setting properties
  28574. meshSubclass.material = source.material;
  28575. meshSubclass.checkCollisions = source.checkCollisions;
  28576. // Cleaning
  28577. if (disposeSource) {
  28578. for (index = 0; index < meshes.length; index++) {
  28579. if (meshes[index]) {
  28580. meshes[index].dispose();
  28581. }
  28582. }
  28583. }
  28584. // Subdivide
  28585. if (subdivideWithSubMeshes) {
  28586. //-- Suppresions du submesh global
  28587. meshSubclass.releaseSubMeshes();
  28588. index = 0;
  28589. var offset = 0;
  28590. //-- aplique la subdivision en fonction du tableau d'indices
  28591. while (index < indiceArray.length) {
  28592. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  28593. offset += indiceArray[index];
  28594. index++;
  28595. }
  28596. }
  28597. return meshSubclass;
  28598. };
  28599. // Consts
  28600. Mesh._FRONTSIDE = 0;
  28601. Mesh._BACKSIDE = 1;
  28602. Mesh._DOUBLESIDE = 2;
  28603. Mesh._DEFAULTSIDE = 0;
  28604. Mesh._NO_CAP = 0;
  28605. Mesh._CAP_START = 1;
  28606. Mesh._CAP_END = 2;
  28607. Mesh._CAP_ALL = 3;
  28608. return Mesh;
  28609. }(BABYLON.AbstractMesh));
  28610. BABYLON.Mesh = Mesh;
  28611. })(BABYLON || (BABYLON = {}));
  28612. //# sourceMappingURL=babylon.mesh.js.map
  28613. var BABYLON;
  28614. (function (BABYLON) {
  28615. var BaseSubMesh = /** @class */ (function () {
  28616. function BaseSubMesh() {
  28617. }
  28618. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  28619. get: function () {
  28620. return this._materialEffect;
  28621. },
  28622. enumerable: true,
  28623. configurable: true
  28624. });
  28625. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  28626. if (defines === void 0) { defines = null; }
  28627. if (this._materialEffect === effect) {
  28628. if (!effect) {
  28629. this._materialDefines = null;
  28630. }
  28631. return;
  28632. }
  28633. this._materialDefines = defines;
  28634. this._materialEffect = effect;
  28635. };
  28636. return BaseSubMesh;
  28637. }());
  28638. BABYLON.BaseSubMesh = BaseSubMesh;
  28639. var SubMesh = /** @class */ (function (_super) {
  28640. __extends(SubMesh, _super);
  28641. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28642. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28643. var _this = _super.call(this) || this;
  28644. _this.materialIndex = materialIndex;
  28645. _this.verticesStart = verticesStart;
  28646. _this.verticesCount = verticesCount;
  28647. _this.indexStart = indexStart;
  28648. _this.indexCount = indexCount;
  28649. _this._renderId = 0;
  28650. _this._mesh = mesh;
  28651. _this._renderingMesh = renderingMesh || mesh;
  28652. mesh.subMeshes.push(_this);
  28653. _this._trianglePlanes = [];
  28654. _this._id = mesh.subMeshes.length - 1;
  28655. if (createBoundingBox) {
  28656. _this.refreshBoundingInfo();
  28657. mesh.computeWorldMatrix(true);
  28658. }
  28659. return _this;
  28660. }
  28661. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28662. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28663. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  28664. };
  28665. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  28666. get: function () {
  28667. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  28668. },
  28669. enumerable: true,
  28670. configurable: true
  28671. });
  28672. /**
  28673. * Returns the submesh BoudingInfo object.
  28674. */
  28675. SubMesh.prototype.getBoundingInfo = function () {
  28676. if (this.IsGlobal) {
  28677. return this._mesh.getBoundingInfo();
  28678. }
  28679. return this._boundingInfo;
  28680. };
  28681. /**
  28682. * Sets the submesh BoundingInfo.
  28683. * Return the SubMesh.
  28684. */
  28685. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  28686. this._boundingInfo = boundingInfo;
  28687. return this;
  28688. };
  28689. /**
  28690. * Returns the mesh of the current submesh.
  28691. */
  28692. SubMesh.prototype.getMesh = function () {
  28693. return this._mesh;
  28694. };
  28695. /**
  28696. * Returns the rendering mesh of the submesh.
  28697. */
  28698. SubMesh.prototype.getRenderingMesh = function () {
  28699. return this._renderingMesh;
  28700. };
  28701. /**
  28702. * Returns the submesh material.
  28703. */
  28704. SubMesh.prototype.getMaterial = function () {
  28705. var rootMaterial = this._renderingMesh.material;
  28706. if (rootMaterial === null || rootMaterial === undefined) {
  28707. return this._mesh.getScene().defaultMaterial;
  28708. }
  28709. else if (rootMaterial.getSubMaterial) {
  28710. var multiMaterial = rootMaterial;
  28711. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28712. if (this._currentMaterial !== effectiveMaterial) {
  28713. this._currentMaterial = effectiveMaterial;
  28714. this._materialDefines = null;
  28715. }
  28716. return effectiveMaterial;
  28717. }
  28718. return rootMaterial;
  28719. };
  28720. // Methods
  28721. /**
  28722. * Sets a new updated BoundingInfo object to the submesh.
  28723. * Returns the SubMesh.
  28724. */
  28725. SubMesh.prototype.refreshBoundingInfo = function () {
  28726. this._lastColliderWorldVertices = null;
  28727. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  28728. return this;
  28729. }
  28730. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28731. if (!data) {
  28732. this._boundingInfo = this._mesh.getBoundingInfo();
  28733. return this;
  28734. }
  28735. var indices = this._renderingMesh.getIndices();
  28736. var extend;
  28737. //is this the only submesh?
  28738. if (this.indexStart === 0 && this.indexCount === indices.length) {
  28739. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28740. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  28741. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  28742. }
  28743. else {
  28744. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  28745. }
  28746. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28747. return this;
  28748. };
  28749. SubMesh.prototype._checkCollision = function (collider) {
  28750. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28751. return boundingInfo._checkCollision(collider);
  28752. };
  28753. /**
  28754. * Updates the submesh BoundingInfo.
  28755. * Returns the Submesh.
  28756. */
  28757. SubMesh.prototype.updateBoundingInfo = function (world) {
  28758. var boundingInfo = this.getBoundingInfo();
  28759. if (!boundingInfo) {
  28760. this.refreshBoundingInfo();
  28761. boundingInfo = this.getBoundingInfo();
  28762. }
  28763. boundingInfo.update(world);
  28764. return this;
  28765. };
  28766. /**
  28767. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  28768. * Boolean returned.
  28769. */
  28770. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  28771. var boundingInfo = this.getBoundingInfo();
  28772. if (!boundingInfo) {
  28773. return false;
  28774. }
  28775. return boundingInfo.isInFrustum(frustumPlanes);
  28776. };
  28777. /**
  28778. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  28779. * Boolean returned.
  28780. */
  28781. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  28782. var boundingInfo = this.getBoundingInfo();
  28783. if (!boundingInfo) {
  28784. return false;
  28785. }
  28786. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  28787. };
  28788. /**
  28789. * Renders the submesh.
  28790. * Returns it.
  28791. */
  28792. SubMesh.prototype.render = function (enableAlphaMode) {
  28793. this._renderingMesh.render(this, enableAlphaMode);
  28794. return this;
  28795. };
  28796. /**
  28797. * Returns a new Index Buffer.
  28798. * Type returned : WebGLBuffer.
  28799. */
  28800. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  28801. if (!this._linesIndexBuffer) {
  28802. var linesIndices = [];
  28803. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28804. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  28805. }
  28806. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  28807. this.linesIndexCount = linesIndices.length;
  28808. }
  28809. return this._linesIndexBuffer;
  28810. };
  28811. /**
  28812. * True is the passed Ray intersects the submesh bounding box.
  28813. * Boolean returned.
  28814. */
  28815. SubMesh.prototype.canIntersects = function (ray) {
  28816. var boundingInfo = this.getBoundingInfo();
  28817. if (!boundingInfo) {
  28818. return false;
  28819. }
  28820. return ray.intersectsBox(boundingInfo.boundingBox);
  28821. };
  28822. /**
  28823. * Returns an object IntersectionInfo.
  28824. */
  28825. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  28826. var intersectInfo = null;
  28827. // LineMesh first as it's also a Mesh...
  28828. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  28829. var lineMesh = this._mesh;
  28830. // Line test
  28831. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  28832. var p0 = positions[indices[index]];
  28833. var p1 = positions[indices[index + 1]];
  28834. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  28835. if (length < 0) {
  28836. continue;
  28837. }
  28838. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  28839. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  28840. if (fastCheck) {
  28841. break;
  28842. }
  28843. }
  28844. }
  28845. }
  28846. else {
  28847. // Triangles test
  28848. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28849. var p0 = positions[indices[index]];
  28850. var p1 = positions[indices[index + 1]];
  28851. var p2 = positions[indices[index + 2]];
  28852. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  28853. if (currentIntersectInfo) {
  28854. if (currentIntersectInfo.distance < 0) {
  28855. continue;
  28856. }
  28857. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  28858. intersectInfo = currentIntersectInfo;
  28859. intersectInfo.faceId = index / 3;
  28860. if (fastCheck) {
  28861. break;
  28862. }
  28863. }
  28864. }
  28865. }
  28866. }
  28867. return intersectInfo;
  28868. };
  28869. SubMesh.prototype._rebuild = function () {
  28870. if (this._linesIndexBuffer) {
  28871. this._linesIndexBuffer = null;
  28872. }
  28873. };
  28874. // Clone
  28875. /**
  28876. * Creates a new Submesh from the passed Mesh.
  28877. */
  28878. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  28879. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  28880. if (!this.IsGlobal) {
  28881. var boundingInfo = this.getBoundingInfo();
  28882. if (!boundingInfo) {
  28883. return result;
  28884. }
  28885. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  28886. }
  28887. return result;
  28888. };
  28889. // Dispose
  28890. /**
  28891. * Disposes the Submesh.
  28892. * Returns nothing.
  28893. */
  28894. SubMesh.prototype.dispose = function () {
  28895. if (this._linesIndexBuffer) {
  28896. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28897. this._linesIndexBuffer = null;
  28898. }
  28899. // Remove from mesh
  28900. var index = this._mesh.subMeshes.indexOf(this);
  28901. this._mesh.subMeshes.splice(index, 1);
  28902. };
  28903. // Statics
  28904. /**
  28905. * Creates a new Submesh from the passed parameters :
  28906. * - materialIndex (integer) : the index of the main mesh material.
  28907. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28908. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28909. * - mesh (Mesh) : the main mesh to create the submesh from.
  28910. * - renderingMesh (optional Mesh) : rendering mesh.
  28911. */
  28912. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28913. var minVertexIndex = Number.MAX_VALUE;
  28914. var maxVertexIndex = -Number.MAX_VALUE;
  28915. renderingMesh = (renderingMesh || mesh);
  28916. var indices = renderingMesh.getIndices();
  28917. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28918. var vertexIndex = indices[index];
  28919. if (vertexIndex < minVertexIndex)
  28920. minVertexIndex = vertexIndex;
  28921. if (vertexIndex > maxVertexIndex)
  28922. maxVertexIndex = vertexIndex;
  28923. }
  28924. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28925. };
  28926. return SubMesh;
  28927. }(BaseSubMesh));
  28928. BABYLON.SubMesh = SubMesh;
  28929. })(BABYLON || (BABYLON = {}));
  28930. //# sourceMappingURL=babylon.subMesh.js.map
  28931. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28932. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28933. s = arguments[i];
  28934. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28935. t[p] = s[p];
  28936. }
  28937. return t;
  28938. };
  28939. var BABYLON;
  28940. (function (BABYLON) {
  28941. var MaterialDefines = /** @class */ (function () {
  28942. function MaterialDefines() {
  28943. this._isDirty = true;
  28944. this._areLightsDirty = true;
  28945. this._areAttributesDirty = true;
  28946. this._areTexturesDirty = true;
  28947. this._areFresnelDirty = true;
  28948. this._areMiscDirty = true;
  28949. this._areImageProcessingDirty = true;
  28950. this._normals = false;
  28951. this._uvs = false;
  28952. this._needNormals = false;
  28953. this._needUVs = false;
  28954. }
  28955. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28956. get: function () {
  28957. return this._isDirty;
  28958. },
  28959. enumerable: true,
  28960. configurable: true
  28961. });
  28962. MaterialDefines.prototype.markAsProcessed = function () {
  28963. this._isDirty = false;
  28964. this._areAttributesDirty = false;
  28965. this._areTexturesDirty = false;
  28966. this._areFresnelDirty = false;
  28967. this._areLightsDirty = false;
  28968. this._areMiscDirty = false;
  28969. this._areImageProcessingDirty = false;
  28970. };
  28971. MaterialDefines.prototype.markAsUnprocessed = function () {
  28972. this._isDirty = true;
  28973. };
  28974. MaterialDefines.prototype.markAllAsDirty = function () {
  28975. this._areTexturesDirty = true;
  28976. this._areAttributesDirty = true;
  28977. this._areLightsDirty = true;
  28978. this._areFresnelDirty = true;
  28979. this._areMiscDirty = true;
  28980. this._areImageProcessingDirty = true;
  28981. this._isDirty = true;
  28982. };
  28983. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28984. this._areImageProcessingDirty = true;
  28985. this._isDirty = true;
  28986. };
  28987. MaterialDefines.prototype.markAsLightDirty = function () {
  28988. this._areLightsDirty = true;
  28989. this._isDirty = true;
  28990. };
  28991. MaterialDefines.prototype.markAsAttributesDirty = function () {
  28992. this._areAttributesDirty = true;
  28993. this._isDirty = true;
  28994. };
  28995. MaterialDefines.prototype.markAsTexturesDirty = function () {
  28996. this._areTexturesDirty = true;
  28997. this._isDirty = true;
  28998. };
  28999. MaterialDefines.prototype.markAsFresnelDirty = function () {
  29000. this._areFresnelDirty = true;
  29001. this._isDirty = true;
  29002. };
  29003. MaterialDefines.prototype.markAsMiscDirty = function () {
  29004. this._areMiscDirty = true;
  29005. this._isDirty = true;
  29006. };
  29007. MaterialDefines.prototype.rebuild = function () {
  29008. if (this._keys) {
  29009. delete this._keys;
  29010. }
  29011. this._keys = [];
  29012. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  29013. var key = _a[_i];
  29014. if (key[0] === "_") {
  29015. continue;
  29016. }
  29017. this._keys.push(key);
  29018. }
  29019. };
  29020. MaterialDefines.prototype.isEqual = function (other) {
  29021. if (this._keys.length !== other._keys.length) {
  29022. return false;
  29023. }
  29024. for (var index = 0; index < this._keys.length; index++) {
  29025. var prop = this._keys[index];
  29026. if (this[prop] !== other[prop]) {
  29027. return false;
  29028. }
  29029. }
  29030. return true;
  29031. };
  29032. MaterialDefines.prototype.cloneTo = function (other) {
  29033. if (this._keys.length !== other._keys.length) {
  29034. other._keys = this._keys.slice(0);
  29035. }
  29036. for (var index = 0; index < this._keys.length; index++) {
  29037. var prop = this._keys[index];
  29038. other[prop] = this[prop];
  29039. }
  29040. };
  29041. MaterialDefines.prototype.reset = function () {
  29042. for (var index = 0; index < this._keys.length; index++) {
  29043. var prop = this._keys[index];
  29044. if (typeof (this[prop]) === "number") {
  29045. this[prop] = 0;
  29046. }
  29047. else {
  29048. this[prop] = false;
  29049. }
  29050. }
  29051. };
  29052. MaterialDefines.prototype.toString = function () {
  29053. var result = "";
  29054. for (var index = 0; index < this._keys.length; index++) {
  29055. var prop = this._keys[index];
  29056. var value = this[prop];
  29057. if (typeof (value) === "number") {
  29058. result += "#define " + prop + " " + this[prop] + "\n";
  29059. }
  29060. else if (value) {
  29061. result += "#define " + prop + "\n";
  29062. }
  29063. }
  29064. return result;
  29065. };
  29066. return MaterialDefines;
  29067. }());
  29068. BABYLON.MaterialDefines = MaterialDefines;
  29069. var Material = /** @class */ (function () {
  29070. function Material(name, scene, doNotAdd) {
  29071. this.checkReadyOnEveryCall = false;
  29072. this.checkReadyOnlyOnce = false;
  29073. this.state = "";
  29074. this._alpha = 1.0;
  29075. this._backFaceCulling = true;
  29076. this.doNotSerialize = false;
  29077. this.storeEffectOnSubMeshes = false;
  29078. /**
  29079. * An event triggered when the material is disposed.
  29080. * @type {BABYLON.Observable}
  29081. */
  29082. this.onDisposeObservable = new BABYLON.Observable();
  29083. /**
  29084. * An event triggered when the material is bound.
  29085. * @type {BABYLON.Observable}
  29086. */
  29087. this.onBindObservable = new BABYLON.Observable();
  29088. /**
  29089. * An event triggered when the material is unbound.
  29090. * @type {BABYLON.Observable}
  29091. */
  29092. this.onUnBindObservable = new BABYLON.Observable();
  29093. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29094. this._needDepthPrePass = false;
  29095. this.disableDepthWrite = false;
  29096. this.forceDepthWrite = false;
  29097. this.separateCullingPass = false;
  29098. this._fogEnabled = true;
  29099. this.pointSize = 1.0;
  29100. this.zOffset = 0;
  29101. this._wasPreviouslyReady = false;
  29102. this._fillMode = Material.TriangleFillMode;
  29103. this.name = name;
  29104. this.id = name || BABYLON.Tools.RandomId();
  29105. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29106. if (this._scene.useRightHandedSystem) {
  29107. this.sideOrientation = Material.ClockWiseSideOrientation;
  29108. }
  29109. else {
  29110. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29111. }
  29112. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  29113. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  29114. if (!doNotAdd) {
  29115. this._scene.materials.push(this);
  29116. }
  29117. }
  29118. Object.defineProperty(Material, "TriangleFillMode", {
  29119. get: function () {
  29120. return Material._TriangleFillMode;
  29121. },
  29122. enumerable: true,
  29123. configurable: true
  29124. });
  29125. Object.defineProperty(Material, "WireFrameFillMode", {
  29126. get: function () {
  29127. return Material._WireFrameFillMode;
  29128. },
  29129. enumerable: true,
  29130. configurable: true
  29131. });
  29132. Object.defineProperty(Material, "PointFillMode", {
  29133. get: function () {
  29134. return Material._PointFillMode;
  29135. },
  29136. enumerable: true,
  29137. configurable: true
  29138. });
  29139. Object.defineProperty(Material, "PointListDrawMode", {
  29140. get: function () {
  29141. return Material._PointListDrawMode;
  29142. },
  29143. enumerable: true,
  29144. configurable: true
  29145. });
  29146. Object.defineProperty(Material, "LineListDrawMode", {
  29147. get: function () {
  29148. return Material._LineListDrawMode;
  29149. },
  29150. enumerable: true,
  29151. configurable: true
  29152. });
  29153. Object.defineProperty(Material, "LineLoopDrawMode", {
  29154. get: function () {
  29155. return Material._LineLoopDrawMode;
  29156. },
  29157. enumerable: true,
  29158. configurable: true
  29159. });
  29160. Object.defineProperty(Material, "LineStripDrawMode", {
  29161. get: function () {
  29162. return Material._LineStripDrawMode;
  29163. },
  29164. enumerable: true,
  29165. configurable: true
  29166. });
  29167. Object.defineProperty(Material, "TriangleStripDrawMode", {
  29168. get: function () {
  29169. return Material._TriangleStripDrawMode;
  29170. },
  29171. enumerable: true,
  29172. configurable: true
  29173. });
  29174. Object.defineProperty(Material, "TriangleFanDrawMode", {
  29175. get: function () {
  29176. return Material._TriangleFanDrawMode;
  29177. },
  29178. enumerable: true,
  29179. configurable: true
  29180. });
  29181. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29182. get: function () {
  29183. return Material._ClockWiseSideOrientation;
  29184. },
  29185. enumerable: true,
  29186. configurable: true
  29187. });
  29188. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29189. get: function () {
  29190. return Material._CounterClockWiseSideOrientation;
  29191. },
  29192. enumerable: true,
  29193. configurable: true
  29194. });
  29195. Object.defineProperty(Material, "TextureDirtyFlag", {
  29196. get: function () {
  29197. return Material._TextureDirtyFlag;
  29198. },
  29199. enumerable: true,
  29200. configurable: true
  29201. });
  29202. Object.defineProperty(Material, "LightDirtyFlag", {
  29203. get: function () {
  29204. return Material._LightDirtyFlag;
  29205. },
  29206. enumerable: true,
  29207. configurable: true
  29208. });
  29209. Object.defineProperty(Material, "FresnelDirtyFlag", {
  29210. get: function () {
  29211. return Material._FresnelDirtyFlag;
  29212. },
  29213. enumerable: true,
  29214. configurable: true
  29215. });
  29216. Object.defineProperty(Material, "AttributesDirtyFlag", {
  29217. get: function () {
  29218. return Material._AttributesDirtyFlag;
  29219. },
  29220. enumerable: true,
  29221. configurable: true
  29222. });
  29223. Object.defineProperty(Material, "MiscDirtyFlag", {
  29224. get: function () {
  29225. return Material._MiscDirtyFlag;
  29226. },
  29227. enumerable: true,
  29228. configurable: true
  29229. });
  29230. Object.defineProperty(Material.prototype, "alpha", {
  29231. get: function () {
  29232. return this._alpha;
  29233. },
  29234. set: function (value) {
  29235. if (this._alpha === value) {
  29236. return;
  29237. }
  29238. this._alpha = value;
  29239. this.markAsDirty(Material.MiscDirtyFlag);
  29240. },
  29241. enumerable: true,
  29242. configurable: true
  29243. });
  29244. Object.defineProperty(Material.prototype, "backFaceCulling", {
  29245. get: function () {
  29246. return this._backFaceCulling;
  29247. },
  29248. set: function (value) {
  29249. if (this._backFaceCulling === value) {
  29250. return;
  29251. }
  29252. this._backFaceCulling = value;
  29253. this.markAsDirty(Material.TextureDirtyFlag);
  29254. },
  29255. enumerable: true,
  29256. configurable: true
  29257. });
  29258. Object.defineProperty(Material.prototype, "onDispose", {
  29259. set: function (callback) {
  29260. if (this._onDisposeObserver) {
  29261. this.onDisposeObservable.remove(this._onDisposeObserver);
  29262. }
  29263. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29264. },
  29265. enumerable: true,
  29266. configurable: true
  29267. });
  29268. Object.defineProperty(Material.prototype, "onBind", {
  29269. set: function (callback) {
  29270. if (this._onBindObserver) {
  29271. this.onBindObservable.remove(this._onBindObserver);
  29272. }
  29273. this._onBindObserver = this.onBindObservable.add(callback);
  29274. },
  29275. enumerable: true,
  29276. configurable: true
  29277. });
  29278. Object.defineProperty(Material.prototype, "alphaMode", {
  29279. get: function () {
  29280. return this._alphaMode;
  29281. },
  29282. set: function (value) {
  29283. if (this._alphaMode === value) {
  29284. return;
  29285. }
  29286. this._alphaMode = value;
  29287. this.markAsDirty(Material.TextureDirtyFlag);
  29288. },
  29289. enumerable: true,
  29290. configurable: true
  29291. });
  29292. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  29293. get: function () {
  29294. return this._needDepthPrePass;
  29295. },
  29296. set: function (value) {
  29297. if (this._needDepthPrePass === value) {
  29298. return;
  29299. }
  29300. this._needDepthPrePass = value;
  29301. if (this._needDepthPrePass) {
  29302. this.checkReadyOnEveryCall = true;
  29303. }
  29304. },
  29305. enumerable: true,
  29306. configurable: true
  29307. });
  29308. Object.defineProperty(Material.prototype, "fogEnabled", {
  29309. get: function () {
  29310. return this._fogEnabled;
  29311. },
  29312. set: function (value) {
  29313. if (this._fogEnabled === value) {
  29314. return;
  29315. }
  29316. this._fogEnabled = value;
  29317. this.markAsDirty(Material.MiscDirtyFlag);
  29318. },
  29319. enumerable: true,
  29320. configurable: true
  29321. });
  29322. Object.defineProperty(Material.prototype, "wireframe", {
  29323. get: function () {
  29324. return this._fillMode === Material.WireFrameFillMode;
  29325. },
  29326. set: function (value) {
  29327. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29328. },
  29329. enumerable: true,
  29330. configurable: true
  29331. });
  29332. Object.defineProperty(Material.prototype, "pointsCloud", {
  29333. get: function () {
  29334. return this._fillMode === Material.PointFillMode;
  29335. },
  29336. set: function (value) {
  29337. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29338. },
  29339. enumerable: true,
  29340. configurable: true
  29341. });
  29342. Object.defineProperty(Material.prototype, "fillMode", {
  29343. get: function () {
  29344. return this._fillMode;
  29345. },
  29346. set: function (value) {
  29347. if (this._fillMode === value) {
  29348. return;
  29349. }
  29350. this._fillMode = value;
  29351. this.markAsDirty(Material.MiscDirtyFlag);
  29352. },
  29353. enumerable: true,
  29354. configurable: true
  29355. });
  29356. /**
  29357. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29358. * subclasses should override adding information pertainent to themselves
  29359. */
  29360. Material.prototype.toString = function (fullDetails) {
  29361. var ret = "Name: " + this.name;
  29362. if (fullDetails) {
  29363. }
  29364. return ret;
  29365. };
  29366. /**
  29367. * Child classes can use it to update shaders
  29368. */
  29369. Material.prototype.getClassName = function () {
  29370. return "Material";
  29371. };
  29372. Object.defineProperty(Material.prototype, "isFrozen", {
  29373. get: function () {
  29374. return this.checkReadyOnlyOnce;
  29375. },
  29376. enumerable: true,
  29377. configurable: true
  29378. });
  29379. Material.prototype.freeze = function () {
  29380. this.checkReadyOnlyOnce = true;
  29381. };
  29382. Material.prototype.unfreeze = function () {
  29383. this.checkReadyOnlyOnce = false;
  29384. };
  29385. Material.prototype.isReady = function (mesh, useInstances) {
  29386. return true;
  29387. };
  29388. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29389. return false;
  29390. };
  29391. Material.prototype.getEffect = function () {
  29392. return this._effect;
  29393. };
  29394. Material.prototype.getScene = function () {
  29395. return this._scene;
  29396. };
  29397. Material.prototype.needAlphaBlending = function () {
  29398. return (this.alpha < 1.0);
  29399. };
  29400. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  29401. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  29402. };
  29403. Material.prototype.needAlphaTesting = function () {
  29404. return false;
  29405. };
  29406. Material.prototype.getAlphaTestTexture = function () {
  29407. return null;
  29408. };
  29409. Material.prototype.markDirty = function () {
  29410. this._wasPreviouslyReady = false;
  29411. };
  29412. Material.prototype._preBind = function (effect, overrideOrientation) {
  29413. if (overrideOrientation === void 0) { overrideOrientation = null; }
  29414. var engine = this._scene.getEngine();
  29415. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  29416. var reverse = orientation === Material.ClockWiseSideOrientation;
  29417. engine.enableEffect(effect ? effect : this._effect);
  29418. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29419. return reverse;
  29420. };
  29421. Material.prototype.bind = function (world, mesh) {
  29422. };
  29423. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29424. };
  29425. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29426. };
  29427. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  29428. sceneUbo.bindToEffect(effect, "Scene");
  29429. };
  29430. Material.prototype.bindView = function (effect) {
  29431. if (!this._useUBO) {
  29432. effect.setMatrix("view", this.getScene().getViewMatrix());
  29433. }
  29434. else {
  29435. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29436. }
  29437. };
  29438. Material.prototype.bindViewProjection = function (effect) {
  29439. if (!this._useUBO) {
  29440. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29441. }
  29442. else {
  29443. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29444. }
  29445. };
  29446. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  29447. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  29448. };
  29449. Material.prototype._afterBind = function (mesh) {
  29450. this._scene._cachedMaterial = this;
  29451. if (mesh) {
  29452. this._scene._cachedVisibility = mesh.visibility;
  29453. }
  29454. else {
  29455. this._scene._cachedVisibility = 1;
  29456. }
  29457. if (mesh) {
  29458. this.onBindObservable.notifyObservers(mesh);
  29459. }
  29460. if (this.disableDepthWrite) {
  29461. var engine = this._scene.getEngine();
  29462. this._cachedDepthWriteState = engine.getDepthWrite();
  29463. engine.setDepthWrite(false);
  29464. }
  29465. };
  29466. Material.prototype.unbind = function () {
  29467. this.onUnBindObservable.notifyObservers(this);
  29468. if (this.disableDepthWrite) {
  29469. var engine = this._scene.getEngine();
  29470. engine.setDepthWrite(this._cachedDepthWriteState);
  29471. }
  29472. };
  29473. Material.prototype.getActiveTextures = function () {
  29474. return [];
  29475. };
  29476. Material.prototype.hasTexture = function (texture) {
  29477. return false;
  29478. };
  29479. Material.prototype.clone = function (name) {
  29480. return null;
  29481. };
  29482. Material.prototype.getBindedMeshes = function () {
  29483. var result = new Array();
  29484. for (var index = 0; index < this._scene.meshes.length; index++) {
  29485. var mesh = this._scene.meshes[index];
  29486. if (mesh.material === this) {
  29487. result.push(mesh);
  29488. }
  29489. }
  29490. return result;
  29491. };
  29492. /**
  29493. * Force shader compilation including textures ready check
  29494. */
  29495. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  29496. var _this = this;
  29497. var localOptions = __assign({ clipPlane: false }, options);
  29498. var subMesh = new BABYLON.BaseSubMesh();
  29499. var scene = this.getScene();
  29500. var checkReady = function () {
  29501. if (!_this._scene || !_this._scene.getEngine()) {
  29502. return;
  29503. }
  29504. if (subMesh._materialDefines) {
  29505. subMesh._materialDefines._renderId = -1;
  29506. }
  29507. var clipPlaneState = scene.clipPlane;
  29508. if (localOptions.clipPlane) {
  29509. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  29510. }
  29511. if (_this.storeEffectOnSubMeshes) {
  29512. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  29513. if (onCompiled) {
  29514. onCompiled(_this);
  29515. }
  29516. }
  29517. else {
  29518. setTimeout(checkReady, 16);
  29519. }
  29520. }
  29521. else {
  29522. if (_this.isReady(mesh)) {
  29523. if (onCompiled) {
  29524. onCompiled(_this);
  29525. }
  29526. }
  29527. else {
  29528. setTimeout(checkReady, 16);
  29529. }
  29530. }
  29531. if (options && options.clipPlane) {
  29532. scene.clipPlane = clipPlaneState;
  29533. }
  29534. };
  29535. checkReady();
  29536. };
  29537. Material.prototype.markAsDirty = function (flag) {
  29538. if (flag & Material.TextureDirtyFlag) {
  29539. this._markAllSubMeshesAsTexturesDirty();
  29540. }
  29541. if (flag & Material.LightDirtyFlag) {
  29542. this._markAllSubMeshesAsLightsDirty();
  29543. }
  29544. if (flag & Material.FresnelDirtyFlag) {
  29545. this._markAllSubMeshesAsFresnelDirty();
  29546. }
  29547. if (flag & Material.AttributesDirtyFlag) {
  29548. this._markAllSubMeshesAsAttributesDirty();
  29549. }
  29550. if (flag & Material.MiscDirtyFlag) {
  29551. this._markAllSubMeshesAsMiscDirty();
  29552. }
  29553. this.getScene().resetCachedMaterial();
  29554. };
  29555. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  29556. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  29557. var mesh = _a[_i];
  29558. if (!mesh.subMeshes) {
  29559. continue;
  29560. }
  29561. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  29562. var subMesh = _c[_b];
  29563. if (subMesh.getMaterial() !== this) {
  29564. continue;
  29565. }
  29566. if (!subMesh._materialDefines) {
  29567. continue;
  29568. }
  29569. func(subMesh._materialDefines);
  29570. }
  29571. }
  29572. };
  29573. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  29574. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  29575. };
  29576. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  29577. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  29578. };
  29579. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  29580. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  29581. };
  29582. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  29583. this._markAllSubMeshesAsDirty(function (defines) {
  29584. defines.markAsFresnelDirty();
  29585. defines.markAsMiscDirty();
  29586. });
  29587. };
  29588. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  29589. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  29590. };
  29591. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  29592. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  29593. };
  29594. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  29595. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  29596. };
  29597. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  29598. this._markAllSubMeshesAsDirty(function (defines) {
  29599. defines.markAsTexturesDirty();
  29600. defines.markAsMiscDirty();
  29601. });
  29602. };
  29603. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29604. // Animations
  29605. this.getScene().stopAnimation(this);
  29606. // Remove from scene
  29607. var index = this._scene.materials.indexOf(this);
  29608. if (index >= 0) {
  29609. this._scene.materials.splice(index, 1);
  29610. }
  29611. // Remove from meshes
  29612. for (index = 0; index < this._scene.meshes.length; index++) {
  29613. var mesh = this._scene.meshes[index];
  29614. if (mesh.material === this) {
  29615. mesh.material = null;
  29616. if (mesh.geometry) {
  29617. var geometry = (mesh.geometry);
  29618. if (this.storeEffectOnSubMeshes) {
  29619. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  29620. var subMesh = _a[_i];
  29621. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  29622. if (forceDisposeEffect && subMesh._materialEffect) {
  29623. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  29624. }
  29625. }
  29626. }
  29627. else {
  29628. geometry._releaseVertexArrayObject(this._effect);
  29629. }
  29630. }
  29631. }
  29632. }
  29633. this._uniformBuffer.dispose();
  29634. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29635. if (forceDisposeEffect && this._effect) {
  29636. if (!this.storeEffectOnSubMeshes) {
  29637. this._scene.getEngine()._releaseEffect(this._effect);
  29638. }
  29639. this._effect = null;
  29640. }
  29641. // Callback
  29642. this.onDisposeObservable.notifyObservers(this);
  29643. this.onDisposeObservable.clear();
  29644. this.onBindObservable.clear();
  29645. this.onUnBindObservable.clear();
  29646. };
  29647. Material.prototype.serialize = function () {
  29648. return BABYLON.SerializationHelper.Serialize(this);
  29649. };
  29650. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29651. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29652. multiMaterial.id = parsedMultiMaterial.id;
  29653. if (BABYLON.Tags) {
  29654. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29655. }
  29656. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29657. var subMatId = parsedMultiMaterial.materials[matIndex];
  29658. if (subMatId) {
  29659. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29660. }
  29661. else {
  29662. multiMaterial.subMaterials.push(null);
  29663. }
  29664. }
  29665. return multiMaterial;
  29666. };
  29667. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29668. if (!parsedMaterial.customType) {
  29669. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29670. }
  29671. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  29672. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  29673. if (!BABYLON.LegacyPBRMaterial) {
  29674. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  29675. return;
  29676. }
  29677. }
  29678. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29679. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29680. ;
  29681. };
  29682. // Triangle views
  29683. Material._TriangleFillMode = 0;
  29684. Material._WireFrameFillMode = 1;
  29685. Material._PointFillMode = 2;
  29686. // Draw modes
  29687. Material._PointListDrawMode = 3;
  29688. Material._LineListDrawMode = 4;
  29689. Material._LineLoopDrawMode = 5;
  29690. Material._LineStripDrawMode = 6;
  29691. Material._TriangleStripDrawMode = 7;
  29692. Material._TriangleFanDrawMode = 8;
  29693. Material._ClockWiseSideOrientation = 0;
  29694. Material._CounterClockWiseSideOrientation = 1;
  29695. Material._TextureDirtyFlag = 1;
  29696. Material._LightDirtyFlag = 2;
  29697. Material._FresnelDirtyFlag = 4;
  29698. Material._AttributesDirtyFlag = 8;
  29699. Material._MiscDirtyFlag = 16;
  29700. __decorate([
  29701. BABYLON.serialize()
  29702. ], Material.prototype, "id", void 0);
  29703. __decorate([
  29704. BABYLON.serialize()
  29705. ], Material.prototype, "name", void 0);
  29706. __decorate([
  29707. BABYLON.serialize()
  29708. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29709. __decorate([
  29710. BABYLON.serialize()
  29711. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29712. __decorate([
  29713. BABYLON.serialize()
  29714. ], Material.prototype, "state", void 0);
  29715. __decorate([
  29716. BABYLON.serialize("alpha")
  29717. ], Material.prototype, "_alpha", void 0);
  29718. __decorate([
  29719. BABYLON.serialize("backFaceCulling")
  29720. ], Material.prototype, "_backFaceCulling", void 0);
  29721. __decorate([
  29722. BABYLON.serialize()
  29723. ], Material.prototype, "sideOrientation", void 0);
  29724. __decorate([
  29725. BABYLON.serialize("alphaMode")
  29726. ], Material.prototype, "_alphaMode", void 0);
  29727. __decorate([
  29728. BABYLON.serialize()
  29729. ], Material.prototype, "_needDepthPrePass", void 0);
  29730. __decorate([
  29731. BABYLON.serialize()
  29732. ], Material.prototype, "disableDepthWrite", void 0);
  29733. __decorate([
  29734. BABYLON.serialize()
  29735. ], Material.prototype, "forceDepthWrite", void 0);
  29736. __decorate([
  29737. BABYLON.serialize()
  29738. ], Material.prototype, "separateCullingPass", void 0);
  29739. __decorate([
  29740. BABYLON.serialize("fogEnabled")
  29741. ], Material.prototype, "_fogEnabled", void 0);
  29742. __decorate([
  29743. BABYLON.serialize()
  29744. ], Material.prototype, "pointSize", void 0);
  29745. __decorate([
  29746. BABYLON.serialize()
  29747. ], Material.prototype, "zOffset", void 0);
  29748. __decorate([
  29749. BABYLON.serialize()
  29750. ], Material.prototype, "wireframe", null);
  29751. __decorate([
  29752. BABYLON.serialize()
  29753. ], Material.prototype, "pointsCloud", null);
  29754. __decorate([
  29755. BABYLON.serialize()
  29756. ], Material.prototype, "fillMode", null);
  29757. return Material;
  29758. }());
  29759. BABYLON.Material = Material;
  29760. })(BABYLON || (BABYLON = {}));
  29761. //# sourceMappingURL=babylon.material.js.map
  29762. var BABYLON;
  29763. (function (BABYLON) {
  29764. var UniformBuffer = /** @class */ (function () {
  29765. /**
  29766. * Uniform buffer objects.
  29767. *
  29768. * Handles blocks of uniform on the GPU.
  29769. *
  29770. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  29771. *
  29772. * For more information, please refer to :
  29773. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  29774. */
  29775. function UniformBuffer(engine, data, dynamic) {
  29776. this._engine = engine;
  29777. this._noUBO = !engine.supportsUniformBuffers;
  29778. this._dynamic = dynamic;
  29779. this._data = data || [];
  29780. this._uniformLocations = {};
  29781. this._uniformSizes = {};
  29782. this._uniformLocationPointer = 0;
  29783. this._needSync = false;
  29784. if (this._noUBO) {
  29785. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  29786. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  29787. this.updateFloat = this._updateFloatForEffect;
  29788. this.updateFloat2 = this._updateFloat2ForEffect;
  29789. this.updateFloat3 = this._updateFloat3ForEffect;
  29790. this.updateFloat4 = this._updateFloat4ForEffect;
  29791. this.updateMatrix = this._updateMatrixForEffect;
  29792. this.updateVector3 = this._updateVector3ForEffect;
  29793. this.updateVector4 = this._updateVector4ForEffect;
  29794. this.updateColor3 = this._updateColor3ForEffect;
  29795. this.updateColor4 = this._updateColor4ForEffect;
  29796. }
  29797. else {
  29798. this._engine._uniformBuffers.push(this);
  29799. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  29800. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  29801. this.updateFloat = this._updateFloatForUniform;
  29802. this.updateFloat2 = this._updateFloat2ForUniform;
  29803. this.updateFloat3 = this._updateFloat3ForUniform;
  29804. this.updateFloat4 = this._updateFloat4ForUniform;
  29805. this.updateMatrix = this._updateMatrixForUniform;
  29806. this.updateVector3 = this._updateVector3ForUniform;
  29807. this.updateVector4 = this._updateVector4ForUniform;
  29808. this.updateColor3 = this._updateColor3ForUniform;
  29809. this.updateColor4 = this._updateColor4ForUniform;
  29810. }
  29811. }
  29812. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  29813. // Properties
  29814. /**
  29815. * Indicates if the buffer is using the WebGL2 UBO implementation,
  29816. * or just falling back on setUniformXXX calls.
  29817. */
  29818. get: function () {
  29819. return !this._noUBO;
  29820. },
  29821. enumerable: true,
  29822. configurable: true
  29823. });
  29824. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  29825. /**
  29826. * Indicates if the WebGL underlying uniform buffer is in sync
  29827. * with the javascript cache data.
  29828. */
  29829. get: function () {
  29830. return !this._needSync;
  29831. },
  29832. enumerable: true,
  29833. configurable: true
  29834. });
  29835. /**
  29836. * Indicates if the WebGL underlying uniform buffer is dynamic.
  29837. * Also, a dynamic UniformBuffer will disable cache verification and always
  29838. * update the underlying WebGL uniform buffer to the GPU.
  29839. */
  29840. UniformBuffer.prototype.isDynamic = function () {
  29841. return this._dynamic !== undefined;
  29842. };
  29843. /**
  29844. * The data cache on JS side.
  29845. */
  29846. UniformBuffer.prototype.getData = function () {
  29847. return this._bufferData;
  29848. };
  29849. /**
  29850. * The underlying WebGL Uniform buffer.
  29851. */
  29852. UniformBuffer.prototype.getBuffer = function () {
  29853. return this._buffer;
  29854. };
  29855. /**
  29856. * std140 layout specifies how to align data within an UBO structure.
  29857. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  29858. * for specs.
  29859. */
  29860. UniformBuffer.prototype._fillAlignment = function (size) {
  29861. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  29862. // and 4x4 matrices
  29863. // TODO : change if other types are used
  29864. var alignment;
  29865. if (size <= 2) {
  29866. alignment = size;
  29867. }
  29868. else {
  29869. alignment = 4;
  29870. }
  29871. if ((this._uniformLocationPointer % alignment) !== 0) {
  29872. var oldPointer = this._uniformLocationPointer;
  29873. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  29874. var diff = this._uniformLocationPointer - oldPointer;
  29875. for (var i = 0; i < diff; i++) {
  29876. this._data.push(0);
  29877. }
  29878. }
  29879. };
  29880. /**
  29881. * Adds an uniform in the buffer.
  29882. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  29883. * for the layout to be correct !
  29884. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29885. * @param {number|number[]} size Data size, or data directly.
  29886. */
  29887. UniformBuffer.prototype.addUniform = function (name, size) {
  29888. if (this._noUBO) {
  29889. return;
  29890. }
  29891. if (this._uniformLocations[name] !== undefined) {
  29892. // Already existing uniform
  29893. return;
  29894. }
  29895. // This function must be called in the order of the shader layout !
  29896. // size can be the size of the uniform, or data directly
  29897. var data;
  29898. if (size instanceof Array) {
  29899. data = size;
  29900. size = data.length;
  29901. }
  29902. else {
  29903. size = size;
  29904. data = [];
  29905. // Fill with zeros
  29906. for (var i = 0; i < size; i++) {
  29907. data.push(0);
  29908. }
  29909. }
  29910. this._fillAlignment(size);
  29911. this._uniformSizes[name] = size;
  29912. this._uniformLocations[name] = this._uniformLocationPointer;
  29913. this._uniformLocationPointer += size;
  29914. for (var i = 0; i < size; i++) {
  29915. this._data.push(data[i]);
  29916. }
  29917. this._needSync = true;
  29918. };
  29919. /**
  29920. * Wrapper for addUniform.
  29921. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29922. * @param {Matrix} mat A 4x4 matrix.
  29923. */
  29924. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29925. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29926. };
  29927. /**
  29928. * Wrapper for addUniform.
  29929. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29930. * @param {number} x
  29931. * @param {number} y
  29932. */
  29933. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29934. var temp = [x, y];
  29935. this.addUniform(name, temp);
  29936. };
  29937. /**
  29938. * Wrapper for addUniform.
  29939. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29940. * @param {number} x
  29941. * @param {number} y
  29942. * @param {number} z
  29943. */
  29944. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29945. var temp = [x, y, z];
  29946. this.addUniform(name, temp);
  29947. };
  29948. /**
  29949. * Wrapper for addUniform.
  29950. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29951. * @param {Color3} color
  29952. */
  29953. UniformBuffer.prototype.addColor3 = function (name, color) {
  29954. var temp = new Array();
  29955. color.toArray(temp);
  29956. this.addUniform(name, temp);
  29957. };
  29958. /**
  29959. * Wrapper for addUniform.
  29960. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29961. * @param {Color3} color
  29962. * @param {number} alpha
  29963. */
  29964. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29965. var temp = new Array();
  29966. color.toArray(temp);
  29967. temp.push(alpha);
  29968. this.addUniform(name, temp);
  29969. };
  29970. /**
  29971. * Wrapper for addUniform.
  29972. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29973. * @param {Vector3} vector
  29974. */
  29975. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29976. var temp = new Array();
  29977. vector.toArray(temp);
  29978. this.addUniform(name, temp);
  29979. };
  29980. /**
  29981. * Wrapper for addUniform.
  29982. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29983. */
  29984. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29985. this.addUniform(name, 12);
  29986. };
  29987. /**
  29988. * Wrapper for addUniform.
  29989. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29990. */
  29991. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  29992. this.addUniform(name, 8);
  29993. };
  29994. /**
  29995. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  29996. */
  29997. UniformBuffer.prototype.create = function () {
  29998. if (this._noUBO) {
  29999. return;
  30000. }
  30001. if (this._buffer) {
  30002. return; // nothing to do
  30003. }
  30004. // See spec, alignment must be filled as a vec4
  30005. this._fillAlignment(4);
  30006. this._bufferData = new Float32Array(this._data);
  30007. this._rebuild();
  30008. this._needSync = true;
  30009. };
  30010. UniformBuffer.prototype._rebuild = function () {
  30011. if (this._noUBO) {
  30012. return;
  30013. }
  30014. if (this._dynamic) {
  30015. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  30016. }
  30017. else {
  30018. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  30019. }
  30020. };
  30021. /**
  30022. * Updates the WebGL Uniform Buffer on the GPU.
  30023. * If the `dynamic` flag is set to true, no cache comparison is done.
  30024. * Otherwise, the buffer will be updated only if the cache differs.
  30025. */
  30026. UniformBuffer.prototype.update = function () {
  30027. if (!this._buffer) {
  30028. this.create();
  30029. return;
  30030. }
  30031. if (!this._dynamic && !this._needSync) {
  30032. return;
  30033. }
  30034. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  30035. this._needSync = false;
  30036. };
  30037. /**
  30038. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  30039. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30040. * @param {number[]|Float32Array} data Flattened data
  30041. * @param {number} size Size of the data.
  30042. */
  30043. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  30044. var location = this._uniformLocations[uniformName];
  30045. if (location === undefined) {
  30046. if (this._buffer) {
  30047. // Cannot add an uniform if the buffer is already created
  30048. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  30049. return;
  30050. }
  30051. this.addUniform(uniformName, size);
  30052. location = this._uniformLocations[uniformName];
  30053. }
  30054. if (!this._buffer) {
  30055. this.create();
  30056. }
  30057. if (!this._dynamic) {
  30058. // Cache for static uniform buffers
  30059. var changed = false;
  30060. for (var i = 0; i < size; i++) {
  30061. if (this._bufferData[location + i] !== data[i]) {
  30062. changed = true;
  30063. this._bufferData[location + i] = data[i];
  30064. }
  30065. }
  30066. this._needSync = this._needSync || changed;
  30067. }
  30068. else {
  30069. // No cache for dynamic
  30070. for (var i = 0; i < size; i++) {
  30071. this._bufferData[location + i] = data[i];
  30072. }
  30073. }
  30074. };
  30075. // Update methods
  30076. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  30077. // To match std140, matrix must be realigned
  30078. for (var i = 0; i < 3; i++) {
  30079. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  30080. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  30081. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  30082. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30083. }
  30084. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  30085. };
  30086. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  30087. this._currentEffect.setMatrix3x3(name, matrix);
  30088. };
  30089. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  30090. this._currentEffect.setMatrix2x2(name, matrix);
  30091. };
  30092. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  30093. // To match std140, matrix must be realigned
  30094. for (var i = 0; i < 2; i++) {
  30095. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  30096. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  30097. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  30098. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  30099. }
  30100. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  30101. };
  30102. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  30103. this._currentEffect.setFloat(name, x);
  30104. };
  30105. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  30106. UniformBuffer._tempBuffer[0] = x;
  30107. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  30108. };
  30109. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  30110. if (suffix === void 0) { suffix = ""; }
  30111. this._currentEffect.setFloat2(name + suffix, x, y);
  30112. };
  30113. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  30114. if (suffix === void 0) { suffix = ""; }
  30115. UniformBuffer._tempBuffer[0] = x;
  30116. UniformBuffer._tempBuffer[1] = y;
  30117. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  30118. };
  30119. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  30120. if (suffix === void 0) { suffix = ""; }
  30121. this._currentEffect.setFloat3(name + suffix, x, y, z);
  30122. };
  30123. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  30124. if (suffix === void 0) { suffix = ""; }
  30125. UniformBuffer._tempBuffer[0] = x;
  30126. UniformBuffer._tempBuffer[1] = y;
  30127. UniformBuffer._tempBuffer[2] = z;
  30128. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30129. };
  30130. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  30131. if (suffix === void 0) { suffix = ""; }
  30132. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  30133. };
  30134. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  30135. if (suffix === void 0) { suffix = ""; }
  30136. UniformBuffer._tempBuffer[0] = x;
  30137. UniformBuffer._tempBuffer[1] = y;
  30138. UniformBuffer._tempBuffer[2] = z;
  30139. UniformBuffer._tempBuffer[3] = w;
  30140. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30141. };
  30142. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  30143. this._currentEffect.setMatrix(name, mat);
  30144. };
  30145. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  30146. this.updateUniform(name, mat.toArray(), 16);
  30147. };
  30148. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  30149. this._currentEffect.setVector3(name, vector);
  30150. };
  30151. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  30152. vector.toArray(UniformBuffer._tempBuffer);
  30153. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30154. };
  30155. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  30156. this._currentEffect.setVector4(name, vector);
  30157. };
  30158. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  30159. vector.toArray(UniformBuffer._tempBuffer);
  30160. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30161. };
  30162. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  30163. if (suffix === void 0) { suffix = ""; }
  30164. this._currentEffect.setColor3(name + suffix, color);
  30165. };
  30166. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  30167. if (suffix === void 0) { suffix = ""; }
  30168. color.toArray(UniformBuffer._tempBuffer);
  30169. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  30170. };
  30171. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  30172. if (suffix === void 0) { suffix = ""; }
  30173. this._currentEffect.setColor4(name + suffix, color, alpha);
  30174. };
  30175. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  30176. if (suffix === void 0) { suffix = ""; }
  30177. color.toArray(UniformBuffer._tempBuffer);
  30178. UniformBuffer._tempBuffer[3] = alpha;
  30179. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  30180. };
  30181. /**
  30182. * Sets a sampler uniform on the effect.
  30183. * @param {string} name Name of the sampler.
  30184. * @param {Texture} texture
  30185. */
  30186. UniformBuffer.prototype.setTexture = function (name, texture) {
  30187. this._currentEffect.setTexture(name, texture);
  30188. };
  30189. /**
  30190. * Directly updates the value of the uniform in the cache AND on the GPU.
  30191. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  30192. * @param {number[]|Float32Array} data Flattened data
  30193. */
  30194. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  30195. this.updateUniform(uniformName, data, data.length);
  30196. this.update();
  30197. };
  30198. /**
  30199. * Binds this uniform buffer to an effect.
  30200. * @param {Effect} effect
  30201. * @param {string} name Name of the uniform block in the shader.
  30202. */
  30203. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  30204. this._currentEffect = effect;
  30205. if (this._noUBO || !this._buffer) {
  30206. return;
  30207. }
  30208. effect.bindUniformBuffer(this._buffer, name);
  30209. };
  30210. /**
  30211. * Disposes the uniform buffer.
  30212. */
  30213. UniformBuffer.prototype.dispose = function () {
  30214. if (this._noUBO) {
  30215. return;
  30216. }
  30217. var index = this._engine._uniformBuffers.indexOf(this);
  30218. if (index !== -1) {
  30219. this._engine._uniformBuffers.splice(index, 1);
  30220. }
  30221. if (!this._buffer) {
  30222. return;
  30223. }
  30224. if (this._engine._releaseBuffer(this._buffer)) {
  30225. this._buffer = null;
  30226. }
  30227. };
  30228. // Pool for avoiding memory leaks
  30229. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  30230. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  30231. return UniformBuffer;
  30232. }());
  30233. BABYLON.UniformBuffer = UniformBuffer;
  30234. })(BABYLON || (BABYLON = {}));
  30235. //# sourceMappingURL=babylon.uniformBuffer.js.map
  30236. var BABYLON;
  30237. (function (BABYLON) {
  30238. var VertexData = /** @class */ (function () {
  30239. function VertexData() {
  30240. }
  30241. VertexData.prototype.set = function (data, kind) {
  30242. switch (kind) {
  30243. case BABYLON.VertexBuffer.PositionKind:
  30244. this.positions = data;
  30245. break;
  30246. case BABYLON.VertexBuffer.NormalKind:
  30247. this.normals = data;
  30248. break;
  30249. case BABYLON.VertexBuffer.TangentKind:
  30250. this.tangents = data;
  30251. break;
  30252. case BABYLON.VertexBuffer.UVKind:
  30253. this.uvs = data;
  30254. break;
  30255. case BABYLON.VertexBuffer.UV2Kind:
  30256. this.uvs2 = data;
  30257. break;
  30258. case BABYLON.VertexBuffer.UV3Kind:
  30259. this.uvs3 = data;
  30260. break;
  30261. case BABYLON.VertexBuffer.UV4Kind:
  30262. this.uvs4 = data;
  30263. break;
  30264. case BABYLON.VertexBuffer.UV5Kind:
  30265. this.uvs5 = data;
  30266. break;
  30267. case BABYLON.VertexBuffer.UV6Kind:
  30268. this.uvs6 = data;
  30269. break;
  30270. case BABYLON.VertexBuffer.ColorKind:
  30271. this.colors = data;
  30272. break;
  30273. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30274. this.matricesIndices = data;
  30275. break;
  30276. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30277. this.matricesWeights = data;
  30278. break;
  30279. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30280. this.matricesIndicesExtra = data;
  30281. break;
  30282. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30283. this.matricesWeightsExtra = data;
  30284. break;
  30285. }
  30286. };
  30287. /**
  30288. * Associates the vertexData to the passed Mesh.
  30289. * Sets it as updatable or not (default `false`).
  30290. * Returns the VertexData.
  30291. */
  30292. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30293. this._applyTo(mesh, updatable);
  30294. return this;
  30295. };
  30296. /**
  30297. * Associates the vertexData to the passed Geometry.
  30298. * Sets it as updatable or not (default `false`).
  30299. * Returns the VertexData.
  30300. */
  30301. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30302. this._applyTo(geometry, updatable);
  30303. return this;
  30304. };
  30305. /**
  30306. * Updates the associated mesh.
  30307. * Returns the VertexData.
  30308. */
  30309. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30310. this._update(mesh);
  30311. return this;
  30312. };
  30313. /**
  30314. * Updates the associated geometry.
  30315. * Returns the VertexData.
  30316. */
  30317. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30318. this._update(geometry);
  30319. return this;
  30320. };
  30321. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30322. if (updatable === void 0) { updatable = false; }
  30323. if (this.positions) {
  30324. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30325. }
  30326. if (this.normals) {
  30327. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30328. }
  30329. if (this.tangents) {
  30330. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  30331. }
  30332. if (this.uvs) {
  30333. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30334. }
  30335. if (this.uvs2) {
  30336. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30337. }
  30338. if (this.uvs3) {
  30339. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30340. }
  30341. if (this.uvs4) {
  30342. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30343. }
  30344. if (this.uvs5) {
  30345. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30346. }
  30347. if (this.uvs6) {
  30348. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30349. }
  30350. if (this.colors) {
  30351. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30352. }
  30353. if (this.matricesIndices) {
  30354. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30355. }
  30356. if (this.matricesWeights) {
  30357. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30358. }
  30359. if (this.matricesIndicesExtra) {
  30360. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30361. }
  30362. if (this.matricesWeightsExtra) {
  30363. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30364. }
  30365. if (this.indices) {
  30366. meshOrGeometry.setIndices(this.indices, null, updatable);
  30367. }
  30368. return this;
  30369. };
  30370. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30371. if (this.positions) {
  30372. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30373. }
  30374. if (this.normals) {
  30375. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30376. }
  30377. if (this.tangents) {
  30378. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  30379. }
  30380. if (this.uvs) {
  30381. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30382. }
  30383. if (this.uvs2) {
  30384. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30385. }
  30386. if (this.uvs3) {
  30387. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30388. }
  30389. if (this.uvs4) {
  30390. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30391. }
  30392. if (this.uvs5) {
  30393. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30394. }
  30395. if (this.uvs6) {
  30396. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30397. }
  30398. if (this.colors) {
  30399. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30400. }
  30401. if (this.matricesIndices) {
  30402. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30403. }
  30404. if (this.matricesWeights) {
  30405. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30406. }
  30407. if (this.matricesIndicesExtra) {
  30408. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30409. }
  30410. if (this.matricesWeightsExtra) {
  30411. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30412. }
  30413. if (this.indices) {
  30414. meshOrGeometry.setIndices(this.indices, null);
  30415. }
  30416. return this;
  30417. };
  30418. /**
  30419. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  30420. * Returns the VertexData.
  30421. */
  30422. VertexData.prototype.transform = function (matrix) {
  30423. var transformed = BABYLON.Vector3.Zero();
  30424. var index;
  30425. if (this.positions) {
  30426. var position = BABYLON.Vector3.Zero();
  30427. for (index = 0; index < this.positions.length; index += 3) {
  30428. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30429. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30430. this.positions[index] = transformed.x;
  30431. this.positions[index + 1] = transformed.y;
  30432. this.positions[index + 2] = transformed.z;
  30433. }
  30434. }
  30435. if (this.normals) {
  30436. var normal = BABYLON.Vector3.Zero();
  30437. for (index = 0; index < this.normals.length; index += 3) {
  30438. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30439. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30440. this.normals[index] = transformed.x;
  30441. this.normals[index + 1] = transformed.y;
  30442. this.normals[index + 2] = transformed.z;
  30443. }
  30444. }
  30445. if (this.tangents) {
  30446. var tangent = BABYLON.Vector4.Zero();
  30447. var tangentTransformed = BABYLON.Vector4.Zero();
  30448. for (index = 0; index < this.tangents.length; index += 4) {
  30449. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  30450. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  30451. this.tangents[index] = tangentTransformed.x;
  30452. this.tangents[index + 1] = tangentTransformed.y;
  30453. this.tangents[index + 2] = tangentTransformed.z;
  30454. this.tangents[index + 3] = tangentTransformed.w;
  30455. }
  30456. }
  30457. return this;
  30458. };
  30459. /**
  30460. * Merges the passed VertexData into the current one.
  30461. * Returns the modified VertexData.
  30462. */
  30463. VertexData.prototype.merge = function (other, options) {
  30464. options = options || {};
  30465. if (other.indices) {
  30466. if (!this.indices) {
  30467. this.indices = [];
  30468. }
  30469. var offset = this.positions ? this.positions.length / 3 : 0;
  30470. for (var index = 0; index < other.indices.length; index++) {
  30471. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  30472. this.indices.push(other.indices[index] + offset);
  30473. }
  30474. }
  30475. this.positions = this._mergeElement(this.positions, other.positions);
  30476. if (!this.positions) {
  30477. return this;
  30478. }
  30479. var count = this.positions.length / 3;
  30480. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  30481. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  30482. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  30483. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  30484. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  30485. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  30486. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  30487. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  30488. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  30489. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  30490. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  30491. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  30492. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  30493. return this;
  30494. };
  30495. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  30496. if (length === void 0) { length = 0; }
  30497. if (defaultValue === void 0) { defaultValue = 0; }
  30498. if (!other && !source) {
  30499. return null;
  30500. }
  30501. if (!other) {
  30502. var padding = new Float32Array(source.length);
  30503. padding.fill(defaultValue);
  30504. return this._mergeElement(source, padding, length);
  30505. }
  30506. if (!source) {
  30507. if (length === 0 || length === other.length) {
  30508. return other;
  30509. }
  30510. var padding = new Float32Array(length - other.length);
  30511. padding.fill(defaultValue);
  30512. return this._mergeElement(padding, other, length);
  30513. }
  30514. var len = other.length + source.length;
  30515. var isSrcTypedArray = source instanceof Float32Array;
  30516. var isOthTypedArray = other instanceof Float32Array;
  30517. // use non-loop method when the source is Float32Array
  30518. if (isSrcTypedArray) {
  30519. var ret32 = new Float32Array(len);
  30520. ret32.set(source);
  30521. ret32.set(other, source.length);
  30522. return ret32;
  30523. // source is number[], when other is also use concat
  30524. }
  30525. else if (!isOthTypedArray) {
  30526. return source.concat(other);
  30527. // source is a number[], but other is a Float32Array, loop required
  30528. }
  30529. else {
  30530. var ret = source.slice(0); // copy source to a separate array
  30531. for (var i = 0, len = other.length; i < len; i++) {
  30532. ret.push(other[i]);
  30533. }
  30534. return ret;
  30535. }
  30536. };
  30537. /**
  30538. * Serializes the VertexData.
  30539. * Returns a serialized object.
  30540. */
  30541. VertexData.prototype.serialize = function () {
  30542. var serializationObject = this.serialize();
  30543. if (this.positions) {
  30544. serializationObject.positions = this.positions;
  30545. }
  30546. if (this.normals) {
  30547. serializationObject.normals = this.normals;
  30548. }
  30549. if (this.tangents) {
  30550. serializationObject.tangents = this.tangents;
  30551. }
  30552. if (this.uvs) {
  30553. serializationObject.uvs = this.uvs;
  30554. }
  30555. if (this.uvs2) {
  30556. serializationObject.uvs2 = this.uvs2;
  30557. }
  30558. if (this.uvs3) {
  30559. serializationObject.uvs3 = this.uvs3;
  30560. }
  30561. if (this.uvs4) {
  30562. serializationObject.uvs4 = this.uvs4;
  30563. }
  30564. if (this.uvs5) {
  30565. serializationObject.uvs5 = this.uvs5;
  30566. }
  30567. if (this.uvs6) {
  30568. serializationObject.uvs6 = this.uvs6;
  30569. }
  30570. if (this.colors) {
  30571. serializationObject.colors = this.colors;
  30572. }
  30573. if (this.matricesIndices) {
  30574. serializationObject.matricesIndices = this.matricesIndices;
  30575. serializationObject.matricesIndices._isExpanded = true;
  30576. }
  30577. if (this.matricesWeights) {
  30578. serializationObject.matricesWeights = this.matricesWeights;
  30579. }
  30580. if (this.matricesIndicesExtra) {
  30581. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30582. serializationObject.matricesIndicesExtra._isExpanded = true;
  30583. }
  30584. if (this.matricesWeightsExtra) {
  30585. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30586. }
  30587. serializationObject.indices = this.indices;
  30588. return serializationObject;
  30589. };
  30590. // Statics
  30591. /**
  30592. * Returns the object VertexData associated to the passed mesh.
  30593. */
  30594. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  30595. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  30596. };
  30597. /**
  30598. * Returns the object VertexData associated to the passed geometry.
  30599. */
  30600. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  30601. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  30602. };
  30603. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  30604. var result = new VertexData();
  30605. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30606. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  30607. }
  30608. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30609. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  30610. }
  30611. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30612. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  30613. }
  30614. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30615. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  30616. }
  30617. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30618. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  30619. }
  30620. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30621. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  30622. }
  30623. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30624. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  30625. }
  30626. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30627. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  30628. }
  30629. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30630. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  30631. }
  30632. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30633. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  30634. }
  30635. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30636. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  30637. }
  30638. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30639. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  30640. }
  30641. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30642. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  30643. }
  30644. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30645. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  30646. }
  30647. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30648. return result;
  30649. };
  30650. /**
  30651. * Creates the vertexData of the Ribbon.
  30652. */
  30653. VertexData.CreateRibbon = function (options) {
  30654. var pathArray = options.pathArray;
  30655. var closeArray = options.closeArray || false;
  30656. var closePath = options.closePath || false;
  30657. var invertUV = options.invertUV || false;
  30658. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30659. var offset = options.offset || defaultOffset;
  30660. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30661. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30662. var customUV = options.uvs;
  30663. var customColors = options.colors;
  30664. var positions = [];
  30665. var indices = [];
  30666. var normals = [];
  30667. var uvs = [];
  30668. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30669. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30670. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30671. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30672. var minlg; // minimal length among all paths from pathArray
  30673. var lg = []; // array of path lengths : nb of vertex per path
  30674. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30675. var p; // path iterator
  30676. var i; // point iterator
  30677. var j; // point iterator
  30678. // if single path in pathArray
  30679. if (pathArray.length < 2) {
  30680. var ar1 = [];
  30681. var ar2 = [];
  30682. for (i = 0; i < pathArray[0].length - offset; i++) {
  30683. ar1.push(pathArray[0][i]);
  30684. ar2.push(pathArray[0][i + offset]);
  30685. }
  30686. pathArray = [ar1, ar2];
  30687. }
  30688. // positions and horizontal distances (u)
  30689. var idc = 0;
  30690. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  30691. var path;
  30692. var l;
  30693. minlg = pathArray[0].length;
  30694. var vectlg;
  30695. var dist;
  30696. for (p = 0; p < pathArray.length; p++) {
  30697. uTotalDistance[p] = 0;
  30698. us[p] = [0];
  30699. path = pathArray[p];
  30700. l = path.length;
  30701. minlg = (minlg < l) ? minlg : l;
  30702. j = 0;
  30703. while (j < l) {
  30704. positions.push(path[j].x, path[j].y, path[j].z);
  30705. if (j > 0) {
  30706. vectlg = path[j].subtract(path[j - 1]).length();
  30707. dist = vectlg + uTotalDistance[p];
  30708. us[p].push(dist);
  30709. uTotalDistance[p] = dist;
  30710. }
  30711. j++;
  30712. }
  30713. if (closePath) {
  30714. j--;
  30715. positions.push(path[0].x, path[0].y, path[0].z);
  30716. vectlg = path[j].subtract(path[0]).length();
  30717. dist = vectlg + uTotalDistance[p];
  30718. us[p].push(dist);
  30719. uTotalDistance[p] = dist;
  30720. }
  30721. lg[p] = l + closePathCorr;
  30722. idx[p] = idc;
  30723. idc += (l + closePathCorr);
  30724. }
  30725. // vertical distances (v)
  30726. var path1;
  30727. var path2;
  30728. var vertex1 = null;
  30729. var vertex2 = null;
  30730. for (i = 0; i < minlg + closePathCorr; i++) {
  30731. vTotalDistance[i] = 0;
  30732. vs[i] = [0];
  30733. for (p = 0; p < pathArray.length - 1; p++) {
  30734. path1 = pathArray[p];
  30735. path2 = pathArray[p + 1];
  30736. if (i === minlg) {
  30737. vertex1 = path1[0];
  30738. vertex2 = path2[0];
  30739. }
  30740. else {
  30741. vertex1 = path1[i];
  30742. vertex2 = path2[i];
  30743. }
  30744. vectlg = vertex2.subtract(vertex1).length();
  30745. dist = vectlg + vTotalDistance[i];
  30746. vs[i].push(dist);
  30747. vTotalDistance[i] = dist;
  30748. }
  30749. if (closeArray && vertex2 && vertex1) {
  30750. path1 = pathArray[p];
  30751. path2 = pathArray[0];
  30752. if (i === minlg) {
  30753. vertex2 = path2[0];
  30754. }
  30755. vectlg = vertex2.subtract(vertex1).length();
  30756. dist = vectlg + vTotalDistance[i];
  30757. vTotalDistance[i] = dist;
  30758. }
  30759. }
  30760. // uvs
  30761. var u;
  30762. var v;
  30763. if (customUV) {
  30764. for (p = 0; p < customUV.length; p++) {
  30765. uvs.push(customUV[p].x, customUV[p].y);
  30766. }
  30767. }
  30768. else {
  30769. for (p = 0; p < pathArray.length; p++) {
  30770. for (i = 0; i < minlg + closePathCorr; i++) {
  30771. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  30772. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  30773. if (invertUV) {
  30774. uvs.push(v, u);
  30775. }
  30776. else {
  30777. uvs.push(u, v);
  30778. }
  30779. }
  30780. }
  30781. }
  30782. // indices
  30783. p = 0; // path index
  30784. var pi = 0; // positions array index
  30785. var l1 = lg[p] - 1; // path1 length
  30786. var l2 = lg[p + 1] - 1; // path2 length
  30787. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30788. var shft = idx[1] - idx[0]; // shift
  30789. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30790. while (pi <= min && p < path1nb) {
  30791. // 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
  30792. indices.push(pi, pi + shft, pi + 1);
  30793. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30794. pi += 1;
  30795. if (pi === min) {
  30796. p++;
  30797. if (p === lg.length - 1) {
  30798. shft = idx[0] - idx[p];
  30799. l1 = lg[p] - 1;
  30800. l2 = lg[0] - 1;
  30801. }
  30802. else {
  30803. shft = idx[p + 1] - idx[p];
  30804. l1 = lg[p] - 1;
  30805. l2 = lg[p + 1] - 1;
  30806. }
  30807. pi = idx[p];
  30808. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30809. }
  30810. }
  30811. // normals
  30812. VertexData.ComputeNormals(positions, indices, normals);
  30813. if (closePath) {
  30814. var indexFirst = 0;
  30815. var indexLast = 0;
  30816. for (p = 0; p < pathArray.length; p++) {
  30817. indexFirst = idx[p] * 3;
  30818. if (p + 1 < pathArray.length) {
  30819. indexLast = (idx[p + 1] - 1) * 3;
  30820. }
  30821. else {
  30822. indexLast = normals.length - 3;
  30823. }
  30824. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30825. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30826. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30827. normals[indexLast] = normals[indexFirst];
  30828. normals[indexLast + 1] = normals[indexFirst + 1];
  30829. normals[indexLast + 2] = normals[indexFirst + 2];
  30830. }
  30831. }
  30832. // sides
  30833. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30834. // Colors
  30835. var colors = null;
  30836. if (customColors) {
  30837. colors = new Float32Array(customColors.length * 4);
  30838. for (var c = 0; c < customColors.length; c++) {
  30839. colors[c * 4] = customColors[c].r;
  30840. colors[c * 4 + 1] = customColors[c].g;
  30841. colors[c * 4 + 2] = customColors[c].b;
  30842. colors[c * 4 + 3] = customColors[c].a;
  30843. }
  30844. }
  30845. // Result
  30846. var vertexData = new VertexData();
  30847. var positions32 = new Float32Array(positions);
  30848. var normals32 = new Float32Array(normals);
  30849. var uvs32 = new Float32Array(uvs);
  30850. vertexData.indices = indices;
  30851. vertexData.positions = positions32;
  30852. vertexData.normals = normals32;
  30853. vertexData.uvs = uvs32;
  30854. if (colors) {
  30855. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  30856. }
  30857. if (closePath) {
  30858. vertexData._idx = idx;
  30859. }
  30860. return vertexData;
  30861. };
  30862. /**
  30863. * Creates the VertexData of the Box.
  30864. */
  30865. VertexData.CreateBox = function (options) {
  30866. var normalsSource = [
  30867. new BABYLON.Vector3(0, 0, 1),
  30868. new BABYLON.Vector3(0, 0, -1),
  30869. new BABYLON.Vector3(1, 0, 0),
  30870. new BABYLON.Vector3(-1, 0, 0),
  30871. new BABYLON.Vector3(0, 1, 0),
  30872. new BABYLON.Vector3(0, -1, 0)
  30873. ];
  30874. var indices = [];
  30875. var positions = [];
  30876. var normals = [];
  30877. var uvs = [];
  30878. var width = options.width || options.size || 1;
  30879. var height = options.height || options.size || 1;
  30880. var depth = options.depth || options.size || 1;
  30881. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30882. var faceUV = options.faceUV || new Array(6);
  30883. var faceColors = options.faceColors;
  30884. var colors = [];
  30885. // default face colors and UV if undefined
  30886. for (var f = 0; f < 6; f++) {
  30887. if (faceUV[f] === undefined) {
  30888. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30889. }
  30890. if (faceColors && faceColors[f] === undefined) {
  30891. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30892. }
  30893. }
  30894. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30895. // Create each face in turn.
  30896. for (var index = 0; index < normalsSource.length; index++) {
  30897. var normal = normalsSource[index];
  30898. // Get two vectors perpendicular to the face normal and to each other.
  30899. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30900. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30901. // Six indices (two triangles) per face.
  30902. var verticesLength = positions.length / 3;
  30903. indices.push(verticesLength);
  30904. indices.push(verticesLength + 1);
  30905. indices.push(verticesLength + 2);
  30906. indices.push(verticesLength);
  30907. indices.push(verticesLength + 2);
  30908. indices.push(verticesLength + 3);
  30909. // Four vertices per face.
  30910. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30911. positions.push(vertex.x, vertex.y, vertex.z);
  30912. normals.push(normal.x, normal.y, normal.z);
  30913. uvs.push(faceUV[index].z, faceUV[index].w);
  30914. if (faceColors) {
  30915. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30916. }
  30917. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30918. positions.push(vertex.x, vertex.y, vertex.z);
  30919. normals.push(normal.x, normal.y, normal.z);
  30920. uvs.push(faceUV[index].x, faceUV[index].w);
  30921. if (faceColors) {
  30922. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30923. }
  30924. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30925. positions.push(vertex.x, vertex.y, vertex.z);
  30926. normals.push(normal.x, normal.y, normal.z);
  30927. uvs.push(faceUV[index].x, faceUV[index].y);
  30928. if (faceColors) {
  30929. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30930. }
  30931. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30932. positions.push(vertex.x, vertex.y, vertex.z);
  30933. normals.push(normal.x, normal.y, normal.z);
  30934. uvs.push(faceUV[index].z, faceUV[index].y);
  30935. if (faceColors) {
  30936. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30937. }
  30938. }
  30939. // sides
  30940. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30941. // Result
  30942. var vertexData = new VertexData();
  30943. vertexData.indices = indices;
  30944. vertexData.positions = positions;
  30945. vertexData.normals = normals;
  30946. vertexData.uvs = uvs;
  30947. if (faceColors) {
  30948. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30949. vertexData.colors = totalColors;
  30950. }
  30951. return vertexData;
  30952. };
  30953. /**
  30954. * Creates the VertexData of the Sphere.
  30955. */
  30956. VertexData.CreateSphere = function (options) {
  30957. var segments = options.segments || 32;
  30958. var diameterX = options.diameterX || options.diameter || 1;
  30959. var diameterY = options.diameterY || options.diameter || 1;
  30960. var diameterZ = options.diameterZ || options.diameter || 1;
  30961. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30962. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30963. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30964. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30965. var totalZRotationSteps = 2 + segments;
  30966. var totalYRotationSteps = 2 * totalZRotationSteps;
  30967. var indices = [];
  30968. var positions = [];
  30969. var normals = [];
  30970. var uvs = [];
  30971. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30972. var normalizedZ = zRotationStep / totalZRotationSteps;
  30973. var angleZ = normalizedZ * Math.PI * slice;
  30974. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30975. var normalizedY = yRotationStep / totalYRotationSteps;
  30976. var angleY = normalizedY * Math.PI * 2 * arc;
  30977. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30978. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30979. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30980. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30981. var vertex = complete.multiply(radius);
  30982. var normal = complete.divide(radius).normalize();
  30983. positions.push(vertex.x, vertex.y, vertex.z);
  30984. normals.push(normal.x, normal.y, normal.z);
  30985. uvs.push(normalizedY, normalizedZ);
  30986. }
  30987. if (zRotationStep > 0) {
  30988. var verticesCount = positions.length / 3;
  30989. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30990. indices.push((firstIndex));
  30991. indices.push((firstIndex + 1));
  30992. indices.push(firstIndex + totalYRotationSteps + 1);
  30993. indices.push((firstIndex + totalYRotationSteps + 1));
  30994. indices.push((firstIndex + 1));
  30995. indices.push((firstIndex + totalYRotationSteps + 2));
  30996. }
  30997. }
  30998. }
  30999. // Sides
  31000. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31001. // Result
  31002. var vertexData = new VertexData();
  31003. vertexData.indices = indices;
  31004. vertexData.positions = positions;
  31005. vertexData.normals = normals;
  31006. vertexData.uvs = uvs;
  31007. return vertexData;
  31008. };
  31009. /**
  31010. * Creates the VertexData of the Cylinder or Cone.
  31011. */
  31012. VertexData.CreateCylinder = function (options) {
  31013. var height = options.height || 2;
  31014. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31015. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  31016. var tessellation = options.tessellation || 24;
  31017. var subdivisions = options.subdivisions || 1;
  31018. var hasRings = options.hasRings ? true : false;
  31019. var enclose = options.enclose ? true : false;
  31020. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31021. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31022. var faceUV = options.faceUV || new Array(3);
  31023. var faceColors = options.faceColors;
  31024. // default face colors and UV if undefined
  31025. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31026. var ringNb = (hasRings) ? subdivisions : 1;
  31027. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31028. var f;
  31029. for (f = 0; f < surfaceNb; f++) {
  31030. if (faceColors && faceColors[f] === undefined) {
  31031. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31032. }
  31033. }
  31034. for (f = 0; f < surfaceNb; f++) {
  31035. if (faceUV && faceUV[f] === undefined) {
  31036. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31037. }
  31038. }
  31039. var indices = new Array();
  31040. var positions = new Array();
  31041. var normals = new Array();
  31042. var uvs = new Array();
  31043. var colors = new Array();
  31044. var angle_step = Math.PI * 2 * arc / tessellation;
  31045. var angle;
  31046. var h;
  31047. var radius;
  31048. var tan = (diameterBottom - diameterTop) / 2 / height;
  31049. var ringVertex = BABYLON.Vector3.Zero();
  31050. var ringNormal = BABYLON.Vector3.Zero();
  31051. var ringFirstVertex = BABYLON.Vector3.Zero();
  31052. var ringFirstNormal = BABYLON.Vector3.Zero();
  31053. var quadNormal = BABYLON.Vector3.Zero();
  31054. var Y = BABYLON.Axis.Y;
  31055. // positions, normals, uvs
  31056. var i;
  31057. var j;
  31058. var r;
  31059. var ringIdx = 1;
  31060. var s = 1; // surface index
  31061. var cs = 0;
  31062. var v = 0;
  31063. for (i = 0; i <= subdivisions; i++) {
  31064. h = i / subdivisions;
  31065. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31066. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31067. for (r = 0; r < ringIdx; r++) {
  31068. if (hasRings) {
  31069. s += r;
  31070. }
  31071. if (enclose) {
  31072. s += 2 * r;
  31073. }
  31074. for (j = 0; j <= tessellation; j++) {
  31075. angle = j * angle_step;
  31076. // position
  31077. ringVertex.x = Math.cos(-angle) * radius;
  31078. ringVertex.y = -height / 2 + h * height;
  31079. ringVertex.z = Math.sin(-angle) * radius;
  31080. // normal
  31081. if (diameterTop === 0 && i === subdivisions) {
  31082. // if no top cap, reuse former normals
  31083. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31084. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31085. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31086. }
  31087. else {
  31088. ringNormal.x = ringVertex.x;
  31089. ringNormal.z = ringVertex.z;
  31090. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31091. ringNormal.normalize();
  31092. }
  31093. // keep first ring vertex values for enclose
  31094. if (j === 0) {
  31095. ringFirstVertex.copyFrom(ringVertex);
  31096. ringFirstNormal.copyFrom(ringNormal);
  31097. }
  31098. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31099. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31100. if (hasRings) {
  31101. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31102. }
  31103. else {
  31104. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31105. }
  31106. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31107. if (faceColors) {
  31108. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31109. }
  31110. }
  31111. // if enclose, add four vertices and their dedicated normals
  31112. if (arc !== 1 && enclose) {
  31113. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31114. positions.push(0, ringVertex.y, 0);
  31115. positions.push(0, ringVertex.y, 0);
  31116. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31117. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31118. quadNormal.normalize();
  31119. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31120. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31121. quadNormal.normalize();
  31122. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31123. if (hasRings) {
  31124. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31125. }
  31126. else {
  31127. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31128. }
  31129. uvs.push(faceUV[s + 1].x, v);
  31130. uvs.push(faceUV[s + 1].z, v);
  31131. if (hasRings) {
  31132. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31133. }
  31134. else {
  31135. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31136. }
  31137. uvs.push(faceUV[s + 2].x, v);
  31138. uvs.push(faceUV[s + 2].z, v);
  31139. if (faceColors) {
  31140. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31141. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31142. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31143. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31144. }
  31145. }
  31146. if (cs !== s) {
  31147. cs = s;
  31148. }
  31149. }
  31150. }
  31151. // indices
  31152. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31153. var s;
  31154. i = 0;
  31155. for (s = 0; s < subdivisions; s++) {
  31156. var i0 = 0;
  31157. var i1 = 0;
  31158. var i2 = 0;
  31159. var i3 = 0;
  31160. for (j = 0; j < tessellation; j++) {
  31161. i0 = i * (e + 1) + j;
  31162. i1 = (i + 1) * (e + 1) + j;
  31163. i2 = i * (e + 1) + (j + 1);
  31164. i3 = (i + 1) * (e + 1) + (j + 1);
  31165. indices.push(i0, i1, i2);
  31166. indices.push(i3, i2, i1);
  31167. }
  31168. if (arc !== 1 && enclose) {
  31169. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31170. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31171. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31172. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31173. }
  31174. i = (hasRings) ? (i + 2) : (i + 1);
  31175. }
  31176. // Caps
  31177. var createCylinderCap = function (isTop) {
  31178. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31179. if (radius === 0) {
  31180. return;
  31181. }
  31182. // Cap positions, normals & uvs
  31183. var angle;
  31184. var circleVector;
  31185. var i;
  31186. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31187. var c = null;
  31188. if (faceColors) {
  31189. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31190. }
  31191. // cap center
  31192. var vbase = positions.length / 3;
  31193. var offset = isTop ? height / 2 : -height / 2;
  31194. var center = new BABYLON.Vector3(0, offset, 0);
  31195. positions.push(center.x, center.y, center.z);
  31196. normals.push(0, isTop ? 1 : -1, 0);
  31197. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31198. if (c) {
  31199. colors.push(c.r, c.g, c.b, c.a);
  31200. }
  31201. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31202. for (i = 0; i <= tessellation; i++) {
  31203. angle = Math.PI * 2 * i * arc / tessellation;
  31204. var cos = Math.cos(-angle);
  31205. var sin = Math.sin(-angle);
  31206. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31207. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31208. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31209. normals.push(0, isTop ? 1 : -1, 0);
  31210. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  31211. if (c) {
  31212. colors.push(c.r, c.g, c.b, c.a);
  31213. }
  31214. }
  31215. // Cap indices
  31216. for (i = 0; i < tessellation; i++) {
  31217. if (!isTop) {
  31218. indices.push(vbase);
  31219. indices.push(vbase + (i + 1));
  31220. indices.push(vbase + (i + 2));
  31221. }
  31222. else {
  31223. indices.push(vbase);
  31224. indices.push(vbase + (i + 2));
  31225. indices.push(vbase + (i + 1));
  31226. }
  31227. }
  31228. };
  31229. // add caps to geometry
  31230. createCylinderCap(false);
  31231. createCylinderCap(true);
  31232. // Sides
  31233. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31234. var vertexData = new VertexData();
  31235. vertexData.indices = indices;
  31236. vertexData.positions = positions;
  31237. vertexData.normals = normals;
  31238. vertexData.uvs = uvs;
  31239. if (faceColors) {
  31240. vertexData.colors = colors;
  31241. }
  31242. return vertexData;
  31243. };
  31244. /**
  31245. * Creates the VertexData of the Torus.
  31246. */
  31247. VertexData.CreateTorus = function (options) {
  31248. var indices = [];
  31249. var positions = [];
  31250. var normals = [];
  31251. var uvs = [];
  31252. var diameter = options.diameter || 1;
  31253. var thickness = options.thickness || 0.5;
  31254. var tessellation = options.tessellation || 16;
  31255. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31256. var stride = tessellation + 1;
  31257. for (var i = 0; i <= tessellation; i++) {
  31258. var u = i / tessellation;
  31259. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31260. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31261. for (var j = 0; j <= tessellation; j++) {
  31262. var v = 1 - j / tessellation;
  31263. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31264. var dx = Math.cos(innerAngle);
  31265. var dy = Math.sin(innerAngle);
  31266. // Create a vertex.
  31267. var normal = new BABYLON.Vector3(dx, dy, 0);
  31268. var position = normal.scale(thickness / 2);
  31269. var textureCoordinate = new BABYLON.Vector2(u, v);
  31270. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31271. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31272. positions.push(position.x, position.y, position.z);
  31273. normals.push(normal.x, normal.y, normal.z);
  31274. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31275. // And create indices for two triangles.
  31276. var nextI = (i + 1) % stride;
  31277. var nextJ = (j + 1) % stride;
  31278. indices.push(i * stride + j);
  31279. indices.push(i * stride + nextJ);
  31280. indices.push(nextI * stride + j);
  31281. indices.push(i * stride + nextJ);
  31282. indices.push(nextI * stride + nextJ);
  31283. indices.push(nextI * stride + j);
  31284. }
  31285. }
  31286. // Sides
  31287. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31288. // Result
  31289. var vertexData = new VertexData();
  31290. vertexData.indices = indices;
  31291. vertexData.positions = positions;
  31292. vertexData.normals = normals;
  31293. vertexData.uvs = uvs;
  31294. return vertexData;
  31295. };
  31296. /**
  31297. * Creates the VertexData of the LineSystem.
  31298. */
  31299. VertexData.CreateLineSystem = function (options) {
  31300. var indices = [];
  31301. var positions = [];
  31302. var lines = options.lines;
  31303. var colors = options.colors;
  31304. var vertexColors = [];
  31305. var idx = 0;
  31306. for (var l = 0; l < lines.length; l++) {
  31307. var points = lines[l];
  31308. for (var index = 0; index < points.length; index++) {
  31309. positions.push(points[index].x, points[index].y, points[index].z);
  31310. if (colors) {
  31311. var color = colors[l];
  31312. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  31313. }
  31314. if (index > 0) {
  31315. indices.push(idx - 1);
  31316. indices.push(idx);
  31317. }
  31318. idx++;
  31319. }
  31320. }
  31321. var vertexData = new VertexData();
  31322. vertexData.indices = indices;
  31323. vertexData.positions = positions;
  31324. if (colors) {
  31325. vertexData.colors = vertexColors;
  31326. }
  31327. return vertexData;
  31328. };
  31329. /**
  31330. * Create the VertexData of the DashedLines.
  31331. */
  31332. VertexData.CreateDashedLines = function (options) {
  31333. var dashSize = options.dashSize || 3;
  31334. var gapSize = options.gapSize || 1;
  31335. var dashNb = options.dashNb || 200;
  31336. var points = options.points;
  31337. var positions = new Array();
  31338. var indices = new Array();
  31339. var curvect = BABYLON.Vector3.Zero();
  31340. var lg = 0;
  31341. var nb = 0;
  31342. var shft = 0;
  31343. var dashshft = 0;
  31344. var curshft = 0;
  31345. var idx = 0;
  31346. var i = 0;
  31347. for (i = 0; i < points.length - 1; i++) {
  31348. points[i + 1].subtractToRef(points[i], curvect);
  31349. lg += curvect.length();
  31350. }
  31351. shft = lg / dashNb;
  31352. dashshft = dashSize * shft / (dashSize + gapSize);
  31353. for (i = 0; i < points.length - 1; i++) {
  31354. points[i + 1].subtractToRef(points[i], curvect);
  31355. nb = Math.floor(curvect.length() / shft);
  31356. curvect.normalize();
  31357. for (var j = 0; j < nb; j++) {
  31358. curshft = shft * j;
  31359. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31360. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31361. indices.push(idx, idx + 1);
  31362. idx += 2;
  31363. }
  31364. }
  31365. // Result
  31366. var vertexData = new VertexData();
  31367. vertexData.positions = positions;
  31368. vertexData.indices = indices;
  31369. return vertexData;
  31370. };
  31371. /**
  31372. * Creates the VertexData of the Ground.
  31373. */
  31374. VertexData.CreateGround = function (options) {
  31375. var indices = [];
  31376. var positions = [];
  31377. var normals = [];
  31378. var uvs = [];
  31379. var row, col;
  31380. var width = options.width || 1;
  31381. var height = options.height || 1;
  31382. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31383. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31384. for (row = 0; row <= subdivisionsY; row++) {
  31385. for (col = 0; col <= subdivisionsX; col++) {
  31386. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31387. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31388. positions.push(position.x, position.y, position.z);
  31389. normals.push(normal.x, normal.y, normal.z);
  31390. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  31391. }
  31392. }
  31393. for (row = 0; row < subdivisionsY; row++) {
  31394. for (col = 0; col < subdivisionsX; col++) {
  31395. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31396. indices.push(col + 1 + row * (subdivisionsX + 1));
  31397. indices.push(col + row * (subdivisionsX + 1));
  31398. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31399. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31400. indices.push(col + row * (subdivisionsX + 1));
  31401. }
  31402. }
  31403. // Result
  31404. var vertexData = new VertexData();
  31405. vertexData.indices = indices;
  31406. vertexData.positions = positions;
  31407. vertexData.normals = normals;
  31408. vertexData.uvs = uvs;
  31409. return vertexData;
  31410. };
  31411. /**
  31412. * Creates the VertexData of the TiledGround.
  31413. */
  31414. VertexData.CreateTiledGround = function (options) {
  31415. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  31416. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  31417. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  31418. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  31419. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31420. var precision = options.precision || { w: 1, h: 1 };
  31421. var indices = new Array();
  31422. var positions = new Array();
  31423. var normals = new Array();
  31424. var uvs = new Array();
  31425. var row, col, tileRow, tileCol;
  31426. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31427. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31428. precision.w = (precision.w < 1) ? 1 : precision.w;
  31429. precision.h = (precision.h < 1) ? 1 : precision.h;
  31430. var tileSize = {
  31431. 'w': (xmax - xmin) / subdivisions.w,
  31432. 'h': (zmax - zmin) / subdivisions.h
  31433. };
  31434. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31435. // Indices
  31436. var base = positions.length / 3;
  31437. var rowLength = precision.w + 1;
  31438. for (row = 0; row < precision.h; row++) {
  31439. for (col = 0; col < precision.w; col++) {
  31440. var square = [
  31441. base + col + row * rowLength,
  31442. base + (col + 1) + row * rowLength,
  31443. base + (col + 1) + (row + 1) * rowLength,
  31444. base + col + (row + 1) * rowLength
  31445. ];
  31446. indices.push(square[1]);
  31447. indices.push(square[2]);
  31448. indices.push(square[3]);
  31449. indices.push(square[0]);
  31450. indices.push(square[1]);
  31451. indices.push(square[3]);
  31452. }
  31453. }
  31454. // Position, normals and uvs
  31455. var position = BABYLON.Vector3.Zero();
  31456. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31457. for (row = 0; row <= precision.h; row++) {
  31458. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31459. for (col = 0; col <= precision.w; col++) {
  31460. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31461. position.y = 0;
  31462. positions.push(position.x, position.y, position.z);
  31463. normals.push(normal.x, normal.y, normal.z);
  31464. uvs.push(col / precision.w, row / precision.h);
  31465. }
  31466. }
  31467. }
  31468. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31469. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31470. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31471. }
  31472. }
  31473. // Result
  31474. var vertexData = new VertexData();
  31475. vertexData.indices = indices;
  31476. vertexData.positions = positions;
  31477. vertexData.normals = normals;
  31478. vertexData.uvs = uvs;
  31479. return vertexData;
  31480. };
  31481. /**
  31482. * Creates the VertexData of the Ground designed from a heightmap.
  31483. */
  31484. VertexData.CreateGroundFromHeightMap = function (options) {
  31485. var indices = [];
  31486. var positions = [];
  31487. var normals = [];
  31488. var uvs = [];
  31489. var row, col;
  31490. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  31491. // Vertices
  31492. for (row = 0; row <= options.subdivisions; row++) {
  31493. for (col = 0; col <= options.subdivisions; col++) {
  31494. 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));
  31495. // Compute height
  31496. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31497. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31498. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31499. var r = options.buffer[pos] / 255.0;
  31500. var g = options.buffer[pos + 1] / 255.0;
  31501. var b = options.buffer[pos + 2] / 255.0;
  31502. var gradient = r * filter.r + g * filter.g + b * filter.b;
  31503. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31504. // Add vertex
  31505. positions.push(position.x, position.y, position.z);
  31506. normals.push(0, 0, 0);
  31507. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31508. }
  31509. }
  31510. // Indices
  31511. for (row = 0; row < options.subdivisions; row++) {
  31512. for (col = 0; col < options.subdivisions; col++) {
  31513. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31514. indices.push(col + 1 + row * (options.subdivisions + 1));
  31515. indices.push(col + row * (options.subdivisions + 1));
  31516. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31517. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31518. indices.push(col + row * (options.subdivisions + 1));
  31519. }
  31520. }
  31521. // Normals
  31522. VertexData.ComputeNormals(positions, indices, normals);
  31523. // Result
  31524. var vertexData = new VertexData();
  31525. vertexData.indices = indices;
  31526. vertexData.positions = positions;
  31527. vertexData.normals = normals;
  31528. vertexData.uvs = uvs;
  31529. return vertexData;
  31530. };
  31531. /**
  31532. * Creates the VertexData of the Plane.
  31533. */
  31534. VertexData.CreatePlane = function (options) {
  31535. var indices = [];
  31536. var positions = [];
  31537. var normals = [];
  31538. var uvs = [];
  31539. var width = options.width || options.size || 1;
  31540. var height = options.height || options.size || 1;
  31541. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31542. // Vertices
  31543. var halfWidth = width / 2.0;
  31544. var halfHeight = height / 2.0;
  31545. positions.push(-halfWidth, -halfHeight, 0);
  31546. normals.push(0, 0, -1.0);
  31547. uvs.push(0.0, 0.0);
  31548. positions.push(halfWidth, -halfHeight, 0);
  31549. normals.push(0, 0, -1.0);
  31550. uvs.push(1.0, 0.0);
  31551. positions.push(halfWidth, halfHeight, 0);
  31552. normals.push(0, 0, -1.0);
  31553. uvs.push(1.0, 1.0);
  31554. positions.push(-halfWidth, halfHeight, 0);
  31555. normals.push(0, 0, -1.0);
  31556. uvs.push(0.0, 1.0);
  31557. // Indices
  31558. indices.push(0);
  31559. indices.push(1);
  31560. indices.push(2);
  31561. indices.push(0);
  31562. indices.push(2);
  31563. indices.push(3);
  31564. // Sides
  31565. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31566. // Result
  31567. var vertexData = new VertexData();
  31568. vertexData.indices = indices;
  31569. vertexData.positions = positions;
  31570. vertexData.normals = normals;
  31571. vertexData.uvs = uvs;
  31572. return vertexData;
  31573. };
  31574. /**
  31575. * Creates the VertexData of the Disc or regular Polygon.
  31576. */
  31577. VertexData.CreateDisc = function (options) {
  31578. var positions = new Array();
  31579. var indices = new Array();
  31580. var normals = new Array();
  31581. var uvs = new Array();
  31582. var radius = options.radius || 0.5;
  31583. var tessellation = options.tessellation || 64;
  31584. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31585. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31586. // positions and uvs
  31587. positions.push(0, 0, 0); // disc center first
  31588. uvs.push(0.5, 0.5);
  31589. var theta = Math.PI * 2 * arc;
  31590. var step = theta / tessellation;
  31591. for (var a = 0; a < theta; a += step) {
  31592. var x = Math.cos(a);
  31593. var y = Math.sin(a);
  31594. var u = (x + 1) / 2;
  31595. var v = (1 - y) / 2;
  31596. positions.push(radius * x, radius * y, 0);
  31597. uvs.push(u, v);
  31598. }
  31599. if (arc === 1) {
  31600. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31601. uvs.push(uvs[2], uvs[3]);
  31602. }
  31603. //indices
  31604. var vertexNb = positions.length / 3;
  31605. for (var i = 1; i < vertexNb - 1; i++) {
  31606. indices.push(i + 1, 0, i);
  31607. }
  31608. // result
  31609. VertexData.ComputeNormals(positions, indices, normals);
  31610. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31611. var vertexData = new VertexData();
  31612. vertexData.indices = indices;
  31613. vertexData.positions = positions;
  31614. vertexData.normals = normals;
  31615. vertexData.uvs = uvs;
  31616. return vertexData;
  31617. };
  31618. /**
  31619. * Re-creates the VertexData of the Polygon for sideOrientation.
  31620. */
  31621. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  31622. var faceUV = fUV || new Array(3);
  31623. var faceColors = fColors;
  31624. var colors = [];
  31625. // default face colors and UV if undefined
  31626. for (var f = 0; f < 3; f++) {
  31627. if (faceUV[f] === undefined) {
  31628. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31629. }
  31630. if (faceColors && faceColors[f] === undefined) {
  31631. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31632. }
  31633. }
  31634. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31635. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31636. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31637. var indices = polygon.getIndices();
  31638. // set face colours and textures
  31639. var idx = 0;
  31640. var face = 0;
  31641. for (var index = 0; index < normals.length; index += 3) {
  31642. //Edge Face no. 1
  31643. if (Math.abs(normals[index + 1]) < 0.001) {
  31644. face = 1;
  31645. }
  31646. //Top Face no. 0
  31647. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  31648. face = 0;
  31649. }
  31650. //Bottom Face no. 2
  31651. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  31652. face = 2;
  31653. }
  31654. idx = index / 3;
  31655. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  31656. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  31657. if (faceColors) {
  31658. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  31659. }
  31660. }
  31661. // sides
  31662. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  31663. // Result
  31664. var vertexData = new VertexData();
  31665. vertexData.indices = indices;
  31666. vertexData.positions = positions;
  31667. vertexData.normals = normals;
  31668. vertexData.uvs = uvs;
  31669. if (faceColors) {
  31670. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31671. vertexData.colors = totalColors;
  31672. }
  31673. return vertexData;
  31674. };
  31675. /**
  31676. * Creates the VertexData of the IcoSphere.
  31677. */
  31678. VertexData.CreateIcoSphere = function (options) {
  31679. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31680. var radius = options.radius || 1;
  31681. var flat = (options.flat === undefined) ? true : options.flat;
  31682. var subdivisions = options.subdivisions || 4;
  31683. var radiusX = options.radiusX || radius;
  31684. var radiusY = options.radiusY || radius;
  31685. var radiusZ = options.radiusZ || radius;
  31686. var t = (1 + Math.sqrt(5)) / 2;
  31687. // 12 vertex x,y,z
  31688. var ico_vertices = [
  31689. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31690. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31691. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31692. ];
  31693. // index of 3 vertex makes a face of icopshere
  31694. var ico_indices = [
  31695. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31696. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31697. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31698. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31699. ];
  31700. // vertex for uv have aliased position, not for UV
  31701. var vertices_unalias_id = [
  31702. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31703. // vertex alias
  31704. 0,
  31705. 2,
  31706. 3,
  31707. 3,
  31708. 3,
  31709. 4,
  31710. 7,
  31711. 8,
  31712. 9,
  31713. 9,
  31714. 10,
  31715. 11 // 23: B + 12
  31716. ];
  31717. // uv as integer step (not pixels !)
  31718. var ico_vertexuv = [
  31719. 5, 1, 3, 1, 6, 4, 0, 0,
  31720. 5, 3, 4, 2, 2, 2, 4, 0,
  31721. 2, 0, 1, 1, 6, 0, 6, 2,
  31722. // vertex alias (for same vertex on different faces)
  31723. 0, 4,
  31724. 3, 3,
  31725. 4, 4,
  31726. 3, 1,
  31727. 4, 2,
  31728. 4, 4,
  31729. 0, 2,
  31730. 1, 1,
  31731. 2, 2,
  31732. 3, 3,
  31733. 1, 3,
  31734. 2, 4 // 23: B + 12
  31735. ];
  31736. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31737. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31738. // First island of uv mapping
  31739. // v = 4h 3+ 2
  31740. // v = 3h 9+ 4
  31741. // v = 2h 9+ 5 B
  31742. // v = 1h 9 1 0
  31743. // v = 0h 3 8 7 A
  31744. // u = 0 1 2 3 4 5 6 *a
  31745. // Second island of uv mapping
  31746. // v = 4h 0+ B+ 4+
  31747. // v = 3h A+ 2+
  31748. // v = 2h 7+ 6 3+
  31749. // v = 1h 8+ 3+
  31750. // v = 0h
  31751. // u = 0 1 2 3 4 5 6 *a
  31752. // Face layout on texture UV mapping
  31753. // ============
  31754. // \ 4 /\ 16 / ======
  31755. // \ / \ / /\ 11 /
  31756. // \/ 7 \/ / \ /
  31757. // ======= / 10 \/
  31758. // /\ 17 /\ =======
  31759. // / \ / \ \ 15 /\
  31760. // / 8 \/ 12 \ \ / \
  31761. // ============ \/ 6 \
  31762. // \ 18 /\ ============
  31763. // \ / \ \ 5 /\ 0 /
  31764. // \/ 13 \ \ / \ /
  31765. // ======= \/ 1 \/
  31766. // =============
  31767. // /\ 19 /\ 2 /\
  31768. // / \ / \ / \
  31769. // / 14 \/ 9 \/ 3 \
  31770. // ===================
  31771. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31772. var ustep = 138 / 1024;
  31773. var vstep = 239 / 1024;
  31774. var uoffset = 60 / 1024;
  31775. var voffset = 26 / 1024;
  31776. // Second island should have margin, not to touch the first island
  31777. // avoid any borderline artefact in pixel rounding
  31778. var island_u_offset = -40 / 1024;
  31779. var island_v_offset = +20 / 1024;
  31780. // face is either island 0 or 1 :
  31781. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31782. var island = [
  31783. 0, 0, 0, 0, 1,
  31784. 0, 0, 1, 1, 0,
  31785. 0, 0, 1, 1, 0,
  31786. 0, 1, 1, 1, 0 // 15 - 19
  31787. ];
  31788. var indices = new Array();
  31789. var positions = new Array();
  31790. var normals = new Array();
  31791. var uvs = new Array();
  31792. var current_indice = 0;
  31793. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31794. var face_vertex_pos = new Array(3);
  31795. var face_vertex_uv = new Array(3);
  31796. var v012;
  31797. for (v012 = 0; v012 < 3; v012++) {
  31798. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31799. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31800. }
  31801. // create all with normals
  31802. for (var face = 0; face < 20; face++) {
  31803. // 3 vertex per face
  31804. for (v012 = 0; v012 < 3; v012++) {
  31805. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31806. var v_id = ico_indices[3 * face + v012];
  31807. // vertex have 3D position (x,y,z)
  31808. 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]);
  31809. // Normalize to get normal, then scale to radius
  31810. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31811. // uv Coordinates from vertex ID
  31812. 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);
  31813. }
  31814. // Subdivide the face (interpolate pos, norm, uv)
  31815. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31816. // - norm is linear interpolation of vertex corner normal
  31817. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31818. // - uv is linear interpolation
  31819. //
  31820. // Topology is as below for sub-divide by 2
  31821. // vertex shown as v0,v1,v2
  31822. // interp index is i1 to progress in range [v0,v1[
  31823. // interp index is i2 to progress in range [v0,v2[
  31824. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31825. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31826. //
  31827. //
  31828. // i2 v2
  31829. // ^ ^
  31830. // / / \
  31831. // / / \
  31832. // / / \
  31833. // / / (0,1) \
  31834. // / #---------\
  31835. // / / \ (0,0)'/ \
  31836. // / / \ / \
  31837. // / / \ / \
  31838. // / / (0,0) \ / (1,0) \
  31839. // / #---------#---------\
  31840. // v0 v1
  31841. //
  31842. // --------------------> i1
  31843. //
  31844. // interp of (i1,i2):
  31845. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31846. // along i1 : lerp(x0,x1, i1/(S-i2))
  31847. //
  31848. // centroid of triangle is needed to get help normal computation
  31849. // (c1,c2) are used for centroid location
  31850. var interp_vertex = function (i1, i2, c1, c2) {
  31851. // vertex is interpolated from
  31852. // - face_vertex_pos[0..2]
  31853. // - face_vertex_uv[0..2]
  31854. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31855. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31856. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31857. pos_interp.normalize();
  31858. var vertex_normal;
  31859. if (flat) {
  31860. // in flat mode, recalculate normal as face centroid normal
  31861. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31862. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31863. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31864. }
  31865. else {
  31866. // in smooth mode, recalculate normal from each single vertex position
  31867. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31868. }
  31869. // Vertex normal need correction due to X,Y,Z radius scaling
  31870. vertex_normal.x /= radiusX;
  31871. vertex_normal.y /= radiusY;
  31872. vertex_normal.z /= radiusZ;
  31873. vertex_normal.normalize();
  31874. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31875. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31876. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31877. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31878. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31879. uvs.push(uv_interp.x, uv_interp.y);
  31880. // push each vertex has member of a face
  31881. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31882. indices.push(current_indice);
  31883. current_indice++;
  31884. };
  31885. for (var i2 = 0; i2 < subdivisions; i2++) {
  31886. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31887. // face : (i1,i2) for /\ :
  31888. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31889. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31890. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31891. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31892. if (i1 + i2 + 1 < subdivisions) {
  31893. // face : (i1,i2)' for \/ :
  31894. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31895. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31896. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31897. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31898. }
  31899. }
  31900. }
  31901. }
  31902. // Sides
  31903. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31904. // Result
  31905. var vertexData = new VertexData();
  31906. vertexData.indices = indices;
  31907. vertexData.positions = positions;
  31908. vertexData.normals = normals;
  31909. vertexData.uvs = uvs;
  31910. return vertexData;
  31911. };
  31912. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31913. /**
  31914. * Creates the VertexData of the Polyhedron.
  31915. */
  31916. VertexData.CreatePolyhedron = function (options) {
  31917. // provided polyhedron types :
  31918. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31919. // 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)
  31920. var polyhedra = [];
  31921. 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]] };
  31922. 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]] };
  31923. polyhedra[2] = {
  31924. 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]],
  31925. 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]]
  31926. };
  31927. polyhedra[3] = {
  31928. 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]],
  31929. 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]]
  31930. };
  31931. polyhedra[4] = {
  31932. 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]],
  31933. 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]]
  31934. };
  31935. 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]] };
  31936. 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]] };
  31937. 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]] };
  31938. 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]] };
  31939. 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]] };
  31940. 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]] };
  31941. 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]] };
  31942. 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]] };
  31943. 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]] };
  31944. polyhedra[14] = {
  31945. 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]],
  31946. 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]]
  31947. };
  31948. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31949. var size = options.size;
  31950. var sizeX = options.sizeX || size || 1;
  31951. var sizeY = options.sizeY || size || 1;
  31952. var sizeZ = options.sizeZ || size || 1;
  31953. var data = options.custom || polyhedra[type];
  31954. var nbfaces = data.face.length;
  31955. var faceUV = options.faceUV || new Array(nbfaces);
  31956. var faceColors = options.faceColors;
  31957. var flat = (options.flat === undefined) ? true : options.flat;
  31958. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31959. var positions = new Array();
  31960. var indices = new Array();
  31961. var normals = new Array();
  31962. var uvs = new Array();
  31963. var colors = new Array();
  31964. var index = 0;
  31965. var faceIdx = 0; // face cursor in the array "indexes"
  31966. var indexes = new Array();
  31967. var i = 0;
  31968. var f = 0;
  31969. var u, v, ang, x, y, tmp;
  31970. // default face colors and UV if undefined
  31971. if (flat) {
  31972. for (f = 0; f < nbfaces; f++) {
  31973. if (faceColors && faceColors[f] === undefined) {
  31974. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31975. }
  31976. if (faceUV && faceUV[f] === undefined) {
  31977. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31978. }
  31979. }
  31980. }
  31981. if (!flat) {
  31982. for (i = 0; i < data.vertex.length; i++) {
  31983. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31984. uvs.push(0, 0);
  31985. }
  31986. for (f = 0; f < nbfaces; f++) {
  31987. for (i = 0; i < data.face[f].length - 2; i++) {
  31988. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31989. }
  31990. }
  31991. }
  31992. else {
  31993. for (f = 0; f < nbfaces; f++) {
  31994. var fl = data.face[f].length; // number of vertices of the current face
  31995. ang = 2 * Math.PI / fl;
  31996. x = 0.5 * Math.tan(ang / 2);
  31997. y = 0.5;
  31998. // positions, uvs, colors
  31999. for (i = 0; i < fl; i++) {
  32000. // positions
  32001. 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);
  32002. indexes.push(index);
  32003. index++;
  32004. // uvs
  32005. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32006. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32007. uvs.push(u, v);
  32008. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32009. y = x * Math.sin(ang) + y * Math.cos(ang);
  32010. x = tmp;
  32011. // colors
  32012. if (faceColors) {
  32013. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32014. }
  32015. }
  32016. // indices from indexes
  32017. for (i = 0; i < fl - 2; i++) {
  32018. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32019. }
  32020. faceIdx += fl;
  32021. }
  32022. }
  32023. VertexData.ComputeNormals(positions, indices, normals);
  32024. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32025. var vertexData = new VertexData();
  32026. vertexData.positions = positions;
  32027. vertexData.indices = indices;
  32028. vertexData.normals = normals;
  32029. vertexData.uvs = uvs;
  32030. if (faceColors && flat) {
  32031. vertexData.colors = colors;
  32032. }
  32033. return vertexData;
  32034. };
  32035. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32036. /**
  32037. * Creates the VertexData of the Torus Knot.
  32038. */
  32039. VertexData.CreateTorusKnot = function (options) {
  32040. var indices = new Array();
  32041. var positions = new Array();
  32042. var normals = new Array();
  32043. var uvs = new Array();
  32044. var radius = options.radius || 2;
  32045. var tube = options.tube || 0.5;
  32046. var radialSegments = options.radialSegments || 32;
  32047. var tubularSegments = options.tubularSegments || 32;
  32048. var p = options.p || 2;
  32049. var q = options.q || 3;
  32050. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32051. // Helper
  32052. var getPos = function (angle) {
  32053. var cu = Math.cos(angle);
  32054. var su = Math.sin(angle);
  32055. var quOverP = q / p * angle;
  32056. var cs = Math.cos(quOverP);
  32057. var tx = radius * (2 + cs) * 0.5 * cu;
  32058. var ty = radius * (2 + cs) * su * 0.5;
  32059. var tz = radius * Math.sin(quOverP) * 0.5;
  32060. return new BABYLON.Vector3(tx, ty, tz);
  32061. };
  32062. // Vertices
  32063. var i;
  32064. var j;
  32065. for (i = 0; i <= radialSegments; i++) {
  32066. var modI = i % radialSegments;
  32067. var u = modI / radialSegments * 2 * p * Math.PI;
  32068. var p1 = getPos(u);
  32069. var p2 = getPos(u + 0.01);
  32070. var tang = p2.subtract(p1);
  32071. var n = p2.add(p1);
  32072. var bitan = BABYLON.Vector3.Cross(tang, n);
  32073. n = BABYLON.Vector3.Cross(bitan, tang);
  32074. bitan.normalize();
  32075. n.normalize();
  32076. for (j = 0; j < tubularSegments; j++) {
  32077. var modJ = j % tubularSegments;
  32078. var v = modJ / tubularSegments * 2 * Math.PI;
  32079. var cx = -tube * Math.cos(v);
  32080. var cy = tube * Math.sin(v);
  32081. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32082. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32083. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32084. uvs.push(i / radialSegments);
  32085. uvs.push(j / tubularSegments);
  32086. }
  32087. }
  32088. for (i = 0; i < radialSegments; i++) {
  32089. for (j = 0; j < tubularSegments; j++) {
  32090. var jNext = (j + 1) % tubularSegments;
  32091. var a = i * tubularSegments + j;
  32092. var b = (i + 1) * tubularSegments + j;
  32093. var c = (i + 1) * tubularSegments + jNext;
  32094. var d = i * tubularSegments + jNext;
  32095. indices.push(d);
  32096. indices.push(b);
  32097. indices.push(a);
  32098. indices.push(d);
  32099. indices.push(c);
  32100. indices.push(b);
  32101. }
  32102. }
  32103. // Normals
  32104. VertexData.ComputeNormals(positions, indices, normals);
  32105. // Sides
  32106. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32107. // Result
  32108. var vertexData = new VertexData();
  32109. vertexData.indices = indices;
  32110. vertexData.positions = positions;
  32111. vertexData.normals = normals;
  32112. vertexData.uvs = uvs;
  32113. return vertexData;
  32114. };
  32115. // Tools
  32116. /**
  32117. * @param {any} - positions (number[] or Float32Array)
  32118. * @param {any} - indices (number[] or Uint16Array)
  32119. * @param {any} - normals (number[] or Float32Array)
  32120. * options (optional) :
  32121. * facetPositions : optional array of facet positions (vector3)
  32122. * facetNormals : optional array of facet normals (vector3)
  32123. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  32124. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  32125. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  32126. * bbSize : optional bounding box size data, required for facetPartitioning computation
  32127. * bInfo : optional bounding info, required for facetPartitioning computation
  32128. * useRightHandedSystem: optional boolean to for right handed system computation
  32129. * depthSort : optional boolean to enable the facet depth sort computation
  32130. * distanceTo : optional Vector3 to compute the facet depth from this location
  32131. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  32132. */
  32133. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  32134. // temporary scalar variables
  32135. var index = 0; // facet index
  32136. var p1p2x = 0.0; // p1p2 vector x coordinate
  32137. var p1p2y = 0.0; // p1p2 vector y coordinate
  32138. var p1p2z = 0.0; // p1p2 vector z coordinate
  32139. var p3p2x = 0.0; // p3p2 vector x coordinate
  32140. var p3p2y = 0.0; // p3p2 vector y coordinate
  32141. var p3p2z = 0.0; // p3p2 vector z coordinate
  32142. var faceNormalx = 0.0; // facet normal x coordinate
  32143. var faceNormaly = 0.0; // facet normal y coordinate
  32144. var faceNormalz = 0.0; // facet normal z coordinate
  32145. var length = 0.0; // facet normal length before normalization
  32146. var v1x = 0; // vector1 x index in the positions array
  32147. var v1y = 0; // vector1 y index in the positions array
  32148. var v1z = 0; // vector1 z index in the positions array
  32149. var v2x = 0; // vector2 x index in the positions array
  32150. var v2y = 0; // vector2 y index in the positions array
  32151. var v2z = 0; // vector2 z index in the positions array
  32152. var v3x = 0; // vector3 x index in the positions array
  32153. var v3y = 0; // vector3 y index in the positions array
  32154. var v3z = 0; // vector3 z index in the positions array
  32155. var computeFacetNormals = false;
  32156. var computeFacetPositions = false;
  32157. var computeFacetPartitioning = false;
  32158. var computeDepthSort = false;
  32159. var faceNormalSign = 1;
  32160. var ratio = 0;
  32161. var distanceTo = null;
  32162. if (options) {
  32163. computeFacetNormals = (options.facetNormals) ? true : false;
  32164. computeFacetPositions = (options.facetPositions) ? true : false;
  32165. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  32166. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  32167. ratio = options.ratio || 0;
  32168. computeDepthSort = (options.depthSort) ? true : false;
  32169. distanceTo = (options.distanceTo);
  32170. if (computeDepthSort) {
  32171. if (distanceTo === undefined) {
  32172. distanceTo = BABYLON.Vector3.Zero();
  32173. }
  32174. var depthSortedFacets = options.depthSortedFacets;
  32175. }
  32176. }
  32177. // facetPartitioning reinit if needed
  32178. var xSubRatio = 0;
  32179. var ySubRatio = 0;
  32180. var zSubRatio = 0;
  32181. var subSq = 0;
  32182. if (computeFacetPartitioning && options && options.bbSize) {
  32183. var ox = 0; // X partitioning index for facet position
  32184. var oy = 0; // Y partinioning index for facet position
  32185. var oz = 0; // Z partinioning index for facet position
  32186. var b1x = 0; // X partitioning index for facet v1 vertex
  32187. var b1y = 0; // Y partitioning index for facet v1 vertex
  32188. var b1z = 0; // z partitioning index for facet v1 vertex
  32189. var b2x = 0; // X partitioning index for facet v2 vertex
  32190. var b2y = 0; // Y partitioning index for facet v2 vertex
  32191. var b2z = 0; // Z partitioning index for facet v2 vertex
  32192. var b3x = 0; // X partitioning index for facet v3 vertex
  32193. var b3y = 0; // Y partitioning index for facet v3 vertex
  32194. var b3z = 0; // Z partitioning index for facet v3 vertex
  32195. var block_idx_o = 0; // facet barycenter block index
  32196. var block_idx_v1 = 0; // v1 vertex block index
  32197. var block_idx_v2 = 0; // v2 vertex block index
  32198. var block_idx_v3 = 0; // v3 vertex block index
  32199. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  32200. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  32201. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  32202. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  32203. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  32204. subSq = options.subDiv.max * options.subDiv.max;
  32205. options.facetPartitioning.length = 0;
  32206. }
  32207. // reset the normals
  32208. for (index = 0; index < positions.length; index++) {
  32209. normals[index] = 0.0;
  32210. }
  32211. // Loop : 1 indice triplet = 1 facet
  32212. var nbFaces = (indices.length / 3) | 0;
  32213. for (index = 0; index < nbFaces; index++) {
  32214. // get the indexes of the coordinates of each vertex of the facet
  32215. v1x = indices[index * 3] * 3;
  32216. v1y = v1x + 1;
  32217. v1z = v1x + 2;
  32218. v2x = indices[index * 3 + 1] * 3;
  32219. v2y = v2x + 1;
  32220. v2z = v2x + 2;
  32221. v3x = indices[index * 3 + 2] * 3;
  32222. v3y = v3x + 1;
  32223. v3z = v3x + 2;
  32224. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  32225. p1p2y = positions[v1y] - positions[v2y];
  32226. p1p2z = positions[v1z] - positions[v2z];
  32227. p3p2x = positions[v3x] - positions[v2x];
  32228. p3p2y = positions[v3y] - positions[v2y];
  32229. p3p2z = positions[v3z] - positions[v2z];
  32230. // compute the face normal with the cross product
  32231. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  32232. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  32233. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  32234. // normalize this normal and store it in the array facetData
  32235. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32236. length = (length === 0) ? 1.0 : length;
  32237. faceNormalx /= length;
  32238. faceNormaly /= length;
  32239. faceNormalz /= length;
  32240. if (computeFacetNormals && options) {
  32241. options.facetNormals[index].x = faceNormalx;
  32242. options.facetNormals[index].y = faceNormaly;
  32243. options.facetNormals[index].z = faceNormalz;
  32244. }
  32245. if (computeFacetPositions && options) {
  32246. // compute and the facet barycenter coordinates in the array facetPositions
  32247. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  32248. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  32249. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  32250. }
  32251. if (computeFacetPartitioning && options) {
  32252. // store the facet indexes in arrays in the main facetPartitioning array :
  32253. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  32254. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  32255. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  32256. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  32257. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32258. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32259. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32260. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32261. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32262. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32263. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32264. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32265. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32266. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  32267. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  32268. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  32269. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  32270. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  32271. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  32272. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  32273. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  32274. // push each facet index in each block containing the vertex
  32275. options.facetPartitioning[block_idx_v1].push(index);
  32276. if (block_idx_v2 != block_idx_v1) {
  32277. options.facetPartitioning[block_idx_v2].push(index);
  32278. }
  32279. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  32280. options.facetPartitioning[block_idx_v3].push(index);
  32281. }
  32282. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  32283. options.facetPartitioning[block_idx_o].push(index);
  32284. }
  32285. }
  32286. if (computeDepthSort && options && options.facetPositions) {
  32287. var dsf = depthSortedFacets[index];
  32288. dsf.ind = index * 3;
  32289. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  32290. }
  32291. // compute the normals anyway
  32292. normals[v1x] += faceNormalx; // accumulate all the normals per face
  32293. normals[v1y] += faceNormaly;
  32294. normals[v1z] += faceNormalz;
  32295. normals[v2x] += faceNormalx;
  32296. normals[v2y] += faceNormaly;
  32297. normals[v2z] += faceNormalz;
  32298. normals[v3x] += faceNormalx;
  32299. normals[v3y] += faceNormaly;
  32300. normals[v3z] += faceNormalz;
  32301. }
  32302. // last normalization of each normal
  32303. for (index = 0; index < normals.length / 3; index++) {
  32304. faceNormalx = normals[index * 3];
  32305. faceNormaly = normals[index * 3 + 1];
  32306. faceNormalz = normals[index * 3 + 2];
  32307. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32308. length = (length === 0) ? 1.0 : length;
  32309. faceNormalx /= length;
  32310. faceNormaly /= length;
  32311. faceNormalz /= length;
  32312. normals[index * 3] = faceNormalx;
  32313. normals[index * 3 + 1] = faceNormaly;
  32314. normals[index * 3 + 2] = faceNormalz;
  32315. }
  32316. };
  32317. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  32318. var li = indices.length;
  32319. var ln = normals.length;
  32320. var i;
  32321. var n;
  32322. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32323. switch (sideOrientation) {
  32324. case BABYLON.Mesh.FRONTSIDE:
  32325. // nothing changed
  32326. break;
  32327. case BABYLON.Mesh.BACKSIDE:
  32328. var tmp;
  32329. // indices
  32330. for (i = 0; i < li; i += 3) {
  32331. tmp = indices[i];
  32332. indices[i] = indices[i + 2];
  32333. indices[i + 2] = tmp;
  32334. }
  32335. // normals
  32336. for (n = 0; n < ln; n++) {
  32337. normals[n] = -normals[n];
  32338. }
  32339. break;
  32340. case BABYLON.Mesh.DOUBLESIDE:
  32341. // positions
  32342. var lp = positions.length;
  32343. var l = lp / 3;
  32344. for (var p = 0; p < lp; p++) {
  32345. positions[lp + p] = positions[p];
  32346. }
  32347. // indices
  32348. for (i = 0; i < li; i += 3) {
  32349. indices[i + li] = indices[i + 2] + l;
  32350. indices[i + 1 + li] = indices[i + 1] + l;
  32351. indices[i + 2 + li] = indices[i] + l;
  32352. }
  32353. // normals
  32354. for (n = 0; n < ln; n++) {
  32355. normals[ln + n] = -normals[n];
  32356. }
  32357. // uvs
  32358. var lu = uvs.length;
  32359. var u = 0;
  32360. for (u = 0; u < lu; u++) {
  32361. uvs[u + lu] = uvs[u];
  32362. }
  32363. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32364. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32365. u = 0;
  32366. for (i = 0; i < lu / 2; i++) {
  32367. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  32368. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  32369. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  32370. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  32371. u += 2;
  32372. }
  32373. break;
  32374. }
  32375. };
  32376. /**
  32377. * Creates a new VertexData from the imported parameters.
  32378. */
  32379. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32380. var vertexData = new VertexData();
  32381. // positions
  32382. var positions = parsedVertexData.positions;
  32383. if (positions) {
  32384. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32385. }
  32386. // normals
  32387. var normals = parsedVertexData.normals;
  32388. if (normals) {
  32389. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32390. }
  32391. // tangents
  32392. var tangents = parsedVertexData.tangents;
  32393. if (tangents) {
  32394. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  32395. }
  32396. // uvs
  32397. var uvs = parsedVertexData.uvs;
  32398. if (uvs) {
  32399. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32400. }
  32401. // uv2s
  32402. var uv2s = parsedVertexData.uv2s;
  32403. if (uv2s) {
  32404. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32405. }
  32406. // uv3s
  32407. var uv3s = parsedVertexData.uv3s;
  32408. if (uv3s) {
  32409. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32410. }
  32411. // uv4s
  32412. var uv4s = parsedVertexData.uv4s;
  32413. if (uv4s) {
  32414. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32415. }
  32416. // uv5s
  32417. var uv5s = parsedVertexData.uv5s;
  32418. if (uv5s) {
  32419. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32420. }
  32421. // uv6s
  32422. var uv6s = parsedVertexData.uv6s;
  32423. if (uv6s) {
  32424. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32425. }
  32426. // colors
  32427. var colors = parsedVertexData.colors;
  32428. if (colors) {
  32429. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32430. }
  32431. // matricesIndices
  32432. var matricesIndices = parsedVertexData.matricesIndices;
  32433. if (matricesIndices) {
  32434. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32435. }
  32436. // matricesWeights
  32437. var matricesWeights = parsedVertexData.matricesWeights;
  32438. if (matricesWeights) {
  32439. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32440. }
  32441. // indices
  32442. var indices = parsedVertexData.indices;
  32443. if (indices) {
  32444. vertexData.indices = indices;
  32445. }
  32446. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32447. };
  32448. return VertexData;
  32449. }());
  32450. BABYLON.VertexData = VertexData;
  32451. })(BABYLON || (BABYLON = {}));
  32452. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  32453. var BABYLON;
  32454. (function (BABYLON) {
  32455. /**
  32456. * Class used to store geometry data (vertex buffers + index buffer)
  32457. */
  32458. var Geometry = /** @class */ (function () {
  32459. /**
  32460. * Creates a new geometry
  32461. * @param id defines the unique ID
  32462. * @param scene defines the hosting scene
  32463. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  32464. * @param updatable defines if geometry must be updatable (false by default)
  32465. * @param mesh defines the mesh that will be associated with the geometry
  32466. */
  32467. function Geometry(id, scene, vertexData, updatable, mesh) {
  32468. if (updatable === void 0) { updatable = false; }
  32469. if (mesh === void 0) { mesh = null; }
  32470. /**
  32471. * Gets the delay loading state of the geometry (none by default which means not delayed)
  32472. */
  32473. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32474. this._totalVertices = 0;
  32475. this._isDisposed = false;
  32476. this._indexBufferIsUpdatable = false;
  32477. this.id = id;
  32478. this._engine = scene.getEngine();
  32479. this._meshes = [];
  32480. this._scene = scene;
  32481. //Init vertex buffer cache
  32482. this._vertexBuffers = {};
  32483. this._indices = [];
  32484. this._updatable = updatable;
  32485. // vertexData
  32486. if (vertexData) {
  32487. this.setAllVerticesData(vertexData, updatable);
  32488. }
  32489. else {
  32490. this._totalVertices = 0;
  32491. this._indices = [];
  32492. }
  32493. if (this._engine.getCaps().vertexArrayObject) {
  32494. this._vertexArrayObjects = {};
  32495. }
  32496. // applyToMesh
  32497. if (mesh) {
  32498. if (mesh.getClassName() === "LinesMesh") {
  32499. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32500. this.updateExtend();
  32501. }
  32502. this.applyToMesh(mesh);
  32503. mesh.computeWorldMatrix(true);
  32504. }
  32505. }
  32506. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32507. /**
  32508. * 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
  32509. */
  32510. get: function () {
  32511. return this._boundingBias;
  32512. },
  32513. /**
  32514. * 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
  32515. */
  32516. set: function (value) {
  32517. if (this._boundingBias && this._boundingBias.equals(value)) {
  32518. return;
  32519. }
  32520. this._boundingBias = value.clone();
  32521. this.updateBoundingInfo(true, null);
  32522. },
  32523. enumerable: true,
  32524. configurable: true
  32525. });
  32526. /**
  32527. * Static function used to attach a new empty geometry to a mesh
  32528. * @param mesh defines the mesh to attach the geometry to
  32529. * @returns the new {BABYLON.Geometry}
  32530. */
  32531. Geometry.CreateGeometryForMesh = function (mesh) {
  32532. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  32533. geometry.applyToMesh(mesh);
  32534. return geometry;
  32535. };
  32536. Object.defineProperty(Geometry.prototype, "extend", {
  32537. /**
  32538. * Gets the current extend of the geometry
  32539. */
  32540. get: function () {
  32541. return this._extend;
  32542. },
  32543. enumerable: true,
  32544. configurable: true
  32545. });
  32546. /**
  32547. * Gets the hosting scene
  32548. * @returns the hosting {BABYLON.Scene}
  32549. */
  32550. Geometry.prototype.getScene = function () {
  32551. return this._scene;
  32552. };
  32553. /**
  32554. * Gets the hosting engine
  32555. * @returns the hosting {BABYLON.Engine}
  32556. */
  32557. Geometry.prototype.getEngine = function () {
  32558. return this._engine;
  32559. };
  32560. /**
  32561. * Defines if the geometry is ready to use
  32562. * @returns true if the geometry is ready to be used
  32563. */
  32564. Geometry.prototype.isReady = function () {
  32565. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32566. };
  32567. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  32568. /**
  32569. * Gets a value indicating that the geometry should not be serialized
  32570. */
  32571. get: function () {
  32572. for (var index = 0; index < this._meshes.length; index++) {
  32573. if (!this._meshes[index].doNotSerialize) {
  32574. return false;
  32575. }
  32576. }
  32577. return true;
  32578. },
  32579. enumerable: true,
  32580. configurable: true
  32581. });
  32582. /** @ignore */
  32583. Geometry.prototype._rebuild = function () {
  32584. if (this._vertexArrayObjects) {
  32585. this._vertexArrayObjects = {};
  32586. }
  32587. // Index buffer
  32588. if (this._meshes.length !== 0 && this._indices) {
  32589. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32590. }
  32591. // Vertex buffers
  32592. for (var key in this._vertexBuffers) {
  32593. var vertexBuffer = this._vertexBuffers[key];
  32594. vertexBuffer._rebuild();
  32595. }
  32596. };
  32597. /**
  32598. * Affects all gemetry data in one call
  32599. * @param vertexData defines the geometry data
  32600. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  32601. */
  32602. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32603. vertexData.applyToGeometry(this, updatable);
  32604. this.notifyUpdate();
  32605. };
  32606. /**
  32607. * Set specific vertex data
  32608. * @param kind defines the data kind (Position, normal, etc...)
  32609. * @param data defines the vertex data to use
  32610. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  32611. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  32612. */
  32613. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32614. if (updatable === void 0) { updatable = false; }
  32615. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32616. this.setVerticesBuffer(buffer);
  32617. };
  32618. /**
  32619. * Removes a specific vertex data
  32620. * @param kind defines the data kind (Position, normal, etc...)
  32621. */
  32622. Geometry.prototype.removeVerticesData = function (kind) {
  32623. if (this._vertexBuffers[kind]) {
  32624. this._vertexBuffers[kind].dispose();
  32625. delete this._vertexBuffers[kind];
  32626. }
  32627. };
  32628. /**
  32629. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  32630. * @param buffer defines the vertex buffer to use
  32631. */
  32632. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32633. var kind = buffer.getKind();
  32634. if (this._vertexBuffers[kind]) {
  32635. this._vertexBuffers[kind].dispose();
  32636. }
  32637. this._vertexBuffers[kind] = buffer;
  32638. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32639. var data = buffer.getData();
  32640. var stride = buffer.getStrideSize();
  32641. this._totalVertices = data.length / stride;
  32642. this.updateExtend(data, stride);
  32643. this._resetPointsArrayCache();
  32644. var meshes = this._meshes;
  32645. var numOfMeshes = meshes.length;
  32646. for (var index = 0; index < numOfMeshes; index++) {
  32647. var mesh = meshes[index];
  32648. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32649. mesh._createGlobalSubMesh(false);
  32650. mesh.computeWorldMatrix(true);
  32651. }
  32652. }
  32653. this.notifyUpdate(kind);
  32654. if (this._vertexArrayObjects) {
  32655. this._disposeVertexArrayObjects();
  32656. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  32657. }
  32658. };
  32659. /**
  32660. * Update a specific vertex buffer
  32661. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  32662. * It will do nothing if the buffer is not updatable
  32663. * @param kind defines the data kind (Position, normal, etc...)
  32664. * @param data defines the data to use
  32665. * @param offset defines the offset in the target buffer where to store the data
  32666. */
  32667. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32668. var vertexBuffer = this.getVertexBuffer(kind);
  32669. if (!vertexBuffer) {
  32670. return;
  32671. }
  32672. vertexBuffer.updateDirectly(data, offset);
  32673. this.notifyUpdate(kind);
  32674. };
  32675. /**
  32676. * Update a specific vertex buffer
  32677. * This function will create a new buffer if the current one is not updatable
  32678. * @param kind defines the data kind (Position, normal, etc...)
  32679. * @param data defines the data to use
  32680. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  32681. */
  32682. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32683. if (updateExtends === void 0) { updateExtends = false; }
  32684. var vertexBuffer = this.getVertexBuffer(kind);
  32685. if (!vertexBuffer) {
  32686. return;
  32687. }
  32688. vertexBuffer.update(data);
  32689. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32690. var stride = vertexBuffer.getStrideSize();
  32691. this._totalVertices = data.length / stride;
  32692. this.updateBoundingInfo(updateExtends, data);
  32693. }
  32694. this.notifyUpdate(kind);
  32695. };
  32696. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32697. if (updateExtends) {
  32698. this.updateExtend(data);
  32699. }
  32700. var meshes = this._meshes;
  32701. var numOfMeshes = meshes.length;
  32702. this._resetPointsArrayCache();
  32703. for (var index = 0; index < numOfMeshes; index++) {
  32704. var mesh = meshes[index];
  32705. if (updateExtends) {
  32706. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32707. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32708. var subMesh = mesh.subMeshes[subIndex];
  32709. subMesh.refreshBoundingInfo();
  32710. }
  32711. }
  32712. }
  32713. };
  32714. /** @ignore */
  32715. Geometry.prototype._bind = function (effect, indexToBind) {
  32716. if (!effect) {
  32717. return;
  32718. }
  32719. if (indexToBind === undefined) {
  32720. indexToBind = this._indexBuffer;
  32721. }
  32722. var vbs = this.getVertexBuffers();
  32723. if (!vbs) {
  32724. return;
  32725. }
  32726. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  32727. this._engine.bindBuffers(vbs, indexToBind, effect);
  32728. return;
  32729. }
  32730. // Using VAO
  32731. if (!this._vertexArrayObjects[effect.key]) {
  32732. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  32733. }
  32734. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  32735. };
  32736. /**
  32737. * Gets total number of vertices
  32738. * @returns the total number of vertices
  32739. */
  32740. Geometry.prototype.getTotalVertices = function () {
  32741. if (!this.isReady()) {
  32742. return 0;
  32743. }
  32744. return this._totalVertices;
  32745. };
  32746. /**
  32747. * Gets a specific vertex data attached to this geometry
  32748. * @param kind defines the data kind (Position, normal, etc...)
  32749. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32750. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32751. * @returns a float array containing vertex data
  32752. */
  32753. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32754. var vertexBuffer = this.getVertexBuffer(kind);
  32755. if (!vertexBuffer) {
  32756. return null;
  32757. }
  32758. var orig = vertexBuffer.getData();
  32759. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  32760. return orig;
  32761. }
  32762. else {
  32763. var len = orig.length;
  32764. var copy = [];
  32765. for (var i = 0; i < len; i++) {
  32766. copy.push(orig[i]);
  32767. }
  32768. return copy;
  32769. }
  32770. };
  32771. /**
  32772. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  32773. * @param kind defines the data kind (Position, normal, etc...)
  32774. * @returns true if the vertex buffer with the specified kind is updatable
  32775. */
  32776. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  32777. var vb = this._vertexBuffers[kind];
  32778. if (!vb) {
  32779. return false;
  32780. }
  32781. return vb.isUpdatable();
  32782. };
  32783. /**
  32784. * Gets a specific vertex buffer
  32785. * @param kind defines the data kind (Position, normal, etc...)
  32786. * @returns a {BABYLON.VertexBuffer}
  32787. */
  32788. Geometry.prototype.getVertexBuffer = function (kind) {
  32789. if (!this.isReady()) {
  32790. return null;
  32791. }
  32792. return this._vertexBuffers[kind];
  32793. };
  32794. /**
  32795. * Returns all vertex buffers
  32796. * @return an object holding all vertex buffers indexed by kind
  32797. */
  32798. Geometry.prototype.getVertexBuffers = function () {
  32799. if (!this.isReady()) {
  32800. return null;
  32801. }
  32802. return this._vertexBuffers;
  32803. };
  32804. /**
  32805. * Gets a boolean indicating if specific vertex buffer is present
  32806. * @param kind defines the data kind (Position, normal, etc...)
  32807. * @returns true if data is present
  32808. */
  32809. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32810. if (!this._vertexBuffers) {
  32811. if (this._delayInfo) {
  32812. return this._delayInfo.indexOf(kind) !== -1;
  32813. }
  32814. return false;
  32815. }
  32816. return this._vertexBuffers[kind] !== undefined;
  32817. };
  32818. /**
  32819. * Gets a list of all attached data kinds (Position, normal, etc...)
  32820. * @returns a list of string containing all kinds
  32821. */
  32822. Geometry.prototype.getVerticesDataKinds = function () {
  32823. var result = [];
  32824. var kind;
  32825. if (!this._vertexBuffers && this._delayInfo) {
  32826. for (kind in this._delayInfo) {
  32827. result.push(kind);
  32828. }
  32829. }
  32830. else {
  32831. for (kind in this._vertexBuffers) {
  32832. result.push(kind);
  32833. }
  32834. }
  32835. return result;
  32836. };
  32837. /**
  32838. * Update index buffer
  32839. * @param indices defines the indices to store in the index buffer
  32840. * @param offset defines the offset in the target buffer where to store the data
  32841. */
  32842. Geometry.prototype.updateIndices = function (indices, offset) {
  32843. if (!this._indexBuffer) {
  32844. return;
  32845. }
  32846. if (!this._indexBufferIsUpdatable) {
  32847. this.setIndices(indices, null, true);
  32848. }
  32849. else {
  32850. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  32851. }
  32852. };
  32853. /**
  32854. * Creates a new index buffer
  32855. * @param indices defines the indices to store in the index buffer
  32856. * @param totalVertices defines the total number of vertices (could be null)
  32857. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  32858. */
  32859. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  32860. if (totalVertices === void 0) { totalVertices = null; }
  32861. if (updatable === void 0) { updatable = false; }
  32862. if (this._indexBuffer) {
  32863. this._engine._releaseBuffer(this._indexBuffer);
  32864. }
  32865. this._disposeVertexArrayObjects();
  32866. this._indices = indices;
  32867. this._indexBufferIsUpdatable = updatable;
  32868. if (this._meshes.length !== 0 && this._indices) {
  32869. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  32870. }
  32871. if (totalVertices != undefined) {
  32872. this._totalVertices = totalVertices;
  32873. }
  32874. var meshes = this._meshes;
  32875. var numOfMeshes = meshes.length;
  32876. for (var index = 0; index < numOfMeshes; index++) {
  32877. meshes[index]._createGlobalSubMesh(true);
  32878. }
  32879. this.notifyUpdate();
  32880. };
  32881. /**
  32882. * Return the total number of indices
  32883. * @returns the total number of indices
  32884. */
  32885. Geometry.prototype.getTotalIndices = function () {
  32886. if (!this.isReady()) {
  32887. return 0;
  32888. }
  32889. return this._indices.length;
  32890. };
  32891. /**
  32892. * Gets the index buffer array
  32893. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32894. * @returns the index buffer array
  32895. */
  32896. Geometry.prototype.getIndices = function (copyWhenShared) {
  32897. if (!this.isReady()) {
  32898. return null;
  32899. }
  32900. var orig = this._indices;
  32901. if (!copyWhenShared || this._meshes.length === 1) {
  32902. return orig;
  32903. }
  32904. else {
  32905. var len = orig.length;
  32906. var copy = [];
  32907. for (var i = 0; i < len; i++) {
  32908. copy.push(orig[i]);
  32909. }
  32910. return copy;
  32911. }
  32912. };
  32913. /**
  32914. * Gets the index buffer
  32915. * @return the index buffer
  32916. */
  32917. Geometry.prototype.getIndexBuffer = function () {
  32918. if (!this.isReady()) {
  32919. return null;
  32920. }
  32921. return this._indexBuffer;
  32922. };
  32923. /** @ignore */
  32924. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  32925. if (effect === void 0) { effect = null; }
  32926. if (!effect || !this._vertexArrayObjects) {
  32927. return;
  32928. }
  32929. if (this._vertexArrayObjects[effect.key]) {
  32930. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  32931. delete this._vertexArrayObjects[effect.key];
  32932. }
  32933. };
  32934. /**
  32935. * Release the associated resources for a specific mesh
  32936. * @param mesh defines the source mesh
  32937. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  32938. */
  32939. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  32940. var meshes = this._meshes;
  32941. var index = meshes.indexOf(mesh);
  32942. if (index === -1) {
  32943. return;
  32944. }
  32945. meshes.splice(index, 1);
  32946. mesh._geometry = null;
  32947. if (meshes.length === 0 && shouldDispose) {
  32948. this.dispose();
  32949. }
  32950. };
  32951. /**
  32952. * Apply current geometry to a given mesh
  32953. * @param mesh defines the mesh to apply geometry to
  32954. */
  32955. Geometry.prototype.applyToMesh = function (mesh) {
  32956. if (mesh._geometry === this) {
  32957. return;
  32958. }
  32959. var previousGeometry = mesh._geometry;
  32960. if (previousGeometry) {
  32961. previousGeometry.releaseForMesh(mesh);
  32962. }
  32963. var meshes = this._meshes;
  32964. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  32965. mesh._geometry = this;
  32966. this._scene.pushGeometry(this);
  32967. meshes.push(mesh);
  32968. if (this.isReady()) {
  32969. this._applyToMesh(mesh);
  32970. }
  32971. else {
  32972. mesh._boundingInfo = this._boundingInfo;
  32973. }
  32974. };
  32975. Geometry.prototype.updateExtend = function (data, stride) {
  32976. if (data === void 0) { data = null; }
  32977. if (!data) {
  32978. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  32979. }
  32980. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  32981. };
  32982. Geometry.prototype._applyToMesh = function (mesh) {
  32983. var numOfMeshes = this._meshes.length;
  32984. // vertexBuffers
  32985. for (var kind in this._vertexBuffers) {
  32986. if (numOfMeshes === 1) {
  32987. this._vertexBuffers[kind].create();
  32988. }
  32989. var buffer = this._vertexBuffers[kind].getBuffer();
  32990. if (buffer)
  32991. buffer.references = numOfMeshes;
  32992. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32993. if (!this._extend) {
  32994. this.updateExtend(this._vertexBuffers[kind].getData());
  32995. }
  32996. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32997. mesh._createGlobalSubMesh(false);
  32998. //bounding info was just created again, world matrix should be applied again.
  32999. mesh._updateBoundingInfo();
  33000. }
  33001. }
  33002. // indexBuffer
  33003. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33004. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33005. }
  33006. if (this._indexBuffer) {
  33007. this._indexBuffer.references = numOfMeshes;
  33008. }
  33009. };
  33010. Geometry.prototype.notifyUpdate = function (kind) {
  33011. if (this.onGeometryUpdated) {
  33012. this.onGeometryUpdated(this, kind);
  33013. }
  33014. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  33015. var mesh = _a[_i];
  33016. mesh._markSubMeshesAsAttributesDirty();
  33017. }
  33018. };
  33019. /**
  33020. * Load the geometry if it was flagged as delay loaded
  33021. * @param scene defines the hosting scene
  33022. * @param onLoaded defines a callback called when the geometry is loaded
  33023. */
  33024. Geometry.prototype.load = function (scene, onLoaded) {
  33025. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33026. return;
  33027. }
  33028. if (this.isReady()) {
  33029. if (onLoaded) {
  33030. onLoaded();
  33031. }
  33032. return;
  33033. }
  33034. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33035. this._queueLoad(scene, onLoaded);
  33036. };
  33037. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33038. var _this = this;
  33039. if (!this.delayLoadingFile) {
  33040. return;
  33041. }
  33042. scene._addPendingData(this);
  33043. scene._loadFile(this.delayLoadingFile, function (data) {
  33044. if (!_this._delayLoadingFunction) {
  33045. return;
  33046. }
  33047. _this._delayLoadingFunction(JSON.parse(data), _this);
  33048. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33049. _this._delayInfo = [];
  33050. scene._removePendingData(_this);
  33051. var meshes = _this._meshes;
  33052. var numOfMeshes = meshes.length;
  33053. for (var index = 0; index < numOfMeshes; index++) {
  33054. _this._applyToMesh(meshes[index]);
  33055. }
  33056. if (onLoaded) {
  33057. onLoaded();
  33058. }
  33059. }, undefined, true);
  33060. };
  33061. /**
  33062. * Invert the geometry to move from a right handed system to a left handed one.
  33063. */
  33064. Geometry.prototype.toLeftHanded = function () {
  33065. // Flip faces
  33066. var tIndices = this.getIndices(false);
  33067. if (tIndices != null && tIndices.length > 0) {
  33068. for (var i = 0; i < tIndices.length; i += 3) {
  33069. var tTemp = tIndices[i + 0];
  33070. tIndices[i + 0] = tIndices[i + 2];
  33071. tIndices[i + 2] = tTemp;
  33072. }
  33073. this.setIndices(tIndices);
  33074. }
  33075. // Negate position.z
  33076. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33077. if (tPositions != null && tPositions.length > 0) {
  33078. for (var i = 0; i < tPositions.length; i += 3) {
  33079. tPositions[i + 2] = -tPositions[i + 2];
  33080. }
  33081. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33082. }
  33083. // Negate normal.z
  33084. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33085. if (tNormals != null && tNormals.length > 0) {
  33086. for (var i = 0; i < tNormals.length; i += 3) {
  33087. tNormals[i + 2] = -tNormals[i + 2];
  33088. }
  33089. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33090. }
  33091. };
  33092. // Cache
  33093. /** @ignore */
  33094. Geometry.prototype._resetPointsArrayCache = function () {
  33095. this._positions = null;
  33096. };
  33097. /** @ignore */
  33098. Geometry.prototype._generatePointsArray = function () {
  33099. if (this._positions)
  33100. return true;
  33101. this._positions = [];
  33102. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33103. if (!data) {
  33104. return false;
  33105. }
  33106. for (var index = 0; index < data.length; index += 3) {
  33107. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  33108. }
  33109. return true;
  33110. };
  33111. /**
  33112. * Gets a value indicating if the geometry is disposed
  33113. * @returns true if the geometry was disposed
  33114. */
  33115. Geometry.prototype.isDisposed = function () {
  33116. return this._isDisposed;
  33117. };
  33118. Geometry.prototype._disposeVertexArrayObjects = function () {
  33119. if (this._vertexArrayObjects) {
  33120. for (var kind in this._vertexArrayObjects) {
  33121. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  33122. }
  33123. this._vertexArrayObjects = {};
  33124. }
  33125. };
  33126. /**
  33127. * Free all associated resources
  33128. */
  33129. Geometry.prototype.dispose = function () {
  33130. var meshes = this._meshes;
  33131. var numOfMeshes = meshes.length;
  33132. var index;
  33133. for (index = 0; index < numOfMeshes; index++) {
  33134. this.releaseForMesh(meshes[index]);
  33135. }
  33136. this._meshes = [];
  33137. this._disposeVertexArrayObjects();
  33138. for (var kind in this._vertexBuffers) {
  33139. this._vertexBuffers[kind].dispose();
  33140. }
  33141. this._vertexBuffers = {};
  33142. this._totalVertices = 0;
  33143. if (this._indexBuffer) {
  33144. this._engine._releaseBuffer(this._indexBuffer);
  33145. }
  33146. this._indexBuffer = null;
  33147. this._indices = [];
  33148. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33149. this.delayLoadingFile = null;
  33150. this._delayLoadingFunction = null;
  33151. this._delayInfo = [];
  33152. this._boundingInfo = null;
  33153. this._scene.removeGeometry(this);
  33154. this._isDisposed = true;
  33155. };
  33156. /**
  33157. * Clone the current geometry into a new geometry
  33158. * @param id defines the unique ID of the new geometry
  33159. * @returns a new geometry object
  33160. */
  33161. Geometry.prototype.copy = function (id) {
  33162. var vertexData = new BABYLON.VertexData();
  33163. vertexData.indices = [];
  33164. var indices = this.getIndices();
  33165. if (indices) {
  33166. for (var index = 0; index < indices.length; index++) {
  33167. vertexData.indices.push(indices[index]);
  33168. }
  33169. }
  33170. var updatable = false;
  33171. var stopChecking = false;
  33172. var kind;
  33173. for (kind in this._vertexBuffers) {
  33174. // using slice() to make a copy of the array and not just reference it
  33175. var data = this.getVerticesData(kind);
  33176. if (data instanceof Float32Array) {
  33177. vertexData.set(new Float32Array(data), kind);
  33178. }
  33179. else {
  33180. vertexData.set(data.slice(0), kind);
  33181. }
  33182. if (!stopChecking) {
  33183. var vb = this.getVertexBuffer(kind);
  33184. if (vb) {
  33185. updatable = vb.isUpdatable();
  33186. stopChecking = !updatable;
  33187. }
  33188. }
  33189. }
  33190. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  33191. geometry.delayLoadState = this.delayLoadState;
  33192. geometry.delayLoadingFile = this.delayLoadingFile;
  33193. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33194. for (kind in this._delayInfo) {
  33195. geometry._delayInfo = geometry._delayInfo || [];
  33196. geometry._delayInfo.push(kind);
  33197. }
  33198. // Bounding info
  33199. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33200. return geometry;
  33201. };
  33202. /**
  33203. * Serialize the current geometry info (and not the vertices data) into a JSON object
  33204. * @return a JSON representation of the current geometry data (without the vertices data)
  33205. */
  33206. Geometry.prototype.serialize = function () {
  33207. var serializationObject = {};
  33208. serializationObject.id = this.id;
  33209. serializationObject.updatable = this._updatable;
  33210. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33211. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33212. }
  33213. return serializationObject;
  33214. };
  33215. Geometry.prototype.toNumberArray = function (origin) {
  33216. if (Array.isArray(origin)) {
  33217. return origin;
  33218. }
  33219. else {
  33220. return Array.prototype.slice.call(origin);
  33221. }
  33222. };
  33223. /**
  33224. * Serialize all vertices data into a JSON oject
  33225. * @returns a JSON representation of the current geometry data
  33226. */
  33227. Geometry.prototype.serializeVerticeData = function () {
  33228. var serializationObject = this.serialize();
  33229. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33230. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  33231. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33232. serializationObject.positions._updatable = true;
  33233. }
  33234. }
  33235. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33236. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  33237. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33238. serializationObject.normals._updatable = true;
  33239. }
  33240. }
  33241. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33242. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  33243. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  33244. serializationObject.tangets._updatable = true;
  33245. }
  33246. }
  33247. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33248. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  33249. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  33250. serializationObject.uvs._updatable = true;
  33251. }
  33252. }
  33253. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33254. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  33255. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  33256. serializationObject.uv2s._updatable = true;
  33257. }
  33258. }
  33259. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33260. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  33261. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  33262. serializationObject.uv3s._updatable = true;
  33263. }
  33264. }
  33265. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33266. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  33267. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  33268. serializationObject.uv4s._updatable = true;
  33269. }
  33270. }
  33271. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33272. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  33273. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  33274. serializationObject.uv5s._updatable = true;
  33275. }
  33276. }
  33277. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33278. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  33279. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  33280. serializationObject.uv6s._updatable = true;
  33281. }
  33282. }
  33283. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33284. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  33285. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  33286. serializationObject.colors._updatable = true;
  33287. }
  33288. }
  33289. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33290. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  33291. serializationObject.matricesIndices._isExpanded = true;
  33292. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33293. serializationObject.matricesIndices._updatable = true;
  33294. }
  33295. }
  33296. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33297. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  33298. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33299. serializationObject.matricesWeights._updatable = true;
  33300. }
  33301. }
  33302. serializationObject.indices = this.toNumberArray(this.getIndices());
  33303. return serializationObject;
  33304. };
  33305. // Statics
  33306. /**
  33307. * Extracts a clone of a mesh geometry
  33308. * @param mesh defines the source mesh
  33309. * @param id defines the unique ID of the new geometry object
  33310. * @returns the new geometry object
  33311. */
  33312. Geometry.ExtractFromMesh = function (mesh, id) {
  33313. var geometry = mesh._geometry;
  33314. if (!geometry) {
  33315. return null;
  33316. }
  33317. return geometry.copy(id);
  33318. };
  33319. /**
  33320. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  33321. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33322. * Be aware Math.random() could cause collisions, but:
  33323. * "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"
  33324. * @returns a string containing a new GUID
  33325. */
  33326. Geometry.RandomId = function () {
  33327. return BABYLON.Tools.RandomId();
  33328. };
  33329. /** @ignore */
  33330. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  33331. var scene = mesh.getScene();
  33332. // Geometry
  33333. var geometryId = parsedGeometry.geometryId;
  33334. if (geometryId) {
  33335. var geometry = scene.getGeometryByID(geometryId);
  33336. if (geometry) {
  33337. geometry.applyToMesh(mesh);
  33338. }
  33339. }
  33340. else if (parsedGeometry instanceof ArrayBuffer) {
  33341. var binaryInfo = mesh._binaryInfo;
  33342. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33343. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33344. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33345. }
  33346. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33347. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33348. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33349. }
  33350. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  33351. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  33352. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  33353. }
  33354. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33355. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33356. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33357. }
  33358. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33359. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33360. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33361. }
  33362. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33363. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33364. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33365. }
  33366. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33367. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33368. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33369. }
  33370. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33371. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33372. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33373. }
  33374. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33375. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33376. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33377. }
  33378. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33379. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33380. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33381. }
  33382. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33383. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33384. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33385. }
  33386. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33387. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33388. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33389. }
  33390. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33391. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33392. mesh.setIndices(indicesData, null);
  33393. }
  33394. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33395. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33396. mesh.subMeshes = [];
  33397. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33398. var materialIndex = subMeshesData[(i * 5) + 0];
  33399. var verticesStart = subMeshesData[(i * 5) + 1];
  33400. var verticesCount = subMeshesData[(i * 5) + 2];
  33401. var indexStart = subMeshesData[(i * 5) + 3];
  33402. var indexCount = subMeshesData[(i * 5) + 4];
  33403. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33404. }
  33405. }
  33406. }
  33407. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33408. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  33409. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  33410. if (parsedGeometry.tangents) {
  33411. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  33412. }
  33413. if (parsedGeometry.uvs) {
  33414. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  33415. }
  33416. if (parsedGeometry.uvs2) {
  33417. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  33418. }
  33419. if (parsedGeometry.uvs3) {
  33420. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  33421. }
  33422. if (parsedGeometry.uvs4) {
  33423. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  33424. }
  33425. if (parsedGeometry.uvs5) {
  33426. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  33427. }
  33428. if (parsedGeometry.uvs6) {
  33429. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  33430. }
  33431. if (parsedGeometry.colors) {
  33432. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  33433. }
  33434. if (parsedGeometry.matricesIndices) {
  33435. if (!parsedGeometry.matricesIndices._isExpanded) {
  33436. var floatIndices = [];
  33437. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33438. var matricesIndex = parsedGeometry.matricesIndices[i];
  33439. floatIndices.push(matricesIndex & 0x000000FF);
  33440. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33441. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33442. floatIndices.push(matricesIndex >> 24);
  33443. }
  33444. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  33445. }
  33446. else {
  33447. delete parsedGeometry.matricesIndices._isExpanded;
  33448. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  33449. }
  33450. }
  33451. if (parsedGeometry.matricesIndicesExtra) {
  33452. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33453. var floatIndices = [];
  33454. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33455. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33456. floatIndices.push(matricesIndex & 0x000000FF);
  33457. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33458. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33459. floatIndices.push(matricesIndex >> 24);
  33460. }
  33461. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  33462. }
  33463. else {
  33464. delete parsedGeometry.matricesIndices._isExpanded;
  33465. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  33466. }
  33467. }
  33468. if (parsedGeometry.matricesWeights) {
  33469. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  33470. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  33471. }
  33472. if (parsedGeometry.matricesWeightsExtra) {
  33473. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  33474. }
  33475. mesh.setIndices(parsedGeometry.indices, null);
  33476. }
  33477. // SubMeshes
  33478. if (parsedGeometry.subMeshes) {
  33479. mesh.subMeshes = [];
  33480. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33481. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33482. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33483. }
  33484. }
  33485. // Flat shading
  33486. if (mesh._shouldGenerateFlatShading) {
  33487. mesh.convertToFlatShadedMesh();
  33488. delete mesh._shouldGenerateFlatShading;
  33489. }
  33490. // Update
  33491. mesh.computeWorldMatrix(true);
  33492. // Octree
  33493. var sceneOctree = scene.selectionOctree;
  33494. if (sceneOctree !== undefined && sceneOctree !== null) {
  33495. sceneOctree.addMesh(mesh);
  33496. }
  33497. };
  33498. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  33499. var epsilon = 1e-3;
  33500. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  33501. return;
  33502. }
  33503. var noInfluenceBoneIndex = 0.0;
  33504. if (parsedGeometry.skeletonId > -1) {
  33505. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  33506. if (!skeleton) {
  33507. return;
  33508. }
  33509. noInfluenceBoneIndex = skeleton.bones.length;
  33510. }
  33511. else {
  33512. return;
  33513. }
  33514. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33515. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33516. var matricesWeights = parsedGeometry.matricesWeights;
  33517. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  33518. var influencers = parsedGeometry.numBoneInfluencer;
  33519. var size = matricesWeights.length;
  33520. for (var i = 0; i < size; i += 4) {
  33521. var weight = 0.0;
  33522. var firstZeroWeight = -1;
  33523. for (var j = 0; j < 4; j++) {
  33524. var w = matricesWeights[i + j];
  33525. weight += w;
  33526. if (w < epsilon && firstZeroWeight < 0) {
  33527. firstZeroWeight = j;
  33528. }
  33529. }
  33530. if (matricesWeightsExtra) {
  33531. for (var j = 0; j < 4; j++) {
  33532. var w = matricesWeightsExtra[i + j];
  33533. weight += w;
  33534. if (w < epsilon && firstZeroWeight < 0) {
  33535. firstZeroWeight = j + 4;
  33536. }
  33537. }
  33538. }
  33539. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33540. firstZeroWeight = influencers - 1;
  33541. }
  33542. if (weight > epsilon) {
  33543. var mweight = 1.0 / weight;
  33544. for (var j = 0; j < 4; j++) {
  33545. matricesWeights[i + j] *= mweight;
  33546. }
  33547. if (matricesWeightsExtra) {
  33548. for (var j = 0; j < 4; j++) {
  33549. matricesWeightsExtra[i + j] *= mweight;
  33550. }
  33551. }
  33552. }
  33553. else {
  33554. if (firstZeroWeight >= 4) {
  33555. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33556. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33557. }
  33558. else {
  33559. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33560. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33561. }
  33562. }
  33563. }
  33564. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33565. if (parsedGeometry.matricesWeightsExtra) {
  33566. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33567. }
  33568. };
  33569. /**
  33570. * Create a new geometry from persisted data (Using .babylon file format)
  33571. * @param parsedVertexData defines the persisted data
  33572. * @param scene defines the hosting scene
  33573. * @param rootUrl defines the root url to use to load assets (like delayed data)
  33574. * @returns the new geometry object
  33575. */
  33576. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33577. if (scene.getGeometryByID(parsedVertexData.id)) {
  33578. return null; // null since geometry could be something else than a box...
  33579. }
  33580. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  33581. if (BABYLON.Tags) {
  33582. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33583. }
  33584. if (parsedVertexData.delayLoadingFile) {
  33585. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33586. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33587. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33588. geometry._delayInfo = [];
  33589. if (parsedVertexData.hasUVs) {
  33590. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33591. }
  33592. if (parsedVertexData.hasUVs2) {
  33593. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33594. }
  33595. if (parsedVertexData.hasUVs3) {
  33596. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33597. }
  33598. if (parsedVertexData.hasUVs4) {
  33599. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33600. }
  33601. if (parsedVertexData.hasUVs5) {
  33602. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33603. }
  33604. if (parsedVertexData.hasUVs6) {
  33605. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33606. }
  33607. if (parsedVertexData.hasColors) {
  33608. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33609. }
  33610. if (parsedVertexData.hasMatricesIndices) {
  33611. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33612. }
  33613. if (parsedVertexData.hasMatricesWeights) {
  33614. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33615. }
  33616. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33617. }
  33618. else {
  33619. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33620. }
  33621. scene.pushGeometry(geometry, true);
  33622. return geometry;
  33623. };
  33624. return Geometry;
  33625. }());
  33626. BABYLON.Geometry = Geometry;
  33627. // Primitives
  33628. /// Abstract class
  33629. /**
  33630. * Abstract class used to provide common services for all typed geometries
  33631. */
  33632. var _PrimitiveGeometry = /** @class */ (function (_super) {
  33633. __extends(_PrimitiveGeometry, _super);
  33634. /**
  33635. * Creates a new typed geometry
  33636. * @param id defines the unique ID of the geometry
  33637. * @param scene defines the hosting scene
  33638. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33639. * @param mesh defines the hosting mesh (can be null)
  33640. */
  33641. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  33642. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  33643. if (mesh === void 0) { mesh = null; }
  33644. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  33645. _this._canBeRegenerated = _canBeRegenerated;
  33646. _this._beingRegenerated = true;
  33647. _this.regenerate();
  33648. _this._beingRegenerated = false;
  33649. return _this;
  33650. }
  33651. /**
  33652. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  33653. * @returns true if the geometry can be regenerated
  33654. */
  33655. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  33656. return this._canBeRegenerated;
  33657. };
  33658. /**
  33659. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  33660. */
  33661. _PrimitiveGeometry.prototype.regenerate = function () {
  33662. if (!this._canBeRegenerated) {
  33663. return;
  33664. }
  33665. this._beingRegenerated = true;
  33666. this.setAllVerticesData(this._regenerateVertexData(), false);
  33667. this._beingRegenerated = false;
  33668. };
  33669. /**
  33670. * Clone the geometry
  33671. * @param id defines the unique ID of the new geometry
  33672. * @returns the new geometry
  33673. */
  33674. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  33675. return _super.prototype.copy.call(this, id);
  33676. };
  33677. // overrides
  33678. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33679. if (!this._beingRegenerated) {
  33680. return;
  33681. }
  33682. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33683. };
  33684. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  33685. if (!this._beingRegenerated) {
  33686. return;
  33687. }
  33688. _super.prototype.setVerticesData.call(this, kind, data, false);
  33689. };
  33690. // to override
  33691. /** @ignore */
  33692. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  33693. throw new Error("Abstract method");
  33694. };
  33695. _PrimitiveGeometry.prototype.copy = function (id) {
  33696. throw new Error("Must be overriden in sub-classes.");
  33697. };
  33698. _PrimitiveGeometry.prototype.serialize = function () {
  33699. var serializationObject = _super.prototype.serialize.call(this);
  33700. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33701. return serializationObject;
  33702. };
  33703. return _PrimitiveGeometry;
  33704. }(Geometry));
  33705. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  33706. /**
  33707. * Creates a ribbon geometry
  33708. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  33709. */
  33710. var RibbonGeometry = /** @class */ (function (_super) {
  33711. __extends(RibbonGeometry, _super);
  33712. /**
  33713. * Creates a ribbon geometry
  33714. * @param id defines the unique ID of the geometry
  33715. * @param scene defines the hosting scene
  33716. * @param pathArray defines the array of paths to use
  33717. * @param closeArray defines if the last path and the first path must be joined
  33718. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  33719. * @param offset defines the offset between points
  33720. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33721. * @param mesh defines the hosting mesh (can be null)
  33722. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33723. */
  33724. function RibbonGeometry(id, scene,
  33725. /**
  33726. * Defines the array of paths to use
  33727. */
  33728. pathArray,
  33729. /**
  33730. * Defines if the last and first points of each path in your pathArray must be joined
  33731. */
  33732. closeArray,
  33733. /**
  33734. * Defines if the last and first points of each path in your pathArray must be joined
  33735. */
  33736. closePath,
  33737. /**
  33738. * Defines the offset between points
  33739. */
  33740. offset, canBeRegenerated, mesh,
  33741. /**
  33742. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33743. */
  33744. side) {
  33745. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33746. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33747. _this.pathArray = pathArray;
  33748. _this.closeArray = closeArray;
  33749. _this.closePath = closePath;
  33750. _this.offset = offset;
  33751. _this.side = side;
  33752. return _this;
  33753. }
  33754. /** @ignore */
  33755. RibbonGeometry.prototype._regenerateVertexData = function () {
  33756. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33757. };
  33758. RibbonGeometry.prototype.copy = function (id) {
  33759. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  33760. };
  33761. return RibbonGeometry;
  33762. }(_PrimitiveGeometry));
  33763. BABYLON.RibbonGeometry = RibbonGeometry;
  33764. /**
  33765. * Creates a box geometry
  33766. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  33767. */
  33768. var BoxGeometry = /** @class */ (function (_super) {
  33769. __extends(BoxGeometry, _super);
  33770. /**
  33771. * Creates a box geometry
  33772. * @param id defines the unique ID of the geometry
  33773. * @param scene defines the hosting scene
  33774. * @param size defines the zise of the box (width, height and depth are the same)
  33775. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33776. * @param mesh defines the hosting mesh (can be null)
  33777. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33778. */
  33779. function BoxGeometry(id, scene,
  33780. /**
  33781. * Defines the zise of the box (width, height and depth are the same)
  33782. */
  33783. size, canBeRegenerated, mesh,
  33784. /**
  33785. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33786. */
  33787. side) {
  33788. if (mesh === void 0) { mesh = null; }
  33789. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33790. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33791. _this.size = size;
  33792. _this.side = side;
  33793. return _this;
  33794. }
  33795. BoxGeometry.prototype._regenerateVertexData = function () {
  33796. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33797. };
  33798. BoxGeometry.prototype.copy = function (id) {
  33799. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  33800. };
  33801. BoxGeometry.prototype.serialize = function () {
  33802. var serializationObject = _super.prototype.serialize.call(this);
  33803. serializationObject.size = this.size;
  33804. return serializationObject;
  33805. };
  33806. BoxGeometry.Parse = function (parsedBox, scene) {
  33807. if (scene.getGeometryByID(parsedBox.id)) {
  33808. return null; // null since geometry could be something else than a box...
  33809. }
  33810. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33811. if (BABYLON.Tags) {
  33812. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33813. }
  33814. scene.pushGeometry(box, true);
  33815. return box;
  33816. };
  33817. return BoxGeometry;
  33818. }(_PrimitiveGeometry));
  33819. BABYLON.BoxGeometry = BoxGeometry;
  33820. /**
  33821. * Creates a sphere geometry
  33822. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  33823. */
  33824. var SphereGeometry = /** @class */ (function (_super) {
  33825. __extends(SphereGeometry, _super);
  33826. /**
  33827. * Create a new sphere geometry
  33828. * @param id defines the unique ID of the geometry
  33829. * @param scene defines the hosting scene
  33830. * @param segments defines the number of segments to use to create the sphere
  33831. * @param diameter defines the diameter of the sphere
  33832. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33833. * @param mesh defines the hosting mesh (can be null)
  33834. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33835. */
  33836. function SphereGeometry(id, scene,
  33837. /**
  33838. * Defines the number of segments to use to create the sphere
  33839. */
  33840. segments,
  33841. /**
  33842. * Defines the diameter of the sphere
  33843. */
  33844. diameter, canBeRegenerated, mesh,
  33845. /**
  33846. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33847. */
  33848. side) {
  33849. if (mesh === void 0) { mesh = null; }
  33850. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33851. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33852. _this.segments = segments;
  33853. _this.diameter = diameter;
  33854. _this.side = side;
  33855. return _this;
  33856. }
  33857. SphereGeometry.prototype._regenerateVertexData = function () {
  33858. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33859. };
  33860. SphereGeometry.prototype.copy = function (id) {
  33861. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33862. };
  33863. SphereGeometry.prototype.serialize = function () {
  33864. var serializationObject = _super.prototype.serialize.call(this);
  33865. serializationObject.segments = this.segments;
  33866. serializationObject.diameter = this.diameter;
  33867. return serializationObject;
  33868. };
  33869. SphereGeometry.Parse = function (parsedSphere, scene) {
  33870. if (scene.getGeometryByID(parsedSphere.id)) {
  33871. return null; // null since geometry could be something else than a sphere...
  33872. }
  33873. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33874. if (BABYLON.Tags) {
  33875. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33876. }
  33877. scene.pushGeometry(sphere, true);
  33878. return sphere;
  33879. };
  33880. return SphereGeometry;
  33881. }(_PrimitiveGeometry));
  33882. BABYLON.SphereGeometry = SphereGeometry;
  33883. /**
  33884. * Creates a disc geometry
  33885. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  33886. */
  33887. var DiscGeometry = /** @class */ (function (_super) {
  33888. __extends(DiscGeometry, _super);
  33889. /**
  33890. * Creates a new disc geometry
  33891. * @param id defines the unique ID of the geometry
  33892. * @param scene defines the hosting scene
  33893. * @param radius defines the radius of the disc
  33894. * @param tessellation defines the tesselation factor to apply to the disc
  33895. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33896. * @param mesh defines the hosting mesh (can be null)
  33897. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33898. */
  33899. function DiscGeometry(id, scene,
  33900. /**
  33901. * Defines the radius of the disc
  33902. */
  33903. radius,
  33904. /**
  33905. * Defines the tesselation factor to apply to the disc
  33906. */
  33907. tessellation, canBeRegenerated, mesh,
  33908. /**
  33909. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33910. */
  33911. side) {
  33912. if (mesh === void 0) { mesh = null; }
  33913. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33914. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33915. _this.radius = radius;
  33916. _this.tessellation = tessellation;
  33917. _this.side = side;
  33918. return _this;
  33919. }
  33920. DiscGeometry.prototype._regenerateVertexData = function () {
  33921. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33922. };
  33923. DiscGeometry.prototype.copy = function (id) {
  33924. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33925. };
  33926. return DiscGeometry;
  33927. }(_PrimitiveGeometry));
  33928. BABYLON.DiscGeometry = DiscGeometry;
  33929. /**
  33930. * Creates a new cylinder geometry
  33931. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  33932. */
  33933. var CylinderGeometry = /** @class */ (function (_super) {
  33934. __extends(CylinderGeometry, _super);
  33935. /**
  33936. * Creates a new cylinder geometry
  33937. * @param id defines the unique ID of the geometry
  33938. * @param scene defines the hosting scene
  33939. * @param height defines the height of the cylinder
  33940. * @param diameterTop defines the diameter of the cylinder's top cap
  33941. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  33942. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  33943. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  33944. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33945. * @param mesh defines the hosting mesh (can be null)
  33946. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33947. */
  33948. function CylinderGeometry(id, scene,
  33949. /**
  33950. * Defines the height of the cylinder
  33951. */
  33952. height,
  33953. /**
  33954. * Defines the diameter of the cylinder's top cap
  33955. */
  33956. diameterTop,
  33957. /**
  33958. * Defines the diameter of the cylinder's bottom cap
  33959. */
  33960. diameterBottom,
  33961. /**
  33962. * Defines the tessellation factor to apply to the cylinder
  33963. */
  33964. tessellation,
  33965. /**
  33966. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  33967. */
  33968. subdivisions, canBeRegenerated, mesh,
  33969. /**
  33970. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33971. */
  33972. side) {
  33973. if (subdivisions === void 0) { subdivisions = 1; }
  33974. if (mesh === void 0) { mesh = null; }
  33975. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33976. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33977. _this.height = height;
  33978. _this.diameterTop = diameterTop;
  33979. _this.diameterBottom = diameterBottom;
  33980. _this.tessellation = tessellation;
  33981. _this.subdivisions = subdivisions;
  33982. _this.side = side;
  33983. return _this;
  33984. }
  33985. CylinderGeometry.prototype._regenerateVertexData = function () {
  33986. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33987. };
  33988. CylinderGeometry.prototype.copy = function (id) {
  33989. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33990. };
  33991. CylinderGeometry.prototype.serialize = function () {
  33992. var serializationObject = _super.prototype.serialize.call(this);
  33993. serializationObject.height = this.height;
  33994. serializationObject.diameterTop = this.diameterTop;
  33995. serializationObject.diameterBottom = this.diameterBottom;
  33996. serializationObject.tessellation = this.tessellation;
  33997. return serializationObject;
  33998. };
  33999. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  34000. if (scene.getGeometryByID(parsedCylinder.id)) {
  34001. return null; // null since geometry could be something else than a cylinder...
  34002. }
  34003. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34004. if (BABYLON.Tags) {
  34005. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34006. }
  34007. scene.pushGeometry(cylinder, true);
  34008. return cylinder;
  34009. };
  34010. return CylinderGeometry;
  34011. }(_PrimitiveGeometry));
  34012. BABYLON.CylinderGeometry = CylinderGeometry;
  34013. /**
  34014. * Creates a new torus geometry
  34015. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  34016. */
  34017. var TorusGeometry = /** @class */ (function (_super) {
  34018. __extends(TorusGeometry, _super);
  34019. /**
  34020. * Creates a new torus geometry
  34021. * @param id defines the unique ID of the geometry
  34022. * @param scene defines the hosting scene
  34023. * @param diameter defines the diameter of the torus
  34024. * @param thickness defines the thickness of the torus (ie. internal diameter)
  34025. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  34026. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34027. * @param mesh defines the hosting mesh (can be null)
  34028. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34029. */
  34030. function TorusGeometry(id, scene,
  34031. /**
  34032. * Defines the diameter of the torus
  34033. */
  34034. diameter,
  34035. /**
  34036. * Defines the thickness of the torus (ie. internal diameter)
  34037. */
  34038. thickness,
  34039. /**
  34040. * Defines the tesselation factor to apply to the torus
  34041. */
  34042. tessellation, canBeRegenerated, mesh,
  34043. /**
  34044. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34045. */
  34046. side) {
  34047. if (mesh === void 0) { mesh = null; }
  34048. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34049. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34050. _this.diameter = diameter;
  34051. _this.thickness = thickness;
  34052. _this.tessellation = tessellation;
  34053. _this.side = side;
  34054. return _this;
  34055. }
  34056. TorusGeometry.prototype._regenerateVertexData = function () {
  34057. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34058. };
  34059. TorusGeometry.prototype.copy = function (id) {
  34060. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34061. };
  34062. TorusGeometry.prototype.serialize = function () {
  34063. var serializationObject = _super.prototype.serialize.call(this);
  34064. serializationObject.diameter = this.diameter;
  34065. serializationObject.thickness = this.thickness;
  34066. serializationObject.tessellation = this.tessellation;
  34067. return serializationObject;
  34068. };
  34069. TorusGeometry.Parse = function (parsedTorus, scene) {
  34070. if (scene.getGeometryByID(parsedTorus.id)) {
  34071. return null; // null since geometry could be something else than a torus...
  34072. }
  34073. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34074. if (BABYLON.Tags) {
  34075. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34076. }
  34077. scene.pushGeometry(torus, true);
  34078. return torus;
  34079. };
  34080. return TorusGeometry;
  34081. }(_PrimitiveGeometry));
  34082. BABYLON.TorusGeometry = TorusGeometry;
  34083. /**
  34084. * Creates a new ground geometry
  34085. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  34086. */
  34087. var GroundGeometry = /** @class */ (function (_super) {
  34088. __extends(GroundGeometry, _super);
  34089. /**
  34090. * Creates a new ground geometry
  34091. * @param id defines the unique ID of the geometry
  34092. * @param scene defines the hosting scene
  34093. * @param width defines the width of the ground
  34094. * @param height defines the height of the ground
  34095. * @param subdivisions defines the subdivisions to apply to the ground
  34096. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34097. * @param mesh defines the hosting mesh (can be null)
  34098. */
  34099. function GroundGeometry(id, scene,
  34100. /**
  34101. * Defines the width of the ground
  34102. */
  34103. width,
  34104. /**
  34105. * Defines the height of the ground
  34106. */
  34107. height,
  34108. /**
  34109. * Defines the subdivisions to apply to the ground
  34110. */
  34111. subdivisions, canBeRegenerated, mesh) {
  34112. if (mesh === void 0) { mesh = null; }
  34113. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34114. _this.width = width;
  34115. _this.height = height;
  34116. _this.subdivisions = subdivisions;
  34117. return _this;
  34118. }
  34119. GroundGeometry.prototype._regenerateVertexData = function () {
  34120. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34121. };
  34122. GroundGeometry.prototype.copy = function (id) {
  34123. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34124. };
  34125. GroundGeometry.prototype.serialize = function () {
  34126. var serializationObject = _super.prototype.serialize.call(this);
  34127. serializationObject.width = this.width;
  34128. serializationObject.height = this.height;
  34129. serializationObject.subdivisions = this.subdivisions;
  34130. return serializationObject;
  34131. };
  34132. GroundGeometry.Parse = function (parsedGround, scene) {
  34133. if (scene.getGeometryByID(parsedGround.id)) {
  34134. return null; // null since geometry could be something else than a ground...
  34135. }
  34136. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34137. if (BABYLON.Tags) {
  34138. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34139. }
  34140. scene.pushGeometry(ground, true);
  34141. return ground;
  34142. };
  34143. return GroundGeometry;
  34144. }(_PrimitiveGeometry));
  34145. BABYLON.GroundGeometry = GroundGeometry;
  34146. /**
  34147. * Creates a tiled ground geometry
  34148. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  34149. */
  34150. var TiledGroundGeometry = /** @class */ (function (_super) {
  34151. __extends(TiledGroundGeometry, _super);
  34152. /**
  34153. * Creates a tiled ground geometry
  34154. * @param id defines the unique ID of the geometry
  34155. * @param scene defines the hosting scene
  34156. * @param xmin defines the minimum value on X axis
  34157. * @param zmin defines the minimum value on Z axis
  34158. * @param xmax defines the maximum value on X axis
  34159. * @param zmax defines the maximum value on Z axis
  34160. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  34161. * @param precision defines the precision to use when computing the tiles
  34162. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34163. * @param mesh defines the hosting mesh (can be null)
  34164. */
  34165. function TiledGroundGeometry(id, scene,
  34166. /**
  34167. * Defines the minimum value on X axis
  34168. */
  34169. xmin,
  34170. /**
  34171. * Defines the minimum value on Z axis
  34172. */
  34173. zmin,
  34174. /**
  34175. * Defines the maximum value on X axis
  34176. */
  34177. xmax,
  34178. /**
  34179. * Defines the maximum value on Z axis
  34180. */
  34181. zmax,
  34182. /**
  34183. * Defines the subdivisions to apply to the ground
  34184. */
  34185. subdivisions,
  34186. /**
  34187. * Defines the precision to use when computing the tiles
  34188. */
  34189. precision, canBeRegenerated, mesh) {
  34190. if (mesh === void 0) { mesh = null; }
  34191. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34192. _this.xmin = xmin;
  34193. _this.zmin = zmin;
  34194. _this.xmax = xmax;
  34195. _this.zmax = zmax;
  34196. _this.subdivisions = subdivisions;
  34197. _this.precision = precision;
  34198. return _this;
  34199. }
  34200. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  34201. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34202. };
  34203. TiledGroundGeometry.prototype.copy = function (id) {
  34204. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34205. };
  34206. return TiledGroundGeometry;
  34207. }(_PrimitiveGeometry));
  34208. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  34209. /**
  34210. * Creates a plane geometry
  34211. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  34212. */
  34213. var PlaneGeometry = /** @class */ (function (_super) {
  34214. __extends(PlaneGeometry, _super);
  34215. /**
  34216. * Creates a plane geometry
  34217. * @param id defines the unique ID of the geometry
  34218. * @param scene defines the hosting scene
  34219. * @param size defines the size of the plane (width === height)
  34220. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34221. * @param mesh defines the hosting mesh (can be null)
  34222. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34223. */
  34224. function PlaneGeometry(id, scene,
  34225. /**
  34226. * Defines the size of the plane (width === height)
  34227. */
  34228. size, canBeRegenerated, mesh,
  34229. /**
  34230. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34231. */
  34232. side) {
  34233. if (mesh === void 0) { mesh = null; }
  34234. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34235. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34236. _this.size = size;
  34237. _this.side = side;
  34238. return _this;
  34239. }
  34240. PlaneGeometry.prototype._regenerateVertexData = function () {
  34241. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34242. };
  34243. PlaneGeometry.prototype.copy = function (id) {
  34244. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34245. };
  34246. PlaneGeometry.prototype.serialize = function () {
  34247. var serializationObject = _super.prototype.serialize.call(this);
  34248. serializationObject.size = this.size;
  34249. return serializationObject;
  34250. };
  34251. PlaneGeometry.Parse = function (parsedPlane, scene) {
  34252. if (scene.getGeometryByID(parsedPlane.id)) {
  34253. return null; // null since geometry could be something else than a ground...
  34254. }
  34255. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34256. if (BABYLON.Tags) {
  34257. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34258. }
  34259. scene.pushGeometry(plane, true);
  34260. return plane;
  34261. };
  34262. return PlaneGeometry;
  34263. }(_PrimitiveGeometry));
  34264. BABYLON.PlaneGeometry = PlaneGeometry;
  34265. /**
  34266. * Creates a torus knot geometry
  34267. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  34268. */
  34269. var TorusKnotGeometry = /** @class */ (function (_super) {
  34270. __extends(TorusKnotGeometry, _super);
  34271. /**
  34272. * Creates a torus knot geometry
  34273. * @param id defines the unique ID of the geometry
  34274. * @param scene defines the hosting scene
  34275. * @param radius defines the radius of the torus knot
  34276. * @param tube defines the thickness of the torus knot tube
  34277. * @param radialSegments defines the number of radial segments
  34278. * @param tubularSegments defines the number of tubular segments
  34279. * @param p defines the first number of windings
  34280. * @param q defines the second number of windings
  34281. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34282. * @param mesh defines the hosting mesh (can be null)
  34283. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34284. */
  34285. function TorusKnotGeometry(id, scene,
  34286. /**
  34287. * Defines the radius of the torus knot
  34288. */
  34289. radius,
  34290. /**
  34291. * Defines the thickness of the torus knot tube
  34292. */
  34293. tube,
  34294. /**
  34295. * Defines the number of radial segments
  34296. */
  34297. radialSegments,
  34298. /**
  34299. * Defines the number of tubular segments
  34300. */
  34301. tubularSegments,
  34302. /**
  34303. * Defines the first number of windings
  34304. */
  34305. p,
  34306. /**
  34307. * Defines the second number of windings
  34308. */
  34309. q, canBeRegenerated, mesh,
  34310. /**
  34311. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34312. */
  34313. side) {
  34314. if (mesh === void 0) { mesh = null; }
  34315. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34316. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34317. _this.radius = radius;
  34318. _this.tube = tube;
  34319. _this.radialSegments = radialSegments;
  34320. _this.tubularSegments = tubularSegments;
  34321. _this.p = p;
  34322. _this.q = q;
  34323. _this.side = side;
  34324. return _this;
  34325. }
  34326. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  34327. 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 });
  34328. };
  34329. TorusKnotGeometry.prototype.copy = function (id) {
  34330. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34331. };
  34332. TorusKnotGeometry.prototype.serialize = function () {
  34333. var serializationObject = _super.prototype.serialize.call(this);
  34334. serializationObject.radius = this.radius;
  34335. serializationObject.tube = this.tube;
  34336. serializationObject.radialSegments = this.radialSegments;
  34337. serializationObject.tubularSegments = this.tubularSegments;
  34338. serializationObject.p = this.p;
  34339. serializationObject.q = this.q;
  34340. return serializationObject;
  34341. };
  34342. ;
  34343. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  34344. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34345. return null; // null since geometry could be something else than a ground...
  34346. }
  34347. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34348. if (BABYLON.Tags) {
  34349. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34350. }
  34351. scene.pushGeometry(torusKnot, true);
  34352. return torusKnot;
  34353. };
  34354. return TorusKnotGeometry;
  34355. }(_PrimitiveGeometry));
  34356. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  34357. //}
  34358. })(BABYLON || (BABYLON = {}));
  34359. //# sourceMappingURL=babylon.geometry.js.map
  34360. var BABYLON;
  34361. (function (BABYLON) {
  34362. var PostProcessManager = /** @class */ (function () {
  34363. function PostProcessManager(scene) {
  34364. this._vertexBuffers = {};
  34365. this._scene = scene;
  34366. }
  34367. PostProcessManager.prototype._prepareBuffers = function () {
  34368. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34369. return;
  34370. }
  34371. // VBO
  34372. var vertices = [];
  34373. vertices.push(1, 1);
  34374. vertices.push(-1, 1);
  34375. vertices.push(-1, -1);
  34376. vertices.push(1, -1);
  34377. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34378. this._buildIndexBuffer();
  34379. };
  34380. PostProcessManager.prototype._buildIndexBuffer = function () {
  34381. // Indices
  34382. var indices = [];
  34383. indices.push(0);
  34384. indices.push(1);
  34385. indices.push(2);
  34386. indices.push(0);
  34387. indices.push(2);
  34388. indices.push(3);
  34389. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34390. };
  34391. PostProcessManager.prototype._rebuild = function () {
  34392. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34393. if (!vb) {
  34394. return;
  34395. }
  34396. vb._rebuild();
  34397. this._buildIndexBuffer();
  34398. };
  34399. // Methods
  34400. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  34401. if (sourceTexture === void 0) { sourceTexture = null; }
  34402. if (postProcesses === void 0) { postProcesses = null; }
  34403. var camera = this._scene.activeCamera;
  34404. if (!camera) {
  34405. return false;
  34406. }
  34407. var postProcesses = postProcesses || camera._postProcesses;
  34408. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34409. return false;
  34410. }
  34411. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  34412. return true;
  34413. };
  34414. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  34415. if (targetTexture === void 0) { targetTexture = null; }
  34416. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34417. var engine = this._scene.getEngine();
  34418. for (var index = 0; index < postProcesses.length; index++) {
  34419. if (index < postProcesses.length - 1) {
  34420. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34421. }
  34422. else {
  34423. if (targetTexture) {
  34424. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  34425. }
  34426. else {
  34427. engine.restoreDefaultFramebuffer();
  34428. }
  34429. }
  34430. var pp = postProcesses[index];
  34431. var effect = pp.apply();
  34432. if (effect) {
  34433. pp.onBeforeRenderObservable.notifyObservers(effect);
  34434. // VBOs
  34435. this._prepareBuffers();
  34436. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34437. // Draw order
  34438. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34439. pp.onAfterRenderObservable.notifyObservers(effect);
  34440. }
  34441. }
  34442. // Restore depth buffer
  34443. engine.setDepthBuffer(true);
  34444. engine.setDepthWrite(true);
  34445. };
  34446. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  34447. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34448. var camera = this._scene.activeCamera;
  34449. if (!camera) {
  34450. return;
  34451. }
  34452. postProcesses = postProcesses || camera._postProcesses;
  34453. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34454. return;
  34455. }
  34456. var engine = this._scene.getEngine();
  34457. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34458. if (index < len - 1) {
  34459. postProcesses[index + 1].activate(camera, targetTexture);
  34460. }
  34461. else {
  34462. if (targetTexture) {
  34463. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  34464. }
  34465. else {
  34466. engine.restoreDefaultFramebuffer();
  34467. }
  34468. }
  34469. if (doNotPresent) {
  34470. break;
  34471. }
  34472. var pp = postProcesses[index];
  34473. var effect = pp.apply();
  34474. if (effect) {
  34475. pp.onBeforeRenderObservable.notifyObservers(effect);
  34476. // VBOs
  34477. this._prepareBuffers();
  34478. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34479. // Draw order
  34480. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34481. pp.onAfterRenderObservable.notifyObservers(effect);
  34482. }
  34483. }
  34484. // Restore states
  34485. engine.setDepthBuffer(true);
  34486. engine.setDepthWrite(true);
  34487. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34488. };
  34489. PostProcessManager.prototype.dispose = function () {
  34490. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34491. if (buffer) {
  34492. buffer.dispose();
  34493. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34494. }
  34495. if (this._indexBuffer) {
  34496. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34497. this._indexBuffer = null;
  34498. }
  34499. };
  34500. return PostProcessManager;
  34501. }());
  34502. BABYLON.PostProcessManager = PostProcessManager;
  34503. })(BABYLON || (BABYLON = {}));
  34504. //# sourceMappingURL=babylon.postProcessManager.js.map
  34505. var BABYLON;
  34506. (function (BABYLON) {
  34507. /**
  34508. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  34509. */
  34510. var PerformanceMonitor = /** @class */ (function () {
  34511. /**
  34512. * constructor
  34513. * @param frameSampleSize The number of samples required to saturate the sliding window
  34514. */
  34515. function PerformanceMonitor(frameSampleSize) {
  34516. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  34517. this._enabled = true;
  34518. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  34519. }
  34520. /**
  34521. * Samples current frame
  34522. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  34523. */
  34524. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  34525. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  34526. if (!this._enabled)
  34527. return;
  34528. if (this._lastFrameTimeMs != null) {
  34529. var dt = timeMs - this._lastFrameTimeMs;
  34530. this._rollingFrameTime.add(dt);
  34531. }
  34532. this._lastFrameTimeMs = timeMs;
  34533. };
  34534. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  34535. /**
  34536. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34537. * @return Average frame time in milliseconds
  34538. */
  34539. get: function () {
  34540. return this._rollingFrameTime.average;
  34541. },
  34542. enumerable: true,
  34543. configurable: true
  34544. });
  34545. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  34546. /**
  34547. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34548. * @return Frame time variance in milliseconds squared
  34549. */
  34550. get: function () {
  34551. return this._rollingFrameTime.variance;
  34552. },
  34553. enumerable: true,
  34554. configurable: true
  34555. });
  34556. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  34557. /**
  34558. * Returns the frame time of the most recent frame
  34559. * @return Frame time in milliseconds
  34560. */
  34561. get: function () {
  34562. return this._rollingFrameTime.history(0);
  34563. },
  34564. enumerable: true,
  34565. configurable: true
  34566. });
  34567. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  34568. /**
  34569. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  34570. * @return Framerate in frames per second
  34571. */
  34572. get: function () {
  34573. return 1000.0 / this._rollingFrameTime.average;
  34574. },
  34575. enumerable: true,
  34576. configurable: true
  34577. });
  34578. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  34579. /**
  34580. * Returns the average framerate in frames per second using the most recent frame time
  34581. * @return Framerate in frames per second
  34582. */
  34583. get: function () {
  34584. var history = this._rollingFrameTime.history(0);
  34585. if (history === 0) {
  34586. return 0;
  34587. }
  34588. return 1000.0 / history;
  34589. },
  34590. enumerable: true,
  34591. configurable: true
  34592. });
  34593. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  34594. /**
  34595. * Returns true if enough samples have been taken to completely fill the sliding window
  34596. * @return true if saturated
  34597. */
  34598. get: function () {
  34599. return this._rollingFrameTime.isSaturated();
  34600. },
  34601. enumerable: true,
  34602. configurable: true
  34603. });
  34604. /**
  34605. * Enables contributions to the sliding window sample set
  34606. */
  34607. PerformanceMonitor.prototype.enable = function () {
  34608. this._enabled = true;
  34609. };
  34610. /**
  34611. * Disables contributions to the sliding window sample set
  34612. * Samples will not be interpolated over the disabled period
  34613. */
  34614. PerformanceMonitor.prototype.disable = function () {
  34615. this._enabled = false;
  34616. //clear last sample to avoid interpolating over the disabled period when next enabled
  34617. this._lastFrameTimeMs = null;
  34618. };
  34619. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  34620. /**
  34621. * Returns true if sampling is enabled
  34622. * @return true if enabled
  34623. */
  34624. get: function () {
  34625. return this._enabled;
  34626. },
  34627. enumerable: true,
  34628. configurable: true
  34629. });
  34630. /**
  34631. * Resets performance monitor
  34632. */
  34633. PerformanceMonitor.prototype.reset = function () {
  34634. //clear last sample to avoid interpolating over the disabled period when next enabled
  34635. this._lastFrameTimeMs = null;
  34636. //wipe record
  34637. this._rollingFrameTime.reset();
  34638. };
  34639. return PerformanceMonitor;
  34640. }());
  34641. BABYLON.PerformanceMonitor = PerformanceMonitor;
  34642. /**
  34643. * RollingAverage
  34644. *
  34645. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  34646. */
  34647. var RollingAverage = /** @class */ (function () {
  34648. /**
  34649. * constructor
  34650. * @param length The number of samples required to saturate the sliding window
  34651. */
  34652. function RollingAverage(length) {
  34653. this._samples = new Array(length);
  34654. this.reset();
  34655. }
  34656. /**
  34657. * Adds a sample to the sample set
  34658. * @param v The sample value
  34659. */
  34660. RollingAverage.prototype.add = function (v) {
  34661. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  34662. var delta;
  34663. //we need to check if we've already wrapped round
  34664. if (this.isSaturated()) {
  34665. //remove bottom of stack from mean
  34666. var bottomValue = this._samples[this._pos];
  34667. delta = bottomValue - this.average;
  34668. this.average -= delta / (this._sampleCount - 1);
  34669. this._m2 -= delta * (bottomValue - this.average);
  34670. }
  34671. else {
  34672. this._sampleCount++;
  34673. }
  34674. //add new value to mean
  34675. delta = v - this.average;
  34676. this.average += delta / (this._sampleCount);
  34677. this._m2 += delta * (v - this.average);
  34678. //set the new variance
  34679. this.variance = this._m2 / (this._sampleCount - 1);
  34680. this._samples[this._pos] = v;
  34681. this._pos++;
  34682. this._pos %= this._samples.length; //positive wrap around
  34683. };
  34684. /**
  34685. * Returns previously added values or null if outside of history or outside the sliding window domain
  34686. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  34687. * @return Value previously recorded with add() or null if outside of range
  34688. */
  34689. RollingAverage.prototype.history = function (i) {
  34690. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  34691. return 0;
  34692. }
  34693. var i0 = this._wrapPosition(this._pos - 1.0);
  34694. return this._samples[this._wrapPosition(i0 - i)];
  34695. };
  34696. /**
  34697. * Returns true if enough samples have been taken to completely fill the sliding window
  34698. * @return true if sample-set saturated
  34699. */
  34700. RollingAverage.prototype.isSaturated = function () {
  34701. return this._sampleCount >= this._samples.length;
  34702. };
  34703. /**
  34704. * Resets the rolling average (equivalent to 0 samples taken so far)
  34705. */
  34706. RollingAverage.prototype.reset = function () {
  34707. this.average = 0;
  34708. this.variance = 0;
  34709. this._sampleCount = 0;
  34710. this._pos = 0;
  34711. this._m2 = 0;
  34712. };
  34713. /**
  34714. * Wraps a value around the sample range boundaries
  34715. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  34716. * @return Wrapped position in sample range
  34717. */
  34718. RollingAverage.prototype._wrapPosition = function (i) {
  34719. var max = this._samples.length;
  34720. return ((i % max) + max) % max;
  34721. };
  34722. return RollingAverage;
  34723. }());
  34724. BABYLON.RollingAverage = RollingAverage;
  34725. })(BABYLON || (BABYLON = {}));
  34726. //# sourceMappingURL=babylon.performanceMonitor.js.map
  34727. var BABYLON;
  34728. (function (BABYLON) {
  34729. /**
  34730. * This groups together the common properties used for image processing either in direct forward pass
  34731. * or through post processing effect depending on the use of the image processing pipeline in your scene
  34732. * or not.
  34733. */
  34734. var ImageProcessingConfiguration = /** @class */ (function () {
  34735. function ImageProcessingConfiguration() {
  34736. /**
  34737. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  34738. */
  34739. this.colorCurves = new BABYLON.ColorCurves();
  34740. this._colorCurvesEnabled = false;
  34741. this._colorGradingEnabled = false;
  34742. this._colorGradingWithGreenDepth = true;
  34743. this._colorGradingBGR = true;
  34744. this._exposure = 1.0;
  34745. this._toneMappingEnabled = false;
  34746. this._contrast = 1.0;
  34747. /**
  34748. * Vignette stretch size.
  34749. */
  34750. this.vignetteStretch = 0;
  34751. /**
  34752. * Vignette centre X Offset.
  34753. */
  34754. this.vignetteCentreX = 0;
  34755. /**
  34756. * Vignette centre Y Offset.
  34757. */
  34758. this.vignetteCentreY = 0;
  34759. /**
  34760. * Vignette weight or intensity of the vignette effect.
  34761. */
  34762. this.vignetteWeight = 1.5;
  34763. /**
  34764. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  34765. * if vignetteEnabled is set to true.
  34766. */
  34767. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  34768. /**
  34769. * Camera field of view used by the Vignette effect.
  34770. */
  34771. this.vignetteCameraFov = 0.5;
  34772. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  34773. this._vignetteEnabled = false;
  34774. this._applyByPostProcess = false;
  34775. this._isEnabled = true;
  34776. /**
  34777. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  34778. * @type {BABYLON.Observable}
  34779. */
  34780. this.onUpdateParameters = new BABYLON.Observable();
  34781. }
  34782. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  34783. /**
  34784. * Gets wether the color curves effect is enabled.
  34785. */
  34786. get: function () {
  34787. return this._colorCurvesEnabled;
  34788. },
  34789. /**
  34790. * Sets wether the color curves effect is enabled.
  34791. */
  34792. set: function (value) {
  34793. if (this._colorCurvesEnabled === value) {
  34794. return;
  34795. }
  34796. this._colorCurvesEnabled = value;
  34797. this._updateParameters();
  34798. },
  34799. enumerable: true,
  34800. configurable: true
  34801. });
  34802. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  34803. /**
  34804. * Gets wether the color grading effect is enabled.
  34805. */
  34806. get: function () {
  34807. return this._colorGradingEnabled;
  34808. },
  34809. /**
  34810. * Sets wether the color grading effect is enabled.
  34811. */
  34812. set: function (value) {
  34813. if (this._colorGradingEnabled === value) {
  34814. return;
  34815. }
  34816. this._colorGradingEnabled = value;
  34817. this._updateParameters();
  34818. },
  34819. enumerable: true,
  34820. configurable: true
  34821. });
  34822. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  34823. /**
  34824. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  34825. */
  34826. get: function () {
  34827. return this._colorGradingWithGreenDepth;
  34828. },
  34829. /**
  34830. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  34831. */
  34832. set: function (value) {
  34833. if (this._colorGradingWithGreenDepth === value) {
  34834. return;
  34835. }
  34836. this._colorGradingWithGreenDepth = value;
  34837. this._updateParameters();
  34838. },
  34839. enumerable: true,
  34840. configurable: true
  34841. });
  34842. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  34843. /**
  34844. * Gets wether the color grading texture contains BGR values.
  34845. */
  34846. get: function () {
  34847. return this._colorGradingBGR;
  34848. },
  34849. /**
  34850. * Sets wether the color grading texture contains BGR values.
  34851. */
  34852. set: function (value) {
  34853. if (this._colorGradingBGR === value) {
  34854. return;
  34855. }
  34856. this._colorGradingBGR = value;
  34857. this._updateParameters();
  34858. },
  34859. enumerable: true,
  34860. configurable: true
  34861. });
  34862. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  34863. /**
  34864. * Gets the Exposure used in the effect.
  34865. */
  34866. get: function () {
  34867. return this._exposure;
  34868. },
  34869. /**
  34870. * Sets the Exposure used in the effect.
  34871. */
  34872. set: function (value) {
  34873. if (this._exposure === value) {
  34874. return;
  34875. }
  34876. this._exposure = value;
  34877. this._updateParameters();
  34878. },
  34879. enumerable: true,
  34880. configurable: true
  34881. });
  34882. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  34883. /**
  34884. * Gets wether the tone mapping effect is enabled.
  34885. */
  34886. get: function () {
  34887. return this._toneMappingEnabled;
  34888. },
  34889. /**
  34890. * Sets wether the tone mapping effect is enabled.
  34891. */
  34892. set: function (value) {
  34893. if (this._toneMappingEnabled === value) {
  34894. return;
  34895. }
  34896. this._toneMappingEnabled = value;
  34897. this._updateParameters();
  34898. },
  34899. enumerable: true,
  34900. configurable: true
  34901. });
  34902. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  34903. /**
  34904. * Gets the contrast used in the effect.
  34905. */
  34906. get: function () {
  34907. return this._contrast;
  34908. },
  34909. /**
  34910. * Sets the contrast used in the effect.
  34911. */
  34912. set: function (value) {
  34913. if (this._contrast === value) {
  34914. return;
  34915. }
  34916. this._contrast = value;
  34917. this._updateParameters();
  34918. },
  34919. enumerable: true,
  34920. configurable: true
  34921. });
  34922. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  34923. /**
  34924. * Gets the vignette blend mode allowing different kind of effect.
  34925. */
  34926. get: function () {
  34927. return this._vignetteBlendMode;
  34928. },
  34929. /**
  34930. * Sets the vignette blend mode allowing different kind of effect.
  34931. */
  34932. set: function (value) {
  34933. if (this._vignetteBlendMode === value) {
  34934. return;
  34935. }
  34936. this._vignetteBlendMode = value;
  34937. this._updateParameters();
  34938. },
  34939. enumerable: true,
  34940. configurable: true
  34941. });
  34942. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  34943. /**
  34944. * Gets wether the vignette effect is enabled.
  34945. */
  34946. get: function () {
  34947. return this._vignetteEnabled;
  34948. },
  34949. /**
  34950. * Sets wether the vignette effect is enabled.
  34951. */
  34952. set: function (value) {
  34953. if (this._vignetteEnabled === value) {
  34954. return;
  34955. }
  34956. this._vignetteEnabled = value;
  34957. this._updateParameters();
  34958. },
  34959. enumerable: true,
  34960. configurable: true
  34961. });
  34962. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  34963. /**
  34964. * Gets wether the image processing is applied through a post process or not.
  34965. */
  34966. get: function () {
  34967. return this._applyByPostProcess;
  34968. },
  34969. /**
  34970. * Sets wether the image processing is applied through a post process or not.
  34971. */
  34972. set: function (value) {
  34973. if (this._applyByPostProcess === value) {
  34974. return;
  34975. }
  34976. this._applyByPostProcess = value;
  34977. this._updateParameters();
  34978. },
  34979. enumerable: true,
  34980. configurable: true
  34981. });
  34982. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  34983. /**
  34984. * Gets wether the image processing is enabled or not.
  34985. */
  34986. get: function () {
  34987. return this._isEnabled;
  34988. },
  34989. /**
  34990. * Sets wether the image processing is enabled or not.
  34991. */
  34992. set: function (value) {
  34993. if (this._isEnabled === value) {
  34994. return;
  34995. }
  34996. this._isEnabled = value;
  34997. this._updateParameters();
  34998. },
  34999. enumerable: true,
  35000. configurable: true
  35001. });
  35002. /**
  35003. * Method called each time the image processing information changes requires to recompile the effect.
  35004. */
  35005. ImageProcessingConfiguration.prototype._updateParameters = function () {
  35006. this.onUpdateParameters.notifyObservers(this);
  35007. };
  35008. ImageProcessingConfiguration.prototype.getClassName = function () {
  35009. return "ImageProcessingConfiguration";
  35010. };
  35011. /**
  35012. * Prepare the list of uniforms associated with the Image Processing effects.
  35013. * @param uniformsList The list of uniforms used in the effect
  35014. * @param defines the list of defines currently in use
  35015. */
  35016. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  35017. if (defines.EXPOSURE) {
  35018. uniforms.push("exposureLinear");
  35019. }
  35020. if (defines.CONTRAST) {
  35021. uniforms.push("contrast");
  35022. }
  35023. if (defines.COLORGRADING) {
  35024. uniforms.push("colorTransformSettings");
  35025. }
  35026. if (defines.VIGNETTE) {
  35027. uniforms.push("vInverseScreenSize");
  35028. uniforms.push("vignetteSettings1");
  35029. uniforms.push("vignetteSettings2");
  35030. }
  35031. if (defines.COLORCURVES) {
  35032. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  35033. }
  35034. };
  35035. /**
  35036. * Prepare the list of samplers associated with the Image Processing effects.
  35037. * @param uniformsList The list of uniforms used in the effect
  35038. * @param defines the list of defines currently in use
  35039. */
  35040. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  35041. if (defines.COLORGRADING) {
  35042. samplersList.push("txColorTransform");
  35043. }
  35044. };
  35045. /**
  35046. * Prepare the list of defines associated to the shader.
  35047. * @param defines the list of defines to complete
  35048. */
  35049. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  35050. if (forPostProcess === void 0) { forPostProcess = false; }
  35051. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  35052. defines.VIGNETTE = false;
  35053. defines.TONEMAPPING = false;
  35054. defines.CONTRAST = false;
  35055. defines.EXPOSURE = false;
  35056. defines.COLORCURVES = false;
  35057. defines.COLORGRADING = false;
  35058. defines.COLORGRADING3D = false;
  35059. defines.IMAGEPROCESSING = false;
  35060. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  35061. return;
  35062. }
  35063. defines.VIGNETTE = this.vignetteEnabled;
  35064. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  35065. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  35066. defines.TONEMAPPING = this.toneMappingEnabled;
  35067. defines.CONTRAST = (this.contrast !== 1.0);
  35068. defines.EXPOSURE = (this.exposure !== 1.0);
  35069. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  35070. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  35071. if (defines.COLORGRADING) {
  35072. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  35073. }
  35074. else {
  35075. defines.COLORGRADING3D = false;
  35076. }
  35077. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  35078. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  35079. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  35080. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  35081. };
  35082. /**
  35083. * Returns true if all the image processing information are ready.
  35084. */
  35085. ImageProcessingConfiguration.prototype.isReady = function () {
  35086. // Color Grading texure can not be none blocking.
  35087. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  35088. };
  35089. /**
  35090. * Binds the image processing to the shader.
  35091. * @param effect The effect to bind to
  35092. */
  35093. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  35094. if (aspectRatio === void 0) { aspectRatio = 1; }
  35095. // Color Curves
  35096. if (this._colorCurvesEnabled && this.colorCurves) {
  35097. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  35098. }
  35099. // Vignette
  35100. if (this._vignetteEnabled) {
  35101. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  35102. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  35103. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  35104. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  35105. var vignetteScaleX = vignetteScaleY * aspectRatio;
  35106. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  35107. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  35108. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  35109. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  35110. var vignettePower = -2.0 * this.vignetteWeight;
  35111. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  35112. }
  35113. // Exposure
  35114. effect.setFloat("exposureLinear", this.exposure);
  35115. // Contrast
  35116. effect.setFloat("contrast", this.contrast);
  35117. // Color transform settings
  35118. if (this.colorGradingTexture) {
  35119. effect.setTexture("txColorTransform", this.colorGradingTexture);
  35120. var textureSize = this.colorGradingTexture.getSize().height;
  35121. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  35122. 0.5 / textureSize, // textureOffset
  35123. textureSize, // textureSize
  35124. this.colorGradingTexture.level // weight
  35125. );
  35126. }
  35127. };
  35128. /**
  35129. * Clones the current image processing instance.
  35130. * @return The cloned image processing
  35131. */
  35132. ImageProcessingConfiguration.prototype.clone = function () {
  35133. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  35134. };
  35135. /**
  35136. * Serializes the current image processing instance to a json representation.
  35137. * @return a JSON representation
  35138. */
  35139. ImageProcessingConfiguration.prototype.serialize = function () {
  35140. return BABYLON.SerializationHelper.Serialize(this);
  35141. };
  35142. /**
  35143. * Parses the image processing from a json representation.
  35144. * @param source the JSON source to parse
  35145. * @return The parsed image processing
  35146. */
  35147. ImageProcessingConfiguration.Parse = function (source) {
  35148. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  35149. };
  35150. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  35151. /**
  35152. * Used to apply the vignette as a mix with the pixel color.
  35153. */
  35154. get: function () {
  35155. return this._VIGNETTEMODE_MULTIPLY;
  35156. },
  35157. enumerable: true,
  35158. configurable: true
  35159. });
  35160. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  35161. /**
  35162. * Used to apply the vignette as a replacement of the pixel color.
  35163. */
  35164. get: function () {
  35165. return this._VIGNETTEMODE_OPAQUE;
  35166. },
  35167. enumerable: true,
  35168. configurable: true
  35169. });
  35170. // Static constants associated to the image processing.
  35171. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  35172. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  35173. __decorate([
  35174. BABYLON.serializeAsColorCurves()
  35175. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  35176. __decorate([
  35177. BABYLON.serialize()
  35178. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  35179. __decorate([
  35180. BABYLON.serializeAsTexture()
  35181. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  35182. __decorate([
  35183. BABYLON.serialize()
  35184. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  35185. __decorate([
  35186. BABYLON.serialize()
  35187. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  35188. __decorate([
  35189. BABYLON.serialize()
  35190. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  35191. __decorate([
  35192. BABYLON.serialize()
  35193. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  35194. __decorate([
  35195. BABYLON.serialize()
  35196. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  35197. __decorate([
  35198. BABYLON.serialize()
  35199. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  35200. __decorate([
  35201. BABYLON.serialize()
  35202. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  35203. __decorate([
  35204. BABYLON.serialize()
  35205. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  35206. __decorate([
  35207. BABYLON.serialize()
  35208. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  35209. __decorate([
  35210. BABYLON.serialize()
  35211. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  35212. __decorate([
  35213. BABYLON.serializeAsColor4()
  35214. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  35215. __decorate([
  35216. BABYLON.serialize()
  35217. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  35218. __decorate([
  35219. BABYLON.serialize()
  35220. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  35221. __decorate([
  35222. BABYLON.serialize()
  35223. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  35224. __decorate([
  35225. BABYLON.serialize()
  35226. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  35227. __decorate([
  35228. BABYLON.serialize()
  35229. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  35230. return ImageProcessingConfiguration;
  35231. }());
  35232. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  35233. })(BABYLON || (BABYLON = {}));
  35234. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  35235. var BABYLON;
  35236. (function (BABYLON) {
  35237. /**
  35238. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  35239. * It can help converting any input color in a desired output one. This can then be used to create effects
  35240. * from sepia, black and white to sixties or futuristic rendering...
  35241. *
  35242. * The only supported format is currently 3dl.
  35243. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  35244. */
  35245. var ColorGradingTexture = /** @class */ (function (_super) {
  35246. __extends(ColorGradingTexture, _super);
  35247. /**
  35248. * Instantiates a ColorGradingTexture from the following parameters.
  35249. *
  35250. * @param url The location of the color gradind data (currently only supporting 3dl)
  35251. * @param scene The scene the texture will be used in
  35252. */
  35253. function ColorGradingTexture(url, scene) {
  35254. var _this = _super.call(this, scene) || this;
  35255. if (!url) {
  35256. return _this;
  35257. }
  35258. _this._engine = scene.getEngine();
  35259. _this._textureMatrix = BABYLON.Matrix.Identity();
  35260. _this.name = url;
  35261. _this.url = url;
  35262. _this.hasAlpha = false;
  35263. _this.isCube = false;
  35264. _this.is3D = _this._engine.webGLVersion > 1;
  35265. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35266. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35267. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35268. _this.anisotropicFilteringLevel = 1;
  35269. _this._texture = _this._getFromCache(url, true);
  35270. if (!_this._texture) {
  35271. if (!scene.useDelayedTextureLoading) {
  35272. _this.loadTexture();
  35273. }
  35274. else {
  35275. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35276. }
  35277. }
  35278. return _this;
  35279. }
  35280. /**
  35281. * Returns the texture matrix used in most of the material.
  35282. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  35283. */
  35284. ColorGradingTexture.prototype.getTextureMatrix = function () {
  35285. return this._textureMatrix;
  35286. };
  35287. /**
  35288. * Occurs when the file being loaded is a .3dl LUT file.
  35289. */
  35290. ColorGradingTexture.prototype.load3dlTexture = function () {
  35291. var engine = this._engine;
  35292. var texture;
  35293. if (engine.webGLVersion === 1) {
  35294. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35295. }
  35296. else {
  35297. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35298. }
  35299. this._texture = texture;
  35300. var callback = function (text) {
  35301. if (typeof text !== "string") {
  35302. return;
  35303. }
  35304. var data = null;
  35305. var tempData = null;
  35306. var line;
  35307. var lines = text.split('\n');
  35308. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  35309. var maxColor = 0;
  35310. for (var i = 0; i < lines.length; i++) {
  35311. line = lines[i];
  35312. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  35313. continue;
  35314. if (line.indexOf('#') === 0)
  35315. continue;
  35316. var words = line.split(" ");
  35317. if (size === 0) {
  35318. // Number of space + one
  35319. size = words.length;
  35320. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  35321. tempData = new Float32Array(size * size * size * 4);
  35322. continue;
  35323. }
  35324. if (size != 0) {
  35325. var r = Math.max(parseInt(words[0]), 0);
  35326. var g = Math.max(parseInt(words[1]), 0);
  35327. var b = Math.max(parseInt(words[2]), 0);
  35328. maxColor = Math.max(r, maxColor);
  35329. maxColor = Math.max(g, maxColor);
  35330. maxColor = Math.max(b, maxColor);
  35331. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  35332. if (tempData) {
  35333. tempData[pixelStorageIndex + 0] = r;
  35334. tempData[pixelStorageIndex + 1] = g;
  35335. tempData[pixelStorageIndex + 2] = b;
  35336. }
  35337. pixelIndexSlice++;
  35338. if (pixelIndexSlice % size == 0) {
  35339. pixelIndexH++;
  35340. pixelIndexSlice = 0;
  35341. if (pixelIndexH % size == 0) {
  35342. pixelIndexW++;
  35343. pixelIndexH = 0;
  35344. }
  35345. }
  35346. }
  35347. }
  35348. if (tempData && data) {
  35349. for (var i = 0; i < tempData.length; i++) {
  35350. if (i > 0 && (i + 1) % 4 === 0) {
  35351. data[i] = 255;
  35352. }
  35353. else {
  35354. var value = tempData[i];
  35355. data[i] = (value / maxColor * 255);
  35356. }
  35357. }
  35358. }
  35359. if (texture.is3D) {
  35360. texture.updateSize(size, size, size);
  35361. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35362. }
  35363. else {
  35364. texture.updateSize(size * size, size);
  35365. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35366. }
  35367. };
  35368. var scene = this.getScene();
  35369. if (scene) {
  35370. scene._loadFile(this.url, callback);
  35371. }
  35372. else {
  35373. this._engine._loadFile(this.url, callback);
  35374. }
  35375. return this._texture;
  35376. };
  35377. /**
  35378. * Starts the loading process of the texture.
  35379. */
  35380. ColorGradingTexture.prototype.loadTexture = function () {
  35381. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  35382. this.load3dlTexture();
  35383. }
  35384. };
  35385. /**
  35386. * Clones the color gradind texture.
  35387. */
  35388. ColorGradingTexture.prototype.clone = function () {
  35389. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  35390. // Base texture
  35391. newTexture.level = this.level;
  35392. return newTexture;
  35393. };
  35394. /**
  35395. * Called during delayed load for textures.
  35396. */
  35397. ColorGradingTexture.prototype.delayLoad = function () {
  35398. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  35399. return;
  35400. }
  35401. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35402. this._texture = this._getFromCache(this.url, true);
  35403. if (!this._texture) {
  35404. this.loadTexture();
  35405. }
  35406. };
  35407. /**
  35408. * Parses a color grading texture serialized by Babylon.
  35409. * @param parsedTexture The texture information being parsedTexture
  35410. * @param scene The scene to load the texture in
  35411. * @param rootUrl The root url of the data assets to load
  35412. * @return A color gradind texture
  35413. */
  35414. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  35415. var texture = null;
  35416. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  35417. texture = new ColorGradingTexture(parsedTexture.name, scene);
  35418. texture.name = parsedTexture.name;
  35419. texture.level = parsedTexture.level;
  35420. }
  35421. return texture;
  35422. };
  35423. /**
  35424. * Serializes the LUT texture to json format.
  35425. */
  35426. ColorGradingTexture.prototype.serialize = function () {
  35427. if (!this.name) {
  35428. return null;
  35429. }
  35430. var serializationObject = {};
  35431. serializationObject.name = this.name;
  35432. serializationObject.level = this.level;
  35433. serializationObject.customType = "BABYLON.ColorGradingTexture";
  35434. return serializationObject;
  35435. };
  35436. /**
  35437. * Empty line regex stored for GC.
  35438. */
  35439. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  35440. return ColorGradingTexture;
  35441. }(BABYLON.BaseTexture));
  35442. BABYLON.ColorGradingTexture = ColorGradingTexture;
  35443. })(BABYLON || (BABYLON = {}));
  35444. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  35445. var BABYLON;
  35446. (function (BABYLON) {
  35447. /**
  35448. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35449. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35450. * 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;
  35451. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35452. */
  35453. var ColorCurves = /** @class */ (function () {
  35454. function ColorCurves() {
  35455. this._dirty = true;
  35456. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  35457. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  35458. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35459. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  35460. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35461. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  35462. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  35463. this._globalHue = 30;
  35464. this._globalDensity = 0;
  35465. this._globalSaturation = 0;
  35466. this._globalExposure = 0;
  35467. this._highlightsHue = 30;
  35468. this._highlightsDensity = 0;
  35469. this._highlightsSaturation = 0;
  35470. this._highlightsExposure = 0;
  35471. this._midtonesHue = 30;
  35472. this._midtonesDensity = 0;
  35473. this._midtonesSaturation = 0;
  35474. this._midtonesExposure = 0;
  35475. this._shadowsHue = 30;
  35476. this._shadowsDensity = 0;
  35477. this._shadowsSaturation = 0;
  35478. this._shadowsExposure = 0;
  35479. }
  35480. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  35481. /**
  35482. * Gets the global Hue value.
  35483. * 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).
  35484. */
  35485. get: function () {
  35486. return this._globalHue;
  35487. },
  35488. /**
  35489. * Sets the global Hue value.
  35490. * 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).
  35491. */
  35492. set: function (value) {
  35493. this._globalHue = value;
  35494. this._dirty = true;
  35495. },
  35496. enumerable: true,
  35497. configurable: true
  35498. });
  35499. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  35500. /**
  35501. * Gets the global Density value.
  35502. * 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.
  35503. * Values less than zero provide a filter of opposite hue.
  35504. */
  35505. get: function () {
  35506. return this._globalDensity;
  35507. },
  35508. /**
  35509. * Sets the global Density value.
  35510. * 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.
  35511. * Values less than zero provide a filter of opposite hue.
  35512. */
  35513. set: function (value) {
  35514. this._globalDensity = value;
  35515. this._dirty = true;
  35516. },
  35517. enumerable: true,
  35518. configurable: true
  35519. });
  35520. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  35521. /**
  35522. * Gets the global Saturation value.
  35523. * 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.
  35524. */
  35525. get: function () {
  35526. return this._globalSaturation;
  35527. },
  35528. /**
  35529. * Sets the global Saturation value.
  35530. * 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.
  35531. */
  35532. set: function (value) {
  35533. this._globalSaturation = value;
  35534. this._dirty = true;
  35535. },
  35536. enumerable: true,
  35537. configurable: true
  35538. });
  35539. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  35540. /**
  35541. * Gets the highlights Hue value.
  35542. * 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).
  35543. */
  35544. get: function () {
  35545. return this._highlightsHue;
  35546. },
  35547. /**
  35548. * Sets the highlights Hue value.
  35549. * 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).
  35550. */
  35551. set: function (value) {
  35552. this._highlightsHue = value;
  35553. this._dirty = true;
  35554. },
  35555. enumerable: true,
  35556. configurable: true
  35557. });
  35558. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  35559. /**
  35560. * Gets the highlights Density value.
  35561. * 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.
  35562. * Values less than zero provide a filter of opposite hue.
  35563. */
  35564. get: function () {
  35565. return this._highlightsDensity;
  35566. },
  35567. /**
  35568. * Sets the highlights Density value.
  35569. * 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.
  35570. * Values less than zero provide a filter of opposite hue.
  35571. */
  35572. set: function (value) {
  35573. this._highlightsDensity = value;
  35574. this._dirty = true;
  35575. },
  35576. enumerable: true,
  35577. configurable: true
  35578. });
  35579. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  35580. /**
  35581. * Gets the highlights Saturation value.
  35582. * 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.
  35583. */
  35584. get: function () {
  35585. return this._highlightsSaturation;
  35586. },
  35587. /**
  35588. * Sets the highlights Saturation value.
  35589. * 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.
  35590. */
  35591. set: function (value) {
  35592. this._highlightsSaturation = value;
  35593. this._dirty = true;
  35594. },
  35595. enumerable: true,
  35596. configurable: true
  35597. });
  35598. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  35599. /**
  35600. * Gets the highlights Exposure value.
  35601. * 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.
  35602. */
  35603. get: function () {
  35604. return this._highlightsExposure;
  35605. },
  35606. /**
  35607. * Sets the highlights Exposure value.
  35608. * 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.
  35609. */
  35610. set: function (value) {
  35611. this._highlightsExposure = value;
  35612. this._dirty = true;
  35613. },
  35614. enumerable: true,
  35615. configurable: true
  35616. });
  35617. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  35618. /**
  35619. * Gets the midtones Hue value.
  35620. * 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).
  35621. */
  35622. get: function () {
  35623. return this._midtonesHue;
  35624. },
  35625. /**
  35626. * Sets the midtones Hue value.
  35627. * 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).
  35628. */
  35629. set: function (value) {
  35630. this._midtonesHue = value;
  35631. this._dirty = true;
  35632. },
  35633. enumerable: true,
  35634. configurable: true
  35635. });
  35636. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  35637. /**
  35638. * Gets the midtones Density value.
  35639. * 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.
  35640. * Values less than zero provide a filter of opposite hue.
  35641. */
  35642. get: function () {
  35643. return this._midtonesDensity;
  35644. },
  35645. /**
  35646. * Sets the midtones Density value.
  35647. * 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.
  35648. * Values less than zero provide a filter of opposite hue.
  35649. */
  35650. set: function (value) {
  35651. this._midtonesDensity = value;
  35652. this._dirty = true;
  35653. },
  35654. enumerable: true,
  35655. configurable: true
  35656. });
  35657. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  35658. /**
  35659. * Gets the midtones Saturation value.
  35660. * 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.
  35661. */
  35662. get: function () {
  35663. return this._midtonesSaturation;
  35664. },
  35665. /**
  35666. * Sets the midtones Saturation value.
  35667. * 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.
  35668. */
  35669. set: function (value) {
  35670. this._midtonesSaturation = value;
  35671. this._dirty = true;
  35672. },
  35673. enumerable: true,
  35674. configurable: true
  35675. });
  35676. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  35677. /**
  35678. * Gets the midtones Exposure value.
  35679. * 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.
  35680. */
  35681. get: function () {
  35682. return this._midtonesExposure;
  35683. },
  35684. /**
  35685. * Sets the midtones Exposure value.
  35686. * 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.
  35687. */
  35688. set: function (value) {
  35689. this._midtonesExposure = value;
  35690. this._dirty = true;
  35691. },
  35692. enumerable: true,
  35693. configurable: true
  35694. });
  35695. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  35696. /**
  35697. * Gets the shadows Hue value.
  35698. * 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).
  35699. */
  35700. get: function () {
  35701. return this._shadowsHue;
  35702. },
  35703. /**
  35704. * Sets the shadows Hue value.
  35705. * 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).
  35706. */
  35707. set: function (value) {
  35708. this._shadowsHue = value;
  35709. this._dirty = true;
  35710. },
  35711. enumerable: true,
  35712. configurable: true
  35713. });
  35714. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  35715. /**
  35716. * Gets the shadows Density value.
  35717. * 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.
  35718. * Values less than zero provide a filter of opposite hue.
  35719. */
  35720. get: function () {
  35721. return this._shadowsDensity;
  35722. },
  35723. /**
  35724. * Sets the shadows Density value.
  35725. * 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.
  35726. * Values less than zero provide a filter of opposite hue.
  35727. */
  35728. set: function (value) {
  35729. this._shadowsDensity = value;
  35730. this._dirty = true;
  35731. },
  35732. enumerable: true,
  35733. configurable: true
  35734. });
  35735. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  35736. /**
  35737. * Gets the shadows Saturation value.
  35738. * 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.
  35739. */
  35740. get: function () {
  35741. return this._shadowsSaturation;
  35742. },
  35743. /**
  35744. * Sets the shadows Saturation value.
  35745. * 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.
  35746. */
  35747. set: function (value) {
  35748. this._shadowsSaturation = value;
  35749. this._dirty = true;
  35750. },
  35751. enumerable: true,
  35752. configurable: true
  35753. });
  35754. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  35755. /**
  35756. * Gets the shadows Exposure value.
  35757. * 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.
  35758. */
  35759. get: function () {
  35760. return this._shadowsExposure;
  35761. },
  35762. /**
  35763. * Sets the shadows Exposure value.
  35764. * 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.
  35765. */
  35766. set: function (value) {
  35767. this._shadowsExposure = value;
  35768. this._dirty = true;
  35769. },
  35770. enumerable: true,
  35771. configurable: true
  35772. });
  35773. ColorCurves.prototype.getClassName = function () {
  35774. return "ColorCurves";
  35775. };
  35776. /**
  35777. * Binds the color curves to the shader.
  35778. * @param colorCurves The color curve to bind
  35779. * @param effect The effect to bind to
  35780. */
  35781. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  35782. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  35783. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  35784. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  35785. if (colorCurves._dirty) {
  35786. colorCurves._dirty = false;
  35787. // Fill in global info.
  35788. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  35789. // Compute highlights info.
  35790. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  35791. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  35792. // Compute midtones info.
  35793. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  35794. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  35795. // Compute shadows info.
  35796. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  35797. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  35798. // Compute deltas (neutral is midtones).
  35799. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  35800. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  35801. }
  35802. if (effect) {
  35803. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  35804. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  35805. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  35806. }
  35807. };
  35808. /**
  35809. * Prepare the list of uniforms associated with the ColorCurves effects.
  35810. * @param uniformsList The list of uniforms used in the effect
  35811. */
  35812. ColorCurves.PrepareUniforms = function (uniformsList) {
  35813. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  35814. };
  35815. /**
  35816. * Returns color grading data based on a hue, density, saturation and exposure value.
  35817. * @param filterHue The hue of the color filter.
  35818. * @param filterDensity The density of the color filter.
  35819. * @param saturation The saturation.
  35820. * @param exposure The exposure.
  35821. * @param result The result data container.
  35822. */
  35823. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  35824. if (hue == null) {
  35825. return;
  35826. }
  35827. hue = ColorCurves.clamp(hue, 0, 360);
  35828. density = ColorCurves.clamp(density, -100, 100);
  35829. saturation = ColorCurves.clamp(saturation, -100, 100);
  35830. exposure = ColorCurves.clamp(exposure, -100, 100);
  35831. // Remap the slider/config filter density with non-linear mapping and also scale by half
  35832. // so that the maximum filter density is only 50% control. This provides fine control
  35833. // for small values and reasonable range.
  35834. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  35835. density *= 0.5;
  35836. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  35837. if (density < 0) {
  35838. density *= -1;
  35839. hue = (hue + 180) % 360;
  35840. }
  35841. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  35842. result.scaleToRef(2, result);
  35843. result.a = 1 + 0.01 * saturation;
  35844. };
  35845. /**
  35846. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  35847. * @param value The input slider value in range [-100,100].
  35848. * @returns Adjusted value.
  35849. */
  35850. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  35851. value /= 100;
  35852. var x = Math.abs(value);
  35853. x = Math.pow(x, 2);
  35854. if (value < 0) {
  35855. x *= -1;
  35856. }
  35857. x *= 100;
  35858. return x;
  35859. };
  35860. /**
  35861. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  35862. * @param hue The hue (H) input.
  35863. * @param saturation The saturation (S) input.
  35864. * @param brightness The brightness (B) input.
  35865. * @result An RGBA color represented as Vector4.
  35866. */
  35867. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  35868. var h = ColorCurves.clamp(hue, 0, 360);
  35869. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  35870. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  35871. if (s === 0) {
  35872. result.r = v;
  35873. result.g = v;
  35874. result.b = v;
  35875. }
  35876. else {
  35877. // sector 0 to 5
  35878. h /= 60;
  35879. var i = Math.floor(h);
  35880. // fractional part of h
  35881. var f = h - i;
  35882. var p = v * (1 - s);
  35883. var q = v * (1 - s * f);
  35884. var t = v * (1 - s * (1 - f));
  35885. switch (i) {
  35886. case 0:
  35887. result.r = v;
  35888. result.g = t;
  35889. result.b = p;
  35890. break;
  35891. case 1:
  35892. result.r = q;
  35893. result.g = v;
  35894. result.b = p;
  35895. break;
  35896. case 2:
  35897. result.r = p;
  35898. result.g = v;
  35899. result.b = t;
  35900. break;
  35901. case 3:
  35902. result.r = p;
  35903. result.g = q;
  35904. result.b = v;
  35905. break;
  35906. case 4:
  35907. result.r = t;
  35908. result.g = p;
  35909. result.b = v;
  35910. break;
  35911. default:// case 5:
  35912. result.r = v;
  35913. result.g = p;
  35914. result.b = q;
  35915. break;
  35916. }
  35917. }
  35918. result.a = 1;
  35919. };
  35920. /**
  35921. * Returns a value clamped between min and max
  35922. * @param value The value to clamp
  35923. * @param min The minimum of value
  35924. * @param max The maximum of value
  35925. * @returns The clamped value.
  35926. */
  35927. ColorCurves.clamp = function (value, min, max) {
  35928. return Math.min(Math.max(value, min), max);
  35929. };
  35930. /**
  35931. * Clones the current color curve instance.
  35932. * @return The cloned curves
  35933. */
  35934. ColorCurves.prototype.clone = function () {
  35935. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  35936. };
  35937. /**
  35938. * Serializes the current color curve instance to a json representation.
  35939. * @return a JSON representation
  35940. */
  35941. ColorCurves.prototype.serialize = function () {
  35942. return BABYLON.SerializationHelper.Serialize(this);
  35943. };
  35944. /**
  35945. * Parses the color curve from a json representation.
  35946. * @param source the JSON source to parse
  35947. * @return The parsed curves
  35948. */
  35949. ColorCurves.Parse = function (source) {
  35950. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  35951. };
  35952. __decorate([
  35953. BABYLON.serialize()
  35954. ], ColorCurves.prototype, "_globalHue", void 0);
  35955. __decorate([
  35956. BABYLON.serialize()
  35957. ], ColorCurves.prototype, "_globalDensity", void 0);
  35958. __decorate([
  35959. BABYLON.serialize()
  35960. ], ColorCurves.prototype, "_globalSaturation", void 0);
  35961. __decorate([
  35962. BABYLON.serialize()
  35963. ], ColorCurves.prototype, "_globalExposure", void 0);
  35964. __decorate([
  35965. BABYLON.serialize()
  35966. ], ColorCurves.prototype, "_highlightsHue", void 0);
  35967. __decorate([
  35968. BABYLON.serialize()
  35969. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  35970. __decorate([
  35971. BABYLON.serialize()
  35972. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  35973. __decorate([
  35974. BABYLON.serialize()
  35975. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  35976. __decorate([
  35977. BABYLON.serialize()
  35978. ], ColorCurves.prototype, "_midtonesHue", void 0);
  35979. __decorate([
  35980. BABYLON.serialize()
  35981. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  35982. __decorate([
  35983. BABYLON.serialize()
  35984. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  35985. __decorate([
  35986. BABYLON.serialize()
  35987. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  35988. return ColorCurves;
  35989. }());
  35990. BABYLON.ColorCurves = ColorCurves;
  35991. })(BABYLON || (BABYLON = {}));
  35992. //# sourceMappingURL=babylon.colorCurves.js.map
  35993. //# sourceMappingURL=babylon.behavior.js.map
  35994. var BABYLON;
  35995. (function (BABYLON) {
  35996. var MaterialHelper = /** @class */ (function () {
  35997. function MaterialHelper() {
  35998. }
  35999. MaterialHelper.BindEyePosition = function (effect, scene) {
  36000. if (scene._forcedViewPosition) {
  36001. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  36002. return;
  36003. }
  36004. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36005. };
  36006. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  36007. defines._needUVs = true;
  36008. defines[key] = true;
  36009. if (texture.getTextureMatrix().isIdentity(true)) {
  36010. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  36011. if (texture.coordinatesIndex === 0) {
  36012. defines["MAINUV1"] = true;
  36013. }
  36014. else {
  36015. defines["MAINUV2"] = true;
  36016. }
  36017. }
  36018. else {
  36019. defines[key + "DIRECTUV"] = 0;
  36020. }
  36021. };
  36022. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  36023. var matrix = texture.getTextureMatrix();
  36024. if (!matrix.isIdentity(true)) {
  36025. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  36026. }
  36027. };
  36028. /**
  36029. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  36030. * @param mesh defines the current mesh
  36031. * @param scene defines the current scene
  36032. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  36033. * @param pointsCloud defines if point cloud rendering has to be turned on
  36034. * @param fogEnabled defines if fog has to be turned on
  36035. * @param alphaTest defines if alpha testing has to be turned on
  36036. * @param defines defines the current list of defines
  36037. */
  36038. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  36039. if (defines._areMiscDirty) {
  36040. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  36041. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  36042. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  36043. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  36044. defines["ALPHATEST"] = alphaTest;
  36045. }
  36046. };
  36047. /**
  36048. * Helper used to prepare the list of defines associated with frame values for shader compilation
  36049. * @param scene defines the current scene
  36050. * @param engine defines the current engine
  36051. * @param defines specifies the list of active defines
  36052. * @param useInstances defines if instances have to be turned on
  36053. * @param alphaTest defines if alpha testing has to be turned on
  36054. */
  36055. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  36056. var changed = false;
  36057. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  36058. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  36059. changed = true;
  36060. }
  36061. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  36062. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  36063. changed = true;
  36064. }
  36065. if (defines["INSTANCES"] !== useInstances) {
  36066. defines["INSTANCES"] = useInstances;
  36067. changed = true;
  36068. }
  36069. if (changed) {
  36070. defines.markAsUnprocessed();
  36071. }
  36072. };
  36073. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  36074. if (useMorphTargets === void 0) { useMorphTargets = false; }
  36075. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  36076. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  36077. return false;
  36078. }
  36079. defines._normals = defines._needNormals;
  36080. defines._uvs = defines._needUVs;
  36081. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  36082. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36083. defines["TANGENT"] = true;
  36084. }
  36085. if (defines._needUVs) {
  36086. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  36087. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  36088. }
  36089. else {
  36090. defines["UV1"] = false;
  36091. defines["UV2"] = false;
  36092. }
  36093. if (useVertexColor) {
  36094. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  36095. defines["VERTEXCOLOR"] = hasVertexColors;
  36096. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  36097. }
  36098. if (useBones) {
  36099. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36100. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  36101. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  36102. }
  36103. else {
  36104. defines["NUM_BONE_INFLUENCERS"] = 0;
  36105. defines["BonesPerMesh"] = 0;
  36106. }
  36107. }
  36108. if (useMorphTargets) {
  36109. var manager = mesh.morphTargetManager;
  36110. if (manager) {
  36111. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  36112. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  36113. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  36114. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  36115. }
  36116. else {
  36117. defines["MORPHTARGETS_TANGENT"] = false;
  36118. defines["MORPHTARGETS_NORMAL"] = false;
  36119. defines["MORPHTARGETS"] = false;
  36120. defines["NUM_MORPH_INFLUENCERS"] = 0;
  36121. }
  36122. }
  36123. return true;
  36124. };
  36125. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  36126. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36127. if (disableLighting === void 0) { disableLighting = false; }
  36128. if (!defines._areLightsDirty) {
  36129. return defines._needNormals;
  36130. }
  36131. var lightIndex = 0;
  36132. var needNormals = false;
  36133. var needRebuild = false;
  36134. var lightmapMode = false;
  36135. var shadowEnabled = false;
  36136. var specularEnabled = false;
  36137. if (scene.lightsEnabled && !disableLighting) {
  36138. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  36139. var light = _a[_i];
  36140. needNormals = true;
  36141. if (defines["LIGHT" + lightIndex] === undefined) {
  36142. needRebuild = true;
  36143. }
  36144. defines["LIGHT" + lightIndex] = true;
  36145. defines["SPOTLIGHT" + lightIndex] = false;
  36146. defines["HEMILIGHT" + lightIndex] = false;
  36147. defines["POINTLIGHT" + lightIndex] = false;
  36148. defines["DIRLIGHT" + lightIndex] = false;
  36149. var type;
  36150. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  36151. type = "SPOTLIGHT" + lightIndex;
  36152. }
  36153. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  36154. type = "HEMILIGHT" + lightIndex;
  36155. }
  36156. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  36157. type = "POINTLIGHT" + lightIndex;
  36158. }
  36159. else {
  36160. type = "DIRLIGHT" + lightIndex;
  36161. }
  36162. defines[type] = true;
  36163. // Specular
  36164. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  36165. specularEnabled = true;
  36166. }
  36167. // Shadows
  36168. defines["SHADOW" + lightIndex] = false;
  36169. defines["SHADOWPCF" + lightIndex] = false;
  36170. defines["SHADOWESM" + lightIndex] = false;
  36171. defines["SHADOWCUBE" + lightIndex] = false;
  36172. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  36173. var shadowGenerator = light.getShadowGenerator();
  36174. if (shadowGenerator) {
  36175. shadowEnabled = true;
  36176. shadowGenerator.prepareDefines(defines, lightIndex);
  36177. }
  36178. }
  36179. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  36180. lightmapMode = true;
  36181. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  36182. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  36183. }
  36184. else {
  36185. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  36186. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  36187. }
  36188. lightIndex++;
  36189. if (lightIndex === maxSimultaneousLights)
  36190. break;
  36191. }
  36192. }
  36193. defines["SPECULARTERM"] = specularEnabled;
  36194. defines["SHADOWS"] = shadowEnabled;
  36195. // Resetting all other lights if any
  36196. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  36197. if (defines["LIGHT" + index] !== undefined) {
  36198. defines["LIGHT" + index] = false;
  36199. defines["HEMILIGHT" + lightIndex] = false;
  36200. defines["POINTLIGHT" + lightIndex] = false;
  36201. defines["DIRLIGHT" + lightIndex] = false;
  36202. defines["SPOTLIGHT" + lightIndex] = false;
  36203. defines["SHADOW" + lightIndex] = false;
  36204. }
  36205. }
  36206. var caps = scene.getEngine().getCaps();
  36207. if (defines["SHADOWFLOAT"] === undefined) {
  36208. needRebuild = true;
  36209. }
  36210. defines["SHADOWFLOAT"] = shadowEnabled &&
  36211. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  36212. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  36213. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  36214. if (needRebuild) {
  36215. defines.rebuild();
  36216. }
  36217. return needNormals;
  36218. };
  36219. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  36220. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36221. var uniformsList;
  36222. var uniformBuffersList = null;
  36223. if (uniformsListOrOptions.uniformsNames) {
  36224. var options = uniformsListOrOptions;
  36225. uniformsList = options.uniformsNames;
  36226. uniformBuffersList = options.uniformBuffersNames;
  36227. samplersList = options.samplers;
  36228. defines = options.defines;
  36229. maxSimultaneousLights = options.maxSimultaneousLights;
  36230. }
  36231. else {
  36232. uniformsList = uniformsListOrOptions;
  36233. if (!samplersList) {
  36234. samplersList = [];
  36235. }
  36236. }
  36237. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36238. if (!defines["LIGHT" + lightIndex]) {
  36239. break;
  36240. }
  36241. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  36242. if (uniformBuffersList) {
  36243. uniformBuffersList.push("Light" + lightIndex);
  36244. }
  36245. samplersList.push("shadowSampler" + lightIndex);
  36246. }
  36247. if (defines["NUM_MORPH_INFLUENCERS"]) {
  36248. uniformsList.push("morphTargetInfluences");
  36249. }
  36250. };
  36251. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  36252. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36253. if (rank === void 0) { rank = 0; }
  36254. var lightFallbackRank = 0;
  36255. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36256. if (!defines["LIGHT" + lightIndex]) {
  36257. break;
  36258. }
  36259. if (lightIndex > 0) {
  36260. lightFallbackRank = rank + lightIndex;
  36261. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  36262. }
  36263. if (!defines["SHADOWS"]) {
  36264. if (defines["SHADOW" + lightIndex]) {
  36265. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  36266. }
  36267. if (defines["SHADOWPCF" + lightIndex]) {
  36268. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  36269. }
  36270. if (defines["SHADOWESM" + lightIndex]) {
  36271. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  36272. }
  36273. }
  36274. }
  36275. return lightFallbackRank++;
  36276. };
  36277. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  36278. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  36279. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  36280. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  36281. var manager = mesh.morphTargetManager;
  36282. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  36283. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  36284. for (var index = 0; index < influencers; index++) {
  36285. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  36286. if (normal) {
  36287. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  36288. }
  36289. if (tangent) {
  36290. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  36291. }
  36292. if (attribs.length > maxAttributesCount) {
  36293. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  36294. }
  36295. }
  36296. }
  36297. };
  36298. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  36299. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  36300. fallbacks.addCPUSkinningFallback(0, mesh);
  36301. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36302. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36303. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  36304. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36305. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36306. }
  36307. }
  36308. };
  36309. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  36310. if (defines["INSTANCES"]) {
  36311. attribs.push("world0");
  36312. attribs.push("world1");
  36313. attribs.push("world2");
  36314. attribs.push("world3");
  36315. }
  36316. };
  36317. // Bindings
  36318. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  36319. if (light.shadowEnabled && mesh.receiveShadows) {
  36320. var shadowGenerator = light.getShadowGenerator();
  36321. if (shadowGenerator) {
  36322. shadowGenerator.bindShadowLight(lightIndex, effect);
  36323. }
  36324. }
  36325. };
  36326. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  36327. light.transferToEffect(effect, lightIndex + "");
  36328. };
  36329. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  36330. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36331. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  36332. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  36333. for (var i = 0; i < len; i++) {
  36334. var light = mesh._lightSources[i];
  36335. var iAsString = i.toString();
  36336. var scaledIntensity = light.getScaledIntensity();
  36337. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  36338. MaterialHelper.BindLightProperties(light, effect, i);
  36339. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  36340. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  36341. if (defines["SPECULARTERM"]) {
  36342. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  36343. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  36344. }
  36345. // Shadows
  36346. if (scene.shadowsEnabled) {
  36347. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  36348. }
  36349. light._uniformBuffer.update();
  36350. }
  36351. };
  36352. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  36353. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  36354. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  36355. effect.setColor3("vFogColor", scene.fogColor);
  36356. }
  36357. };
  36358. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  36359. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36360. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  36361. if (matrices && effect) {
  36362. effect.setMatrices("mBones", matrices);
  36363. }
  36364. }
  36365. };
  36366. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  36367. var manager = abstractMesh.morphTargetManager;
  36368. if (!abstractMesh || !manager) {
  36369. return;
  36370. }
  36371. effect.setFloatArray("morphTargetInfluences", manager.influences);
  36372. };
  36373. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  36374. if (defines["LOGARITHMICDEPTH"]) {
  36375. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  36376. }
  36377. };
  36378. MaterialHelper.BindClipPlane = function (effect, scene) {
  36379. if (scene.clipPlane) {
  36380. var clipPlane = scene.clipPlane;
  36381. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36382. }
  36383. };
  36384. return MaterialHelper;
  36385. }());
  36386. BABYLON.MaterialHelper = MaterialHelper;
  36387. })(BABYLON || (BABYLON = {}));
  36388. //# sourceMappingURL=babylon.materialHelper.js.map
  36389. var BABYLON;
  36390. (function (BABYLON) {
  36391. var PushMaterial = /** @class */ (function (_super) {
  36392. __extends(PushMaterial, _super);
  36393. function PushMaterial(name, scene) {
  36394. var _this = _super.call(this, name, scene) || this;
  36395. _this.storeEffectOnSubMeshes = true;
  36396. return _this;
  36397. }
  36398. PushMaterial.prototype.getEffect = function () {
  36399. return this._activeEffect;
  36400. };
  36401. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  36402. if (!mesh) {
  36403. return false;
  36404. }
  36405. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  36406. return true;
  36407. }
  36408. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  36409. };
  36410. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36411. this._activeEffect.setMatrix("world", world);
  36412. };
  36413. PushMaterial.prototype.bind = function (world, mesh) {
  36414. if (!mesh) {
  36415. return;
  36416. }
  36417. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  36418. };
  36419. PushMaterial.prototype._afterBind = function (mesh, effect) {
  36420. if (effect === void 0) { effect = null; }
  36421. _super.prototype._afterBind.call(this, mesh);
  36422. this.getScene()._cachedEffect = effect;
  36423. };
  36424. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  36425. if (visibility === void 0) { visibility = 1; }
  36426. return scene.isCachedMaterialInvalid(this, effect, visibility);
  36427. };
  36428. return PushMaterial;
  36429. }(BABYLON.Material));
  36430. BABYLON.PushMaterial = PushMaterial;
  36431. })(BABYLON || (BABYLON = {}));
  36432. //# sourceMappingURL=babylon.pushMaterial.js.map
  36433. var BABYLON;
  36434. (function (BABYLON) {
  36435. var StandardMaterialDefines = /** @class */ (function (_super) {
  36436. __extends(StandardMaterialDefines, _super);
  36437. function StandardMaterialDefines() {
  36438. var _this = _super.call(this) || this;
  36439. _this.MAINUV1 = false;
  36440. _this.MAINUV2 = false;
  36441. _this.DIFFUSE = false;
  36442. _this.DIFFUSEDIRECTUV = 0;
  36443. _this.AMBIENT = false;
  36444. _this.AMBIENTDIRECTUV = 0;
  36445. _this.OPACITY = false;
  36446. _this.OPACITYDIRECTUV = 0;
  36447. _this.OPACITYRGB = false;
  36448. _this.REFLECTION = false;
  36449. _this.EMISSIVE = false;
  36450. _this.EMISSIVEDIRECTUV = 0;
  36451. _this.SPECULAR = false;
  36452. _this.SPECULARDIRECTUV = 0;
  36453. _this.BUMP = false;
  36454. _this.BUMPDIRECTUV = 0;
  36455. _this.PARALLAX = false;
  36456. _this.PARALLAXOCCLUSION = false;
  36457. _this.SPECULAROVERALPHA = false;
  36458. _this.CLIPPLANE = false;
  36459. _this.ALPHATEST = false;
  36460. _this.DEPTHPREPASS = false;
  36461. _this.ALPHAFROMDIFFUSE = false;
  36462. _this.POINTSIZE = false;
  36463. _this.FOG = false;
  36464. _this.SPECULARTERM = false;
  36465. _this.DIFFUSEFRESNEL = false;
  36466. _this.OPACITYFRESNEL = false;
  36467. _this.REFLECTIONFRESNEL = false;
  36468. _this.REFRACTIONFRESNEL = false;
  36469. _this.EMISSIVEFRESNEL = false;
  36470. _this.FRESNEL = false;
  36471. _this.NORMAL = false;
  36472. _this.UV1 = false;
  36473. _this.UV2 = false;
  36474. _this.VERTEXCOLOR = false;
  36475. _this.VERTEXALPHA = false;
  36476. _this.NUM_BONE_INFLUENCERS = 0;
  36477. _this.BonesPerMesh = 0;
  36478. _this.INSTANCES = false;
  36479. _this.GLOSSINESS = false;
  36480. _this.ROUGHNESS = false;
  36481. _this.EMISSIVEASILLUMINATION = false;
  36482. _this.LINKEMISSIVEWITHDIFFUSE = false;
  36483. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  36484. _this.LIGHTMAP = false;
  36485. _this.LIGHTMAPDIRECTUV = 0;
  36486. _this.USELIGHTMAPASSHADOWMAP = false;
  36487. _this.REFLECTIONMAP_3D = false;
  36488. _this.REFLECTIONMAP_SPHERICAL = false;
  36489. _this.REFLECTIONMAP_PLANAR = false;
  36490. _this.REFLECTIONMAP_CUBIC = false;
  36491. _this.REFLECTIONMAP_PROJECTION = false;
  36492. _this.REFLECTIONMAP_SKYBOX = false;
  36493. _this.REFLECTIONMAP_EXPLICIT = false;
  36494. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36495. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36496. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36497. _this.INVERTCUBICMAP = false;
  36498. _this.LOGARITHMICDEPTH = false;
  36499. _this.REFRACTION = false;
  36500. _this.REFRACTIONMAP_3D = false;
  36501. _this.REFLECTIONOVERALPHA = false;
  36502. _this.TWOSIDEDLIGHTING = false;
  36503. _this.SHADOWFLOAT = false;
  36504. _this.MORPHTARGETS = false;
  36505. _this.MORPHTARGETS_NORMAL = false;
  36506. _this.MORPHTARGETS_TANGENT = false;
  36507. _this.NUM_MORPH_INFLUENCERS = 0;
  36508. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  36509. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  36510. _this.IMAGEPROCESSING = false;
  36511. _this.VIGNETTE = false;
  36512. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36513. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36514. _this.TONEMAPPING = false;
  36515. _this.CONTRAST = false;
  36516. _this.COLORCURVES = false;
  36517. _this.COLORGRADING = false;
  36518. _this.COLORGRADING3D = false;
  36519. _this.SAMPLER3DGREENDEPTH = false;
  36520. _this.SAMPLER3DBGRMAP = false;
  36521. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36522. _this.EXPOSURE = false;
  36523. _this.rebuild();
  36524. return _this;
  36525. }
  36526. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  36527. var modes = [
  36528. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  36529. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  36530. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  36531. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  36532. ];
  36533. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  36534. var mode = modes_1[_i];
  36535. this[mode] = (mode === modeToEnable);
  36536. }
  36537. };
  36538. return StandardMaterialDefines;
  36539. }(BABYLON.MaterialDefines));
  36540. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  36541. var StandardMaterial = /** @class */ (function (_super) {
  36542. __extends(StandardMaterial, _super);
  36543. function StandardMaterial(name, scene) {
  36544. var _this = _super.call(this, name, scene) || this;
  36545. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36546. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  36547. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  36548. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36549. _this.specularPower = 64;
  36550. _this._useAlphaFromDiffuseTexture = false;
  36551. _this._useEmissiveAsIllumination = false;
  36552. _this._linkEmissiveWithDiffuse = false;
  36553. _this._useSpecularOverAlpha = false;
  36554. _this._useReflectionOverAlpha = false;
  36555. _this._disableLighting = false;
  36556. _this._useParallax = false;
  36557. _this._useParallaxOcclusion = false;
  36558. _this.parallaxScaleBias = 0.05;
  36559. _this._roughness = 0;
  36560. _this.indexOfRefraction = 0.98;
  36561. _this.invertRefractionY = true;
  36562. _this._useLightmapAsShadowmap = false;
  36563. _this._useReflectionFresnelFromSpecular = false;
  36564. _this._useGlossinessFromSpecularMapAlpha = false;
  36565. _this._maxSimultaneousLights = 4;
  36566. /**
  36567. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36568. */
  36569. _this._invertNormalMapX = false;
  36570. /**
  36571. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36572. */
  36573. _this._invertNormalMapY = false;
  36574. /**
  36575. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36576. */
  36577. _this._twoSidedLighting = false;
  36578. _this._renderTargets = new BABYLON.SmartArray(16);
  36579. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  36580. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36581. // Setup the default processing configuration to the scene.
  36582. _this._attachImageProcessingConfiguration(null);
  36583. _this.getRenderTargetTextures = function () {
  36584. _this._renderTargets.reset();
  36585. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36586. _this._renderTargets.push(_this._reflectionTexture);
  36587. }
  36588. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36589. _this._renderTargets.push(_this._refractionTexture);
  36590. }
  36591. return _this._renderTargets;
  36592. };
  36593. return _this;
  36594. }
  36595. ;
  36596. ;
  36597. ;
  36598. ;
  36599. ;
  36600. ;
  36601. ;
  36602. ;
  36603. ;
  36604. ;
  36605. ;
  36606. ;
  36607. ;
  36608. ;
  36609. ;
  36610. ;
  36611. ;
  36612. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  36613. /**
  36614. * Gets the image processing configuration used either in this material.
  36615. */
  36616. get: function () {
  36617. return this._imageProcessingConfiguration;
  36618. },
  36619. /**
  36620. * Sets the Default image processing configuration used either in the this material.
  36621. *
  36622. * If sets to null, the scene one is in use.
  36623. */
  36624. set: function (value) {
  36625. this._attachImageProcessingConfiguration(value);
  36626. // Ensure the effect will be rebuilt.
  36627. this._markAllSubMeshesAsTexturesDirty();
  36628. },
  36629. enumerable: true,
  36630. configurable: true
  36631. });
  36632. /**
  36633. * Attaches a new image processing configuration to the Standard Material.
  36634. * @param configuration
  36635. */
  36636. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36637. var _this = this;
  36638. if (configuration === this._imageProcessingConfiguration) {
  36639. return;
  36640. }
  36641. // Detaches observer.
  36642. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36643. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36644. }
  36645. // Pick the scene configuration if needed.
  36646. if (!configuration) {
  36647. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36648. }
  36649. else {
  36650. this._imageProcessingConfiguration = configuration;
  36651. }
  36652. // Attaches observer.
  36653. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36654. _this._markAllSubMeshesAsImageProcessingDirty();
  36655. });
  36656. };
  36657. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  36658. /**
  36659. * Gets wether the color curves effect is enabled.
  36660. */
  36661. get: function () {
  36662. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36663. },
  36664. /**
  36665. * Sets wether the color curves effect is enabled.
  36666. */
  36667. set: function (value) {
  36668. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36669. },
  36670. enumerable: true,
  36671. configurable: true
  36672. });
  36673. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  36674. /**
  36675. * Gets wether the color grading effect is enabled.
  36676. */
  36677. get: function () {
  36678. return this.imageProcessingConfiguration.colorGradingEnabled;
  36679. },
  36680. /**
  36681. * Gets wether the color grading effect is enabled.
  36682. */
  36683. set: function (value) {
  36684. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36685. },
  36686. enumerable: true,
  36687. configurable: true
  36688. });
  36689. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  36690. /**
  36691. * Gets wether tonemapping is enabled or not.
  36692. */
  36693. get: function () {
  36694. return this._imageProcessingConfiguration.toneMappingEnabled;
  36695. },
  36696. /**
  36697. * Sets wether tonemapping is enabled or not
  36698. */
  36699. set: function (value) {
  36700. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36701. },
  36702. enumerable: true,
  36703. configurable: true
  36704. });
  36705. ;
  36706. ;
  36707. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  36708. /**
  36709. * The camera exposure used on this material.
  36710. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36711. * This corresponds to a photographic exposure.
  36712. */
  36713. get: function () {
  36714. return this._imageProcessingConfiguration.exposure;
  36715. },
  36716. /**
  36717. * The camera exposure used on this material.
  36718. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36719. * This corresponds to a photographic exposure.
  36720. */
  36721. set: function (value) {
  36722. this._imageProcessingConfiguration.exposure = value;
  36723. },
  36724. enumerable: true,
  36725. configurable: true
  36726. });
  36727. ;
  36728. ;
  36729. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  36730. /**
  36731. * Gets The camera contrast used on this material.
  36732. */
  36733. get: function () {
  36734. return this._imageProcessingConfiguration.contrast;
  36735. },
  36736. /**
  36737. * Sets The camera contrast used on this material.
  36738. */
  36739. set: function (value) {
  36740. this._imageProcessingConfiguration.contrast = value;
  36741. },
  36742. enumerable: true,
  36743. configurable: true
  36744. });
  36745. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  36746. /**
  36747. * Gets the Color Grading 2D Lookup Texture.
  36748. */
  36749. get: function () {
  36750. return this._imageProcessingConfiguration.colorGradingTexture;
  36751. },
  36752. /**
  36753. * Sets the Color Grading 2D Lookup Texture.
  36754. */
  36755. set: function (value) {
  36756. this._imageProcessingConfiguration.colorGradingTexture = value;
  36757. },
  36758. enumerable: true,
  36759. configurable: true
  36760. });
  36761. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  36762. /**
  36763. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36764. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36765. * 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;
  36766. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36767. */
  36768. get: function () {
  36769. return this._imageProcessingConfiguration.colorCurves;
  36770. },
  36771. /**
  36772. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36773. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36774. * 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;
  36775. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36776. */
  36777. set: function (value) {
  36778. this._imageProcessingConfiguration.colorCurves = value;
  36779. },
  36780. enumerable: true,
  36781. configurable: true
  36782. });
  36783. StandardMaterial.prototype.getClassName = function () {
  36784. return "StandardMaterial";
  36785. };
  36786. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  36787. get: function () {
  36788. return this._useLogarithmicDepth;
  36789. },
  36790. set: function (value) {
  36791. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36792. this._markAllSubMeshesAsMiscDirty();
  36793. },
  36794. enumerable: true,
  36795. configurable: true
  36796. });
  36797. StandardMaterial.prototype.needAlphaBlending = function () {
  36798. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  36799. };
  36800. StandardMaterial.prototype.needAlphaTesting = function () {
  36801. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  36802. };
  36803. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  36804. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  36805. };
  36806. StandardMaterial.prototype.getAlphaTestTexture = function () {
  36807. return this._diffuseTexture;
  36808. };
  36809. /**
  36810. * Child classes can use it to update shaders
  36811. */
  36812. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36813. if (useInstances === void 0) { useInstances = false; }
  36814. if (subMesh.effect && this.isFrozen) {
  36815. if (this._wasPreviouslyReady && subMesh.effect) {
  36816. return true;
  36817. }
  36818. }
  36819. if (!subMesh._materialDefines) {
  36820. subMesh._materialDefines = new StandardMaterialDefines();
  36821. }
  36822. var scene = this.getScene();
  36823. var defines = subMesh._materialDefines;
  36824. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36825. if (defines._renderId === scene.getRenderId()) {
  36826. return true;
  36827. }
  36828. }
  36829. var engine = scene.getEngine();
  36830. // Lights
  36831. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36832. // Textures
  36833. if (defines._areTexturesDirty) {
  36834. defines._needUVs = false;
  36835. defines.MAINUV1 = false;
  36836. defines.MAINUV2 = false;
  36837. if (scene.texturesEnabled) {
  36838. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36839. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  36840. return false;
  36841. }
  36842. else {
  36843. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  36844. }
  36845. }
  36846. else {
  36847. defines.DIFFUSE = false;
  36848. }
  36849. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36850. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36851. return false;
  36852. }
  36853. else {
  36854. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36855. }
  36856. }
  36857. else {
  36858. defines.AMBIENT = false;
  36859. }
  36860. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36861. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36862. return false;
  36863. }
  36864. else {
  36865. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36866. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36867. }
  36868. }
  36869. else {
  36870. defines.OPACITY = false;
  36871. }
  36872. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36873. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  36874. return false;
  36875. }
  36876. else {
  36877. defines._needNormals = true;
  36878. defines.REFLECTION = true;
  36879. defines.ROUGHNESS = (this._roughness > 0);
  36880. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  36881. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  36882. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  36883. switch (this._reflectionTexture.coordinatesMode) {
  36884. case BABYLON.Texture.CUBIC_MODE:
  36885. case BABYLON.Texture.INVCUBIC_MODE:
  36886. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  36887. break;
  36888. case BABYLON.Texture.EXPLICIT_MODE:
  36889. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  36890. break;
  36891. case BABYLON.Texture.PLANAR_MODE:
  36892. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  36893. break;
  36894. case BABYLON.Texture.PROJECTION_MODE:
  36895. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  36896. break;
  36897. case BABYLON.Texture.SKYBOX_MODE:
  36898. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  36899. break;
  36900. case BABYLON.Texture.SPHERICAL_MODE:
  36901. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  36902. break;
  36903. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36904. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  36905. break;
  36906. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36907. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  36908. break;
  36909. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36910. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  36911. break;
  36912. }
  36913. }
  36914. }
  36915. else {
  36916. defines.REFLECTION = false;
  36917. }
  36918. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36919. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36920. return false;
  36921. }
  36922. else {
  36923. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36924. }
  36925. }
  36926. else {
  36927. defines.EMISSIVE = false;
  36928. }
  36929. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36930. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36931. return false;
  36932. }
  36933. else {
  36934. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36935. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36936. }
  36937. }
  36938. else {
  36939. defines.LIGHTMAP = false;
  36940. }
  36941. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36942. if (!this._specularTexture.isReadyOrNotBlocking()) {
  36943. return false;
  36944. }
  36945. else {
  36946. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  36947. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  36948. }
  36949. }
  36950. else {
  36951. defines.SPECULAR = false;
  36952. }
  36953. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  36954. // Bump texure can not be not blocking.
  36955. if (!this._bumpTexture.isReady()) {
  36956. return false;
  36957. }
  36958. else {
  36959. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36960. defines.PARALLAX = this._useParallax;
  36961. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  36962. }
  36963. }
  36964. else {
  36965. defines.BUMP = false;
  36966. }
  36967. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36968. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  36969. return false;
  36970. }
  36971. else {
  36972. defines._needUVs = true;
  36973. defines.REFRACTION = true;
  36974. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  36975. }
  36976. }
  36977. else {
  36978. defines.REFRACTION = false;
  36979. }
  36980. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  36981. }
  36982. else {
  36983. defines.DIFFUSE = false;
  36984. defines.AMBIENT = false;
  36985. defines.OPACITY = false;
  36986. defines.REFLECTION = false;
  36987. defines.EMISSIVE = false;
  36988. defines.LIGHTMAP = false;
  36989. defines.BUMP = false;
  36990. defines.REFRACTION = false;
  36991. }
  36992. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  36993. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  36994. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  36995. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36996. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36997. }
  36998. if (defines._areImageProcessingDirty) {
  36999. if (!this._imageProcessingConfiguration.isReady()) {
  37000. return false;
  37001. }
  37002. this._imageProcessingConfiguration.prepareDefines(defines);
  37003. }
  37004. if (defines._areFresnelDirty) {
  37005. if (StandardMaterial.FresnelEnabled) {
  37006. // Fresnel
  37007. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  37008. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  37009. this._reflectionFresnelParameters) {
  37010. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  37011. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  37012. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  37013. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  37014. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  37015. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  37016. defines._needNormals = true;
  37017. defines.FRESNEL = true;
  37018. }
  37019. }
  37020. else {
  37021. defines.FRESNEL = false;
  37022. }
  37023. }
  37024. // Misc.
  37025. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  37026. // Attribs
  37027. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  37028. // Values that need to be evaluated on every frame
  37029. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  37030. // Get correct effect
  37031. if (defines.isDirty) {
  37032. defines.markAsProcessed();
  37033. scene.resetCachedMaterial();
  37034. // Fallbacks
  37035. var fallbacks = new BABYLON.EffectFallbacks();
  37036. if (defines.REFLECTION) {
  37037. fallbacks.addFallback(0, "REFLECTION");
  37038. }
  37039. if (defines.SPECULAR) {
  37040. fallbacks.addFallback(0, "SPECULAR");
  37041. }
  37042. if (defines.BUMP) {
  37043. fallbacks.addFallback(0, "BUMP");
  37044. }
  37045. if (defines.PARALLAX) {
  37046. fallbacks.addFallback(1, "PARALLAX");
  37047. }
  37048. if (defines.PARALLAXOCCLUSION) {
  37049. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  37050. }
  37051. if (defines.SPECULAROVERALPHA) {
  37052. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  37053. }
  37054. if (defines.FOG) {
  37055. fallbacks.addFallback(1, "FOG");
  37056. }
  37057. if (defines.POINTSIZE) {
  37058. fallbacks.addFallback(0, "POINTSIZE");
  37059. }
  37060. if (defines.LOGARITHMICDEPTH) {
  37061. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  37062. }
  37063. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  37064. if (defines.SPECULARTERM) {
  37065. fallbacks.addFallback(0, "SPECULARTERM");
  37066. }
  37067. if (defines.DIFFUSEFRESNEL) {
  37068. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  37069. }
  37070. if (defines.OPACITYFRESNEL) {
  37071. fallbacks.addFallback(2, "OPACITYFRESNEL");
  37072. }
  37073. if (defines.REFLECTIONFRESNEL) {
  37074. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  37075. }
  37076. if (defines.EMISSIVEFRESNEL) {
  37077. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  37078. }
  37079. if (defines.FRESNEL) {
  37080. fallbacks.addFallback(4, "FRESNEL");
  37081. }
  37082. //Attributes
  37083. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37084. if (defines.NORMAL) {
  37085. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37086. }
  37087. if (defines.UV1) {
  37088. attribs.push(BABYLON.VertexBuffer.UVKind);
  37089. }
  37090. if (defines.UV2) {
  37091. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37092. }
  37093. if (defines.VERTEXCOLOR) {
  37094. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37095. }
  37096. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37097. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37098. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37099. var shaderName = "default";
  37100. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  37101. "vFogInfos", "vFogColor", "pointSize",
  37102. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37103. "mBones",
  37104. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37105. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  37106. "logarithmicDepthConstant", "vTangentSpaceParams"
  37107. ];
  37108. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  37109. var uniformBuffers = ["Material", "Scene"];
  37110. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37111. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37112. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37113. uniformsNames: uniforms,
  37114. uniformBuffersNames: uniformBuffers,
  37115. samplers: samplers,
  37116. defines: defines,
  37117. maxSimultaneousLights: this._maxSimultaneousLights
  37118. });
  37119. if (this.customShaderNameResolve) {
  37120. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  37121. }
  37122. var join = defines.toString();
  37123. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  37124. attributes: attribs,
  37125. uniformsNames: uniforms,
  37126. uniformBuffersNames: uniformBuffers,
  37127. samplers: samplers,
  37128. defines: join,
  37129. fallbacks: fallbacks,
  37130. onCompiled: this.onCompiled,
  37131. onError: this.onError,
  37132. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37133. }, engine), defines);
  37134. this.buildUniformLayout();
  37135. }
  37136. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37137. return false;
  37138. }
  37139. defines._renderId = scene.getRenderId();
  37140. this._wasPreviouslyReady = true;
  37141. return true;
  37142. };
  37143. StandardMaterial.prototype.buildUniformLayout = function () {
  37144. // Order is important !
  37145. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  37146. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  37147. this._uniformBuffer.addUniform("opacityParts", 4);
  37148. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  37149. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  37150. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  37151. this._uniformBuffer.addUniform("refractionRightColor", 4);
  37152. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  37153. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  37154. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  37155. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  37156. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37157. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37158. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37159. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37160. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  37161. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37162. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  37163. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37164. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37165. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37166. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37167. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37168. this._uniformBuffer.addUniform("specularMatrix", 16);
  37169. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37170. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37171. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37172. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37173. this._uniformBuffer.addUniform("vSpecularColor", 4);
  37174. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37175. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  37176. this._uniformBuffer.addUniform("pointSize", 1);
  37177. this._uniformBuffer.create();
  37178. };
  37179. StandardMaterial.prototype.unbind = function () {
  37180. if (this._activeEffect) {
  37181. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37182. this._activeEffect.setTexture("reflection2DSampler", null);
  37183. }
  37184. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37185. this._activeEffect.setTexture("refraction2DSampler", null);
  37186. }
  37187. }
  37188. _super.prototype.unbind.call(this);
  37189. };
  37190. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37191. var scene = this.getScene();
  37192. var defines = subMesh._materialDefines;
  37193. if (!defines) {
  37194. return;
  37195. }
  37196. var effect = subMesh.effect;
  37197. if (!effect) {
  37198. return;
  37199. }
  37200. this._activeEffect = effect;
  37201. // Matrices
  37202. this.bindOnlyWorldMatrix(world);
  37203. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37204. // Bones
  37205. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  37206. if (mustRebind) {
  37207. this._uniformBuffer.bindToEffect(effect, "Material");
  37208. this.bindViewProjection(effect);
  37209. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37210. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  37211. // Fresnel
  37212. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  37213. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  37214. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  37215. }
  37216. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  37217. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  37218. }
  37219. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  37220. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  37221. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  37222. }
  37223. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  37224. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  37225. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  37226. }
  37227. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  37228. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  37229. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  37230. }
  37231. }
  37232. // Textures
  37233. if (scene.texturesEnabled) {
  37234. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37235. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  37236. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  37237. }
  37238. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37239. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  37240. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37241. }
  37242. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37243. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37244. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37245. }
  37246. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37247. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  37248. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  37249. }
  37250. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37251. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37252. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37253. }
  37254. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37255. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37256. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37257. }
  37258. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37259. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  37260. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  37261. }
  37262. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37263. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  37264. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37265. if (scene._mirroredCameraPosition) {
  37266. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37267. }
  37268. else {
  37269. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37270. }
  37271. }
  37272. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37273. var depth = 1.0;
  37274. if (!this._refractionTexture.isCube) {
  37275. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  37276. if (this._refractionTexture.depth) {
  37277. depth = this._refractionTexture.depth;
  37278. }
  37279. }
  37280. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  37281. }
  37282. }
  37283. // Point size
  37284. if (this.pointsCloud) {
  37285. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37286. }
  37287. if (defines.SPECULARTERM) {
  37288. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  37289. }
  37290. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  37291. // Diffuse
  37292. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  37293. }
  37294. // Textures
  37295. if (scene.texturesEnabled) {
  37296. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37297. effect.setTexture("diffuseSampler", this._diffuseTexture);
  37298. }
  37299. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37300. effect.setTexture("ambientSampler", this._ambientTexture);
  37301. }
  37302. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37303. effect.setTexture("opacitySampler", this._opacityTexture);
  37304. }
  37305. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37306. if (this._reflectionTexture.isCube) {
  37307. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  37308. }
  37309. else {
  37310. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  37311. }
  37312. }
  37313. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37314. effect.setTexture("emissiveSampler", this._emissiveTexture);
  37315. }
  37316. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37317. effect.setTexture("lightmapSampler", this._lightmapTexture);
  37318. }
  37319. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37320. effect.setTexture("specularSampler", this._specularTexture);
  37321. }
  37322. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37323. effect.setTexture("bumpSampler", this._bumpTexture);
  37324. }
  37325. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37326. var depth = 1.0;
  37327. if (this._refractionTexture.isCube) {
  37328. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  37329. }
  37330. else {
  37331. effect.setTexture("refraction2DSampler", this._refractionTexture);
  37332. }
  37333. }
  37334. }
  37335. // Clip plane
  37336. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  37337. // Colors
  37338. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  37339. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  37340. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37341. }
  37342. if (mustRebind || !this.isFrozen) {
  37343. // Lights
  37344. if (scene.lightsEnabled && !this._disableLighting) {
  37345. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  37346. }
  37347. // View
  37348. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  37349. this.bindView(effect);
  37350. }
  37351. // Fog
  37352. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  37353. // Morph targets
  37354. if (defines.NUM_MORPH_INFLUENCERS) {
  37355. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  37356. }
  37357. // Log. depth
  37358. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  37359. // image processing
  37360. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  37361. this._imageProcessingConfiguration.bind(this._activeEffect);
  37362. }
  37363. }
  37364. this._uniformBuffer.update();
  37365. this._afterBind(mesh, this._activeEffect);
  37366. };
  37367. StandardMaterial.prototype.getAnimatables = function () {
  37368. var results = [];
  37369. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  37370. results.push(this._diffuseTexture);
  37371. }
  37372. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37373. results.push(this._ambientTexture);
  37374. }
  37375. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37376. results.push(this._opacityTexture);
  37377. }
  37378. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37379. results.push(this._reflectionTexture);
  37380. }
  37381. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37382. results.push(this._emissiveTexture);
  37383. }
  37384. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  37385. results.push(this._specularTexture);
  37386. }
  37387. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37388. results.push(this._bumpTexture);
  37389. }
  37390. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37391. results.push(this._lightmapTexture);
  37392. }
  37393. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37394. results.push(this._refractionTexture);
  37395. }
  37396. return results;
  37397. };
  37398. StandardMaterial.prototype.getActiveTextures = function () {
  37399. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37400. if (this._diffuseTexture) {
  37401. activeTextures.push(this._diffuseTexture);
  37402. }
  37403. if (this._ambientTexture) {
  37404. activeTextures.push(this._ambientTexture);
  37405. }
  37406. if (this._opacityTexture) {
  37407. activeTextures.push(this._opacityTexture);
  37408. }
  37409. if (this._reflectionTexture) {
  37410. activeTextures.push(this._reflectionTexture);
  37411. }
  37412. if (this._emissiveTexture) {
  37413. activeTextures.push(this._emissiveTexture);
  37414. }
  37415. if (this._specularTexture) {
  37416. activeTextures.push(this._specularTexture);
  37417. }
  37418. if (this._bumpTexture) {
  37419. activeTextures.push(this._bumpTexture);
  37420. }
  37421. if (this._lightmapTexture) {
  37422. activeTextures.push(this._lightmapTexture);
  37423. }
  37424. if (this._refractionTexture) {
  37425. activeTextures.push(this._refractionTexture);
  37426. }
  37427. return activeTextures;
  37428. };
  37429. StandardMaterial.prototype.hasTexture = function (texture) {
  37430. if (_super.prototype.hasTexture.call(this, texture)) {
  37431. return true;
  37432. }
  37433. if (this._diffuseTexture === texture) {
  37434. return true;
  37435. }
  37436. if (this._ambientTexture === texture) {
  37437. return true;
  37438. }
  37439. if (this._opacityTexture === texture) {
  37440. return true;
  37441. }
  37442. if (this._reflectionTexture === texture) {
  37443. return true;
  37444. }
  37445. if (this._emissiveTexture === texture) {
  37446. return true;
  37447. }
  37448. if (this._specularTexture === texture) {
  37449. return true;
  37450. }
  37451. if (this._bumpTexture === texture) {
  37452. return true;
  37453. }
  37454. if (this._lightmapTexture === texture) {
  37455. return true;
  37456. }
  37457. if (this._refractionTexture === texture) {
  37458. return true;
  37459. }
  37460. return false;
  37461. };
  37462. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37463. if (forceDisposeTextures) {
  37464. if (this._diffuseTexture) {
  37465. this._diffuseTexture.dispose();
  37466. }
  37467. if (this._ambientTexture) {
  37468. this._ambientTexture.dispose();
  37469. }
  37470. if (this._opacityTexture) {
  37471. this._opacityTexture.dispose();
  37472. }
  37473. if (this._reflectionTexture) {
  37474. this._reflectionTexture.dispose();
  37475. }
  37476. if (this._emissiveTexture) {
  37477. this._emissiveTexture.dispose();
  37478. }
  37479. if (this._specularTexture) {
  37480. this._specularTexture.dispose();
  37481. }
  37482. if (this._bumpTexture) {
  37483. this._bumpTexture.dispose();
  37484. }
  37485. if (this._lightmapTexture) {
  37486. this._lightmapTexture.dispose();
  37487. }
  37488. if (this._refractionTexture) {
  37489. this._refractionTexture.dispose();
  37490. }
  37491. }
  37492. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37493. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37494. }
  37495. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37496. };
  37497. StandardMaterial.prototype.clone = function (name) {
  37498. var _this = this;
  37499. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  37500. result.name = name;
  37501. result.id = name;
  37502. return result;
  37503. };
  37504. StandardMaterial.prototype.serialize = function () {
  37505. return BABYLON.SerializationHelper.Serialize(this);
  37506. };
  37507. // Statics
  37508. StandardMaterial.Parse = function (source, scene, rootUrl) {
  37509. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  37510. };
  37511. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  37512. get: function () {
  37513. return StandardMaterial._DiffuseTextureEnabled;
  37514. },
  37515. set: function (value) {
  37516. if (StandardMaterial._DiffuseTextureEnabled === value) {
  37517. return;
  37518. }
  37519. StandardMaterial._DiffuseTextureEnabled = value;
  37520. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37521. },
  37522. enumerable: true,
  37523. configurable: true
  37524. });
  37525. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  37526. get: function () {
  37527. return StandardMaterial._AmbientTextureEnabled;
  37528. },
  37529. set: function (value) {
  37530. if (StandardMaterial._AmbientTextureEnabled === value) {
  37531. return;
  37532. }
  37533. StandardMaterial._AmbientTextureEnabled = value;
  37534. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37535. },
  37536. enumerable: true,
  37537. configurable: true
  37538. });
  37539. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  37540. get: function () {
  37541. return StandardMaterial._OpacityTextureEnabled;
  37542. },
  37543. set: function (value) {
  37544. if (StandardMaterial._OpacityTextureEnabled === value) {
  37545. return;
  37546. }
  37547. StandardMaterial._OpacityTextureEnabled = value;
  37548. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37549. },
  37550. enumerable: true,
  37551. configurable: true
  37552. });
  37553. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  37554. get: function () {
  37555. return StandardMaterial._ReflectionTextureEnabled;
  37556. },
  37557. set: function (value) {
  37558. if (StandardMaterial._ReflectionTextureEnabled === value) {
  37559. return;
  37560. }
  37561. StandardMaterial._ReflectionTextureEnabled = value;
  37562. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37563. },
  37564. enumerable: true,
  37565. configurable: true
  37566. });
  37567. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  37568. get: function () {
  37569. return StandardMaterial._EmissiveTextureEnabled;
  37570. },
  37571. set: function (value) {
  37572. if (StandardMaterial._EmissiveTextureEnabled === value) {
  37573. return;
  37574. }
  37575. StandardMaterial._EmissiveTextureEnabled = value;
  37576. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37577. },
  37578. enumerable: true,
  37579. configurable: true
  37580. });
  37581. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  37582. get: function () {
  37583. return StandardMaterial._SpecularTextureEnabled;
  37584. },
  37585. set: function (value) {
  37586. if (StandardMaterial._SpecularTextureEnabled === value) {
  37587. return;
  37588. }
  37589. StandardMaterial._SpecularTextureEnabled = value;
  37590. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37591. },
  37592. enumerable: true,
  37593. configurable: true
  37594. });
  37595. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  37596. get: function () {
  37597. return StandardMaterial._BumpTextureEnabled;
  37598. },
  37599. set: function (value) {
  37600. if (StandardMaterial._BumpTextureEnabled === value) {
  37601. return;
  37602. }
  37603. StandardMaterial._BumpTextureEnabled = value;
  37604. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37605. },
  37606. enumerable: true,
  37607. configurable: true
  37608. });
  37609. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  37610. get: function () {
  37611. return StandardMaterial._LightmapTextureEnabled;
  37612. },
  37613. set: function (value) {
  37614. if (StandardMaterial._LightmapTextureEnabled === value) {
  37615. return;
  37616. }
  37617. StandardMaterial._LightmapTextureEnabled = value;
  37618. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37619. },
  37620. enumerable: true,
  37621. configurable: true
  37622. });
  37623. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  37624. get: function () {
  37625. return StandardMaterial._RefractionTextureEnabled;
  37626. },
  37627. set: function (value) {
  37628. if (StandardMaterial._RefractionTextureEnabled === value) {
  37629. return;
  37630. }
  37631. StandardMaterial._RefractionTextureEnabled = value;
  37632. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37633. },
  37634. enumerable: true,
  37635. configurable: true
  37636. });
  37637. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  37638. get: function () {
  37639. return StandardMaterial._ColorGradingTextureEnabled;
  37640. },
  37641. set: function (value) {
  37642. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  37643. return;
  37644. }
  37645. StandardMaterial._ColorGradingTextureEnabled = value;
  37646. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37647. },
  37648. enumerable: true,
  37649. configurable: true
  37650. });
  37651. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  37652. get: function () {
  37653. return StandardMaterial._FresnelEnabled;
  37654. },
  37655. set: function (value) {
  37656. if (StandardMaterial._FresnelEnabled === value) {
  37657. return;
  37658. }
  37659. StandardMaterial._FresnelEnabled = value;
  37660. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  37661. },
  37662. enumerable: true,
  37663. configurable: true
  37664. });
  37665. // Flags used to enable or disable a type of texture for all Standard Materials
  37666. StandardMaterial._DiffuseTextureEnabled = true;
  37667. StandardMaterial._AmbientTextureEnabled = true;
  37668. StandardMaterial._OpacityTextureEnabled = true;
  37669. StandardMaterial._ReflectionTextureEnabled = true;
  37670. StandardMaterial._EmissiveTextureEnabled = true;
  37671. StandardMaterial._SpecularTextureEnabled = true;
  37672. StandardMaterial._BumpTextureEnabled = true;
  37673. StandardMaterial._LightmapTextureEnabled = true;
  37674. StandardMaterial._RefractionTextureEnabled = true;
  37675. StandardMaterial._ColorGradingTextureEnabled = true;
  37676. StandardMaterial._FresnelEnabled = true;
  37677. __decorate([
  37678. BABYLON.serializeAsTexture("diffuseTexture")
  37679. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  37680. __decorate([
  37681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  37682. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  37683. __decorate([
  37684. BABYLON.serializeAsTexture("ambientTexture")
  37685. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  37686. __decorate([
  37687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37688. ], StandardMaterial.prototype, "ambientTexture", void 0);
  37689. __decorate([
  37690. BABYLON.serializeAsTexture("opacityTexture")
  37691. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  37692. __decorate([
  37693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  37694. ], StandardMaterial.prototype, "opacityTexture", void 0);
  37695. __decorate([
  37696. BABYLON.serializeAsTexture("reflectionTexture")
  37697. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  37698. __decorate([
  37699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37700. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  37701. __decorate([
  37702. BABYLON.serializeAsTexture("emissiveTexture")
  37703. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  37704. __decorate([
  37705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37706. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  37707. __decorate([
  37708. BABYLON.serializeAsTexture("specularTexture")
  37709. ], StandardMaterial.prototype, "_specularTexture", void 0);
  37710. __decorate([
  37711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37712. ], StandardMaterial.prototype, "specularTexture", void 0);
  37713. __decorate([
  37714. BABYLON.serializeAsTexture("bumpTexture")
  37715. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  37716. __decorate([
  37717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37718. ], StandardMaterial.prototype, "bumpTexture", void 0);
  37719. __decorate([
  37720. BABYLON.serializeAsTexture("lightmapTexture")
  37721. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  37722. __decorate([
  37723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37724. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  37725. __decorate([
  37726. BABYLON.serializeAsTexture("refractionTexture")
  37727. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  37728. __decorate([
  37729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37730. ], StandardMaterial.prototype, "refractionTexture", void 0);
  37731. __decorate([
  37732. BABYLON.serializeAsColor3("ambient")
  37733. ], StandardMaterial.prototype, "ambientColor", void 0);
  37734. __decorate([
  37735. BABYLON.serializeAsColor3("diffuse")
  37736. ], StandardMaterial.prototype, "diffuseColor", void 0);
  37737. __decorate([
  37738. BABYLON.serializeAsColor3("specular")
  37739. ], StandardMaterial.prototype, "specularColor", void 0);
  37740. __decorate([
  37741. BABYLON.serializeAsColor3("emissive")
  37742. ], StandardMaterial.prototype, "emissiveColor", void 0);
  37743. __decorate([
  37744. BABYLON.serialize()
  37745. ], StandardMaterial.prototype, "specularPower", void 0);
  37746. __decorate([
  37747. BABYLON.serialize("useAlphaFromDiffuseTexture")
  37748. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  37749. __decorate([
  37750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37751. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  37752. __decorate([
  37753. BABYLON.serialize("useEmissiveAsIllumination")
  37754. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  37755. __decorate([
  37756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37757. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  37758. __decorate([
  37759. BABYLON.serialize("linkEmissiveWithDiffuse")
  37760. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  37761. __decorate([
  37762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37763. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  37764. __decorate([
  37765. BABYLON.serialize("useSpecularOverAlpha")
  37766. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  37767. __decorate([
  37768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37769. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  37770. __decorate([
  37771. BABYLON.serialize("useReflectionOverAlpha")
  37772. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  37773. __decorate([
  37774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37775. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  37776. __decorate([
  37777. BABYLON.serialize("disableLighting")
  37778. ], StandardMaterial.prototype, "_disableLighting", void 0);
  37779. __decorate([
  37780. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37781. ], StandardMaterial.prototype, "disableLighting", void 0);
  37782. __decorate([
  37783. BABYLON.serialize("useParallax")
  37784. ], StandardMaterial.prototype, "_useParallax", void 0);
  37785. __decorate([
  37786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37787. ], StandardMaterial.prototype, "useParallax", void 0);
  37788. __decorate([
  37789. BABYLON.serialize("useParallaxOcclusion")
  37790. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  37791. __decorate([
  37792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37793. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  37794. __decorate([
  37795. BABYLON.serialize()
  37796. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  37797. __decorate([
  37798. BABYLON.serialize("roughness")
  37799. ], StandardMaterial.prototype, "_roughness", void 0);
  37800. __decorate([
  37801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37802. ], StandardMaterial.prototype, "roughness", void 0);
  37803. __decorate([
  37804. BABYLON.serialize()
  37805. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  37806. __decorate([
  37807. BABYLON.serialize()
  37808. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  37809. __decorate([
  37810. BABYLON.serialize("useLightmapAsShadowmap")
  37811. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  37812. __decorate([
  37813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37814. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37815. __decorate([
  37816. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  37817. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  37818. __decorate([
  37819. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37820. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  37821. __decorate([
  37822. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  37823. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  37824. __decorate([
  37825. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  37826. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  37827. __decorate([
  37828. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  37829. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  37830. __decorate([
  37831. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37832. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  37833. __decorate([
  37834. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  37835. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  37836. __decorate([
  37837. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37838. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  37839. __decorate([
  37840. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  37841. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  37842. __decorate([
  37843. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37844. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  37845. __decorate([
  37846. BABYLON.serialize("useReflectionFresnelFromSpecular")
  37847. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  37848. __decorate([
  37849. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37850. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  37851. __decorate([
  37852. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  37853. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  37854. __decorate([
  37855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37856. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  37857. __decorate([
  37858. BABYLON.serialize("maxSimultaneousLights")
  37859. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  37860. __decorate([
  37861. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37862. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  37863. __decorate([
  37864. BABYLON.serialize("invertNormalMapX")
  37865. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  37866. __decorate([
  37867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37868. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  37869. __decorate([
  37870. BABYLON.serialize("invertNormalMapY")
  37871. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  37872. __decorate([
  37873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37874. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  37875. __decorate([
  37876. BABYLON.serialize("twoSidedLighting")
  37877. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  37878. __decorate([
  37879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37880. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  37881. __decorate([
  37882. BABYLON.serialize()
  37883. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  37884. return StandardMaterial;
  37885. }(BABYLON.PushMaterial));
  37886. BABYLON.StandardMaterial = StandardMaterial;
  37887. })(BABYLON || (BABYLON = {}));
  37888. //# sourceMappingURL=babylon.standardMaterial.js.map
  37889. var BABYLON;
  37890. (function (BABYLON) {
  37891. var PBRMaterialDefines = /** @class */ (function (_super) {
  37892. __extends(PBRMaterialDefines, _super);
  37893. function PBRMaterialDefines() {
  37894. var _this = _super.call(this) || this;
  37895. _this.PBR = true;
  37896. _this.MAINUV1 = false;
  37897. _this.MAINUV2 = false;
  37898. _this.UV1 = false;
  37899. _this.UV2 = false;
  37900. _this.ALBEDO = false;
  37901. _this.ALBEDODIRECTUV = 0;
  37902. _this.VERTEXCOLOR = false;
  37903. _this.AMBIENT = false;
  37904. _this.AMBIENTDIRECTUV = 0;
  37905. _this.AMBIENTINGRAYSCALE = false;
  37906. _this.OPACITY = false;
  37907. _this.VERTEXALPHA = false;
  37908. _this.OPACITYDIRECTUV = 0;
  37909. _this.OPACITYRGB = false;
  37910. _this.ALPHATEST = false;
  37911. _this.DEPTHPREPASS = false;
  37912. _this.ALPHABLEND = false;
  37913. _this.ALPHAFROMALBEDO = false;
  37914. _this.ALPHATESTVALUE = 0.5;
  37915. _this.SPECULAROVERALPHA = false;
  37916. _this.RADIANCEOVERALPHA = false;
  37917. _this.ALPHAFRESNEL = false;
  37918. _this.LINEARALPHAFRESNEL = false;
  37919. _this.PREMULTIPLYALPHA = false;
  37920. _this.EMISSIVE = false;
  37921. _this.EMISSIVEDIRECTUV = 0;
  37922. _this.REFLECTIVITY = false;
  37923. _this.REFLECTIVITYDIRECTUV = 0;
  37924. _this.SPECULARTERM = false;
  37925. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  37926. _this.MICROSURFACEAUTOMATIC = false;
  37927. _this.LODBASEDMICROSFURACE = false;
  37928. _this.MICROSURFACEMAP = false;
  37929. _this.MICROSURFACEMAPDIRECTUV = 0;
  37930. _this.METALLICWORKFLOW = false;
  37931. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  37932. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  37933. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  37934. _this.AOSTOREINMETALMAPRED = false;
  37935. _this.ENVIRONMENTBRDF = false;
  37936. _this.NORMAL = false;
  37937. _this.TANGENT = false;
  37938. _this.BUMP = false;
  37939. _this.BUMPDIRECTUV = 0;
  37940. _this.PARALLAX = false;
  37941. _this.PARALLAXOCCLUSION = false;
  37942. _this.NORMALXYSCALE = true;
  37943. _this.LIGHTMAP = false;
  37944. _this.LIGHTMAPDIRECTUV = 0;
  37945. _this.USELIGHTMAPASSHADOWMAP = false;
  37946. _this.REFLECTION = false;
  37947. _this.REFLECTIONMAP_3D = false;
  37948. _this.REFLECTIONMAP_SPHERICAL = false;
  37949. _this.REFLECTIONMAP_PLANAR = false;
  37950. _this.REFLECTIONMAP_CUBIC = false;
  37951. _this.REFLECTIONMAP_PROJECTION = false;
  37952. _this.REFLECTIONMAP_SKYBOX = false;
  37953. _this.REFLECTIONMAP_EXPLICIT = false;
  37954. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37955. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37956. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37957. _this.INVERTCUBICMAP = false;
  37958. _this.USESPHERICALFROMREFLECTIONMAP = false;
  37959. _this.USESPHERICALINVERTEX = false;
  37960. _this.REFLECTIONMAP_OPPOSITEZ = false;
  37961. _this.LODINREFLECTIONALPHA = false;
  37962. _this.GAMMAREFLECTION = false;
  37963. _this.RADIANCEOCCLUSION = false;
  37964. _this.HORIZONOCCLUSION = false;
  37965. _this.REFRACTION = false;
  37966. _this.REFRACTIONMAP_3D = false;
  37967. _this.REFRACTIONMAP_OPPOSITEZ = false;
  37968. _this.LODINREFRACTIONALPHA = false;
  37969. _this.GAMMAREFRACTION = false;
  37970. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  37971. _this.INSTANCES = false;
  37972. _this.NUM_BONE_INFLUENCERS = 0;
  37973. _this.BonesPerMesh = 0;
  37974. _this.NONUNIFORMSCALING = false;
  37975. _this.MORPHTARGETS = false;
  37976. _this.MORPHTARGETS_NORMAL = false;
  37977. _this.MORPHTARGETS_TANGENT = false;
  37978. _this.NUM_MORPH_INFLUENCERS = 0;
  37979. _this.IMAGEPROCESSING = false;
  37980. _this.VIGNETTE = false;
  37981. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  37982. _this.VIGNETTEBLENDMODEOPAQUE = false;
  37983. _this.TONEMAPPING = false;
  37984. _this.CONTRAST = false;
  37985. _this.COLORCURVES = false;
  37986. _this.COLORGRADING = false;
  37987. _this.COLORGRADING3D = false;
  37988. _this.SAMPLER3DGREENDEPTH = false;
  37989. _this.SAMPLER3DBGRMAP = false;
  37990. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  37991. _this.EXPOSURE = false;
  37992. _this.USEPHYSICALLIGHTFALLOFF = false;
  37993. _this.TWOSIDEDLIGHTING = false;
  37994. _this.SHADOWFLOAT = false;
  37995. _this.CLIPPLANE = false;
  37996. _this.POINTSIZE = false;
  37997. _this.FOG = false;
  37998. _this.LOGARITHMICDEPTH = false;
  37999. _this.FORCENORMALFORWARD = false;
  38000. _this.rebuild();
  38001. return _this;
  38002. }
  38003. PBRMaterialDefines.prototype.reset = function () {
  38004. _super.prototype.reset.call(this);
  38005. this.ALPHATESTVALUE = 0.5;
  38006. this.PBR = true;
  38007. };
  38008. return PBRMaterialDefines;
  38009. }(BABYLON.MaterialDefines));
  38010. /**
  38011. * The Physically based material base class of BJS.
  38012. *
  38013. * This offers the main features of a standard PBR material.
  38014. * For more information, please refer to the documentation :
  38015. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38016. */
  38017. var PBRBaseMaterial = /** @class */ (function (_super) {
  38018. __extends(PBRBaseMaterial, _super);
  38019. /**
  38020. * Instantiates a new PBRMaterial instance.
  38021. *
  38022. * @param name The material name
  38023. * @param scene The scene the material will be use in.
  38024. */
  38025. function PBRBaseMaterial(name, scene) {
  38026. var _this = _super.call(this, name, scene) || this;
  38027. /**
  38028. * Intensity of the direct lights e.g. the four lights available in your scene.
  38029. * This impacts both the direct diffuse and specular highlights.
  38030. */
  38031. _this._directIntensity = 1.0;
  38032. /**
  38033. * Intensity of the emissive part of the material.
  38034. * This helps controlling the emissive effect without modifying the emissive color.
  38035. */
  38036. _this._emissiveIntensity = 1.0;
  38037. /**
  38038. * Intensity of the environment e.g. how much the environment will light the object
  38039. * either through harmonics for rough material or through the refelction for shiny ones.
  38040. */
  38041. _this._environmentIntensity = 1.0;
  38042. /**
  38043. * This is a special control allowing the reduction of the specular highlights coming from the
  38044. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38045. */
  38046. _this._specularIntensity = 1.0;
  38047. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  38048. /**
  38049. * Debug Control allowing disabling the bump map on this material.
  38050. */
  38051. _this._disableBumpMap = false;
  38052. /**
  38053. * AKA Occlusion Texture Intensity in other nomenclature.
  38054. */
  38055. _this._ambientTextureStrength = 1.0;
  38056. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  38057. /**
  38058. * AKA Diffuse Color in other nomenclature.
  38059. */
  38060. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  38061. /**
  38062. * AKA Specular Color in other nomenclature.
  38063. */
  38064. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38065. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  38066. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  38067. /**
  38068. * AKA Glossiness in other nomenclature.
  38069. */
  38070. _this._microSurface = 0.9;
  38071. /**
  38072. * source material index of refraction (IOR)' / 'destination material IOR.
  38073. */
  38074. _this._indexOfRefraction = 0.66;
  38075. /**
  38076. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38077. */
  38078. _this._invertRefractionY = false;
  38079. /**
  38080. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38081. * Materials half opaque for instance using refraction could benefit from this control.
  38082. */
  38083. _this._linkRefractionWithTransparency = false;
  38084. _this._useLightmapAsShadowmap = false;
  38085. /**
  38086. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38087. * makes the reflect vector face the model (under horizon).
  38088. */
  38089. _this._useHorizonOcclusion = true;
  38090. /**
  38091. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38092. * too much the area relying on ambient texture to define their ambient occlusion.
  38093. */
  38094. _this._useRadianceOcclusion = true;
  38095. /**
  38096. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  38097. */
  38098. _this._useAlphaFromAlbedoTexture = false;
  38099. /**
  38100. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38101. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38102. */
  38103. _this._useSpecularOverAlpha = true;
  38104. /**
  38105. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38106. */
  38107. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  38108. /**
  38109. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38110. */
  38111. _this._useRoughnessFromMetallicTextureAlpha = true;
  38112. /**
  38113. * Specifies if the metallic texture contains the roughness information in its green channel.
  38114. */
  38115. _this._useRoughnessFromMetallicTextureGreen = false;
  38116. /**
  38117. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38118. */
  38119. _this._useMetallnessFromMetallicTextureBlue = false;
  38120. /**
  38121. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38122. */
  38123. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  38124. /**
  38125. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38126. */
  38127. _this._useAmbientInGrayScale = false;
  38128. /**
  38129. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38130. * The material will try to infer what glossiness each pixel should be.
  38131. */
  38132. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  38133. /**
  38134. * BJS is using an harcoded light falloff based on a manually sets up range.
  38135. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38136. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38137. */
  38138. _this._usePhysicalLightFalloff = true;
  38139. /**
  38140. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38141. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38142. */
  38143. _this._useRadianceOverAlpha = true;
  38144. /**
  38145. * Allows using the bump map in parallax mode.
  38146. */
  38147. _this._useParallax = false;
  38148. /**
  38149. * Allows using the bump map in parallax occlusion mode.
  38150. */
  38151. _this._useParallaxOcclusion = false;
  38152. /**
  38153. * Controls the scale bias of the parallax mode.
  38154. */
  38155. _this._parallaxScaleBias = 0.05;
  38156. /**
  38157. * If sets to true, disables all the lights affecting the material.
  38158. */
  38159. _this._disableLighting = false;
  38160. /**
  38161. * Number of Simultaneous lights allowed on the material.
  38162. */
  38163. _this._maxSimultaneousLights = 4;
  38164. /**
  38165. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  38166. */
  38167. _this._invertNormalMapX = false;
  38168. /**
  38169. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  38170. */
  38171. _this._invertNormalMapY = false;
  38172. /**
  38173. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38174. */
  38175. _this._twoSidedLighting = false;
  38176. /**
  38177. * Defines the alpha limits in alpha test mode.
  38178. */
  38179. _this._alphaCutOff = 0.4;
  38180. /**
  38181. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38182. */
  38183. _this._forceAlphaTest = false;
  38184. /**
  38185. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38186. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38187. */
  38188. _this._useAlphaFresnel = false;
  38189. /**
  38190. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38191. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38192. */
  38193. _this._useLinearAlphaFresnel = false;
  38194. /**
  38195. * The transparency mode of the material.
  38196. */
  38197. _this._transparencyMode = null;
  38198. /**
  38199. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  38200. * from cos thetav and roughness:
  38201. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  38202. */
  38203. _this._environmentBRDFTexture = null;
  38204. /**
  38205. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38206. */
  38207. _this._forceIrradianceInFragment = false;
  38208. /**
  38209. * Force normal to face away from face.
  38210. */
  38211. _this._forceNormalForward = false;
  38212. /**
  38213. * Force metallic workflow.
  38214. */
  38215. _this._forceMetallicWorkflow = false;
  38216. _this._renderTargets = new BABYLON.SmartArray(16);
  38217. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38218. // Setup the default processing configuration to the scene.
  38219. _this._attachImageProcessingConfiguration(null);
  38220. _this.getRenderTargetTextures = function () {
  38221. _this._renderTargets.reset();
  38222. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38223. _this._renderTargets.push(_this._reflectionTexture);
  38224. }
  38225. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38226. _this._renderTargets.push(_this._refractionTexture);
  38227. }
  38228. return _this._renderTargets;
  38229. };
  38230. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38231. return _this;
  38232. }
  38233. /**
  38234. * Attaches a new image processing configuration to the PBR Material.
  38235. * @param configuration
  38236. */
  38237. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38238. var _this = this;
  38239. if (configuration === this._imageProcessingConfiguration) {
  38240. return;
  38241. }
  38242. // Detaches observer.
  38243. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38244. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38245. }
  38246. // Pick the scene configuration if needed.
  38247. if (!configuration) {
  38248. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38249. }
  38250. else {
  38251. this._imageProcessingConfiguration = configuration;
  38252. }
  38253. // Attaches observer.
  38254. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38255. _this._markAllSubMeshesAsImageProcessingDirty();
  38256. });
  38257. };
  38258. PBRBaseMaterial.prototype.getClassName = function () {
  38259. return "PBRBaseMaterial";
  38260. };
  38261. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  38262. get: function () {
  38263. return this._useLogarithmicDepth;
  38264. },
  38265. set: function (value) {
  38266. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38267. },
  38268. enumerable: true,
  38269. configurable: true
  38270. });
  38271. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  38272. /**
  38273. * Gets the current transparency mode.
  38274. */
  38275. get: function () {
  38276. return this._transparencyMode;
  38277. },
  38278. /**
  38279. * Sets the transparency mode of the material.
  38280. */
  38281. set: function (value) {
  38282. if (this._transparencyMode === value) {
  38283. return;
  38284. }
  38285. this._transparencyMode = value;
  38286. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  38287. this._markAllSubMeshesAsTexturesAndMiscDirty();
  38288. },
  38289. enumerable: true,
  38290. configurable: true
  38291. });
  38292. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  38293. /**
  38294. * Returns true if alpha blending should be disabled.
  38295. */
  38296. get: function () {
  38297. return (this._linkRefractionWithTransparency ||
  38298. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  38299. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38300. },
  38301. enumerable: true,
  38302. configurable: true
  38303. });
  38304. /**
  38305. * Specifies whether or not this material should be rendered in alpha blend mode.
  38306. */
  38307. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38308. if (this._disableAlphaBlending) {
  38309. return false;
  38310. }
  38311. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  38312. };
  38313. /**
  38314. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  38315. */
  38316. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  38317. if (this._disableAlphaBlending) {
  38318. return false;
  38319. }
  38320. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  38321. };
  38322. /**
  38323. * Specifies whether or not this material should be rendered in alpha test mode.
  38324. */
  38325. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38326. if (this._forceAlphaTest) {
  38327. return true;
  38328. }
  38329. if (this._linkRefractionWithTransparency) {
  38330. return false;
  38331. }
  38332. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38333. };
  38334. /**
  38335. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  38336. */
  38337. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38338. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38339. };
  38340. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38341. return this._albedoTexture;
  38342. };
  38343. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38344. var _this = this;
  38345. if (subMesh.effect && this.isFrozen) {
  38346. if (this._wasPreviouslyReady) {
  38347. return true;
  38348. }
  38349. }
  38350. if (!subMesh._materialDefines) {
  38351. subMesh._materialDefines = new PBRMaterialDefines();
  38352. }
  38353. var scene = this.getScene();
  38354. var defines = subMesh._materialDefines;
  38355. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38356. if (defines._renderId === scene.getRenderId()) {
  38357. return true;
  38358. }
  38359. }
  38360. var engine = scene.getEngine();
  38361. // Lights
  38362. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38363. defines._needNormals = true;
  38364. // Textures
  38365. if (defines._areTexturesDirty) {
  38366. defines._needUVs = false;
  38367. if (scene.texturesEnabled) {
  38368. if (scene.getEngine().getCaps().textureLOD) {
  38369. defines.LODBASEDMICROSFURACE = true;
  38370. }
  38371. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38372. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38373. return false;
  38374. }
  38375. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  38376. }
  38377. else {
  38378. defines.ALBEDO = false;
  38379. }
  38380. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38381. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38382. return false;
  38383. }
  38384. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38385. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38386. }
  38387. else {
  38388. defines.AMBIENT = false;
  38389. }
  38390. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38391. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38392. return false;
  38393. }
  38394. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38395. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38396. }
  38397. else {
  38398. defines.OPACITY = false;
  38399. }
  38400. var reflectionTexture = this._getReflectionTexture();
  38401. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38402. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38403. return false;
  38404. }
  38405. defines.REFLECTION = true;
  38406. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  38407. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  38408. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  38409. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38410. defines.INVERTCUBICMAP = true;
  38411. }
  38412. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38413. switch (reflectionTexture.coordinatesMode) {
  38414. case BABYLON.Texture.CUBIC_MODE:
  38415. case BABYLON.Texture.INVCUBIC_MODE:
  38416. defines.REFLECTIONMAP_CUBIC = true;
  38417. break;
  38418. case BABYLON.Texture.EXPLICIT_MODE:
  38419. defines.REFLECTIONMAP_EXPLICIT = true;
  38420. break;
  38421. case BABYLON.Texture.PLANAR_MODE:
  38422. defines.REFLECTIONMAP_PLANAR = true;
  38423. break;
  38424. case BABYLON.Texture.PROJECTION_MODE:
  38425. defines.REFLECTIONMAP_PROJECTION = true;
  38426. break;
  38427. case BABYLON.Texture.SKYBOX_MODE:
  38428. defines.REFLECTIONMAP_SKYBOX = true;
  38429. break;
  38430. case BABYLON.Texture.SPHERICAL_MODE:
  38431. defines.REFLECTIONMAP_SPHERICAL = true;
  38432. break;
  38433. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38434. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38435. break;
  38436. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38437. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38438. break;
  38439. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38440. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38441. break;
  38442. }
  38443. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  38444. if (reflectionTexture.sphericalPolynomial) {
  38445. defines.USESPHERICALFROMREFLECTIONMAP = true;
  38446. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  38447. defines.USESPHERICALINVERTEX = false;
  38448. }
  38449. else {
  38450. defines.USESPHERICALINVERTEX = true;
  38451. }
  38452. }
  38453. }
  38454. }
  38455. else {
  38456. defines.REFLECTION = false;
  38457. defines.REFLECTIONMAP_3D = false;
  38458. defines.REFLECTIONMAP_SPHERICAL = false;
  38459. defines.REFLECTIONMAP_PLANAR = false;
  38460. defines.REFLECTIONMAP_CUBIC = false;
  38461. defines.REFLECTIONMAP_PROJECTION = false;
  38462. defines.REFLECTIONMAP_SKYBOX = false;
  38463. defines.REFLECTIONMAP_EXPLICIT = false;
  38464. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38465. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38466. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38467. defines.INVERTCUBICMAP = false;
  38468. defines.USESPHERICALFROMREFLECTIONMAP = false;
  38469. defines.USESPHERICALINVERTEX = false;
  38470. defines.REFLECTIONMAP_OPPOSITEZ = false;
  38471. defines.LODINREFLECTIONALPHA = false;
  38472. defines.GAMMAREFLECTION = false;
  38473. }
  38474. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38475. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38476. return false;
  38477. }
  38478. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38479. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38480. }
  38481. else {
  38482. defines.LIGHTMAP = false;
  38483. }
  38484. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38485. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38486. return false;
  38487. }
  38488. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38489. }
  38490. else {
  38491. defines.EMISSIVE = false;
  38492. }
  38493. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38494. if (this._metallicTexture) {
  38495. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38496. return false;
  38497. }
  38498. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  38499. defines.METALLICWORKFLOW = true;
  38500. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38501. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38502. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38503. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38504. }
  38505. else if (this._reflectivityTexture) {
  38506. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38507. return false;
  38508. }
  38509. defines.METALLICWORKFLOW = false;
  38510. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  38511. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38512. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38513. }
  38514. else {
  38515. defines.METALLICWORKFLOW = false;
  38516. defines.REFLECTIVITY = false;
  38517. }
  38518. if (this._microSurfaceTexture) {
  38519. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38520. return false;
  38521. }
  38522. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  38523. }
  38524. else {
  38525. defines.MICROSURFACEMAP = false;
  38526. }
  38527. }
  38528. else {
  38529. defines.REFLECTIVITY = false;
  38530. defines.MICROSURFACEMAP = false;
  38531. }
  38532. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38533. // Bump texure can not be none blocking.
  38534. if (!this._bumpTexture.isReady()) {
  38535. return false;
  38536. }
  38537. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38538. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38539. defines.PARALLAX = true;
  38540. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  38541. }
  38542. else {
  38543. defines.PARALLAX = false;
  38544. }
  38545. }
  38546. else {
  38547. defines.BUMP = false;
  38548. }
  38549. var refractionTexture = this._getRefractionTexture();
  38550. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38551. if (!refractionTexture.isReadyOrNotBlocking()) {
  38552. return false;
  38553. }
  38554. defines.REFRACTION = true;
  38555. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  38556. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  38557. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  38558. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  38559. if (this._linkRefractionWithTransparency) {
  38560. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38561. }
  38562. }
  38563. else {
  38564. defines.REFRACTION = false;
  38565. }
  38566. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38567. // This is blocking.
  38568. if (!this._environmentBRDFTexture.isReady()) {
  38569. return false;
  38570. }
  38571. defines.ENVIRONMENTBRDF = true;
  38572. }
  38573. else {
  38574. defines.ENVIRONMENTBRDF = false;
  38575. }
  38576. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38577. defines.ALPHAFROMALBEDO = true;
  38578. }
  38579. else {
  38580. defines.ALPHAFROMALBEDO = false;
  38581. }
  38582. }
  38583. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38584. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  38585. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  38586. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38587. defines.METALLICWORKFLOW = true;
  38588. }
  38589. else {
  38590. defines.METALLICWORKFLOW = false;
  38591. }
  38592. if (!this.backFaceCulling && this._twoSidedLighting) {
  38593. defines.TWOSIDEDLIGHTING = true;
  38594. }
  38595. else {
  38596. defines.TWOSIDEDLIGHTING = false;
  38597. }
  38598. defines.ALPHATESTVALUE = this._alphaCutOff;
  38599. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38600. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  38601. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  38602. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  38603. }
  38604. if (defines._areImageProcessingDirty) {
  38605. if (!this._imageProcessingConfiguration.isReady()) {
  38606. return false;
  38607. }
  38608. this._imageProcessingConfiguration.prepareDefines(defines);
  38609. }
  38610. defines.FORCENORMALFORWARD = this._forceNormalForward;
  38611. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  38612. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  38613. // Misc.
  38614. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  38615. // Values that need to be evaluated on every frame
  38616. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false);
  38617. // Attribs
  38618. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  38619. var bufferMesh = null;
  38620. if (mesh instanceof BABYLON.InstancedMesh) {
  38621. bufferMesh = mesh.sourceMesh;
  38622. }
  38623. else if (mesh instanceof BABYLON.Mesh) {
  38624. bufferMesh = mesh;
  38625. }
  38626. if (bufferMesh) {
  38627. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38628. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  38629. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  38630. var normals = normalVertexBuffer.getData();
  38631. var vertexBufferOffset = normalVertexBuffer.getOffset();
  38632. var strideSize = normalVertexBuffer.getStrideSize();
  38633. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  38634. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  38635. defines.NORMAL = false;
  38636. }
  38637. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38638. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  38639. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  38640. var tangents = tangentVertexBuffer.getData();
  38641. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  38642. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  38643. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  38644. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  38645. defines.TANGENT = false;
  38646. }
  38647. }
  38648. }
  38649. else {
  38650. if (!scene.getEngine().getCaps().standardDerivatives) {
  38651. bufferMesh.createNormals(true);
  38652. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  38653. }
  38654. }
  38655. }
  38656. }
  38657. // Get correct effect
  38658. if (defines.isDirty) {
  38659. defines.markAsProcessed();
  38660. scene.resetCachedMaterial();
  38661. // Fallbacks
  38662. var fallbacks = new BABYLON.EffectFallbacks();
  38663. var fallbackRank = 0;
  38664. if (defines.USESPHERICALINVERTEX) {
  38665. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  38666. }
  38667. if (defines.FOG) {
  38668. fallbacks.addFallback(fallbackRank, "FOG");
  38669. }
  38670. if (defines.POINTSIZE) {
  38671. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  38672. }
  38673. if (defines.LOGARITHMICDEPTH) {
  38674. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  38675. }
  38676. if (defines.PARALLAX) {
  38677. fallbacks.addFallback(fallbackRank, "PARALLAX");
  38678. }
  38679. if (defines.PARALLAXOCCLUSION) {
  38680. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  38681. }
  38682. if (defines.ENVIRONMENTBRDF) {
  38683. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  38684. }
  38685. if (defines.TANGENT) {
  38686. fallbacks.addFallback(fallbackRank++, "TANGENT");
  38687. }
  38688. if (defines.BUMP) {
  38689. fallbacks.addFallback(fallbackRank++, "BUMP");
  38690. }
  38691. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  38692. if (defines.SPECULARTERM) {
  38693. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  38694. }
  38695. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  38696. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  38697. }
  38698. if (defines.LIGHTMAP) {
  38699. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  38700. }
  38701. if (defines.NORMAL) {
  38702. fallbacks.addFallback(fallbackRank++, "NORMAL");
  38703. }
  38704. if (defines.AMBIENT) {
  38705. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  38706. }
  38707. if (defines.EMISSIVE) {
  38708. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  38709. }
  38710. if (defines.VERTEXCOLOR) {
  38711. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  38712. }
  38713. if (defines.NUM_BONE_INFLUENCERS > 0) {
  38714. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  38715. }
  38716. if (defines.MORPHTARGETS) {
  38717. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  38718. }
  38719. //Attributes
  38720. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38721. if (defines.NORMAL) {
  38722. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38723. }
  38724. if (defines.TANGENT) {
  38725. attribs.push(BABYLON.VertexBuffer.TangentKind);
  38726. }
  38727. if (defines.UV1) {
  38728. attribs.push(BABYLON.VertexBuffer.UVKind);
  38729. }
  38730. if (defines.UV2) {
  38731. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38732. }
  38733. if (defines.VERTEXCOLOR) {
  38734. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38735. }
  38736. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38737. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38738. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38739. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  38740. "vFogInfos", "vFogColor", "pointSize",
  38741. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38742. "mBones",
  38743. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38744. "vLightingIntensity",
  38745. "logarithmicDepthConstant",
  38746. "vSphericalX", "vSphericalY", "vSphericalZ",
  38747. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  38748. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  38749. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  38750. "vTangentSpaceParams"
  38751. ];
  38752. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  38753. "bumpSampler", "lightmapSampler", "opacitySampler",
  38754. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  38755. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  38756. "microSurfaceSampler", "environmentBrdfSampler"];
  38757. var uniformBuffers = ["Material", "Scene"];
  38758. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38759. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38760. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38761. uniformsNames: uniforms,
  38762. uniformBuffersNames: uniformBuffers,
  38763. samplers: samplers,
  38764. defines: defines,
  38765. maxSimultaneousLights: this._maxSimultaneousLights
  38766. });
  38767. var onCompiled = function (effect) {
  38768. if (_this.onCompiled) {
  38769. _this.onCompiled(effect);
  38770. }
  38771. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  38772. };
  38773. var join = defines.toString();
  38774. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  38775. attributes: attribs,
  38776. uniformsNames: uniforms,
  38777. uniformBuffersNames: uniformBuffers,
  38778. samplers: samplers,
  38779. defines: join,
  38780. fallbacks: fallbacks,
  38781. onCompiled: onCompiled,
  38782. onError: this.onError,
  38783. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38784. }, engine), defines);
  38785. this.buildUniformLayout();
  38786. }
  38787. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38788. return false;
  38789. }
  38790. defines._renderId = scene.getRenderId();
  38791. this._wasPreviouslyReady = true;
  38792. return true;
  38793. };
  38794. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  38795. // Order is important !
  38796. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  38797. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  38798. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38799. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38800. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38801. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  38802. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  38803. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38804. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38805. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38806. this._uniformBuffer.addUniform("albedoMatrix", 16);
  38807. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38808. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38809. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38810. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38811. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  38812. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  38813. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38814. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38815. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38816. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38817. this._uniformBuffer.addUniform("vReflectionColor", 3);
  38818. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  38819. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  38820. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  38821. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  38822. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  38823. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38824. this._uniformBuffer.addUniform("pointSize", 1);
  38825. this._uniformBuffer.create();
  38826. };
  38827. PBRBaseMaterial.prototype.unbind = function () {
  38828. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38829. this._uniformBuffer.setTexture("reflectionSampler", null);
  38830. }
  38831. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38832. this._uniformBuffer.setTexture("refractionSampler", null);
  38833. }
  38834. _super.prototype.unbind.call(this);
  38835. };
  38836. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38837. this._activeEffect.setMatrix("world", world);
  38838. };
  38839. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38840. var scene = this.getScene();
  38841. var defines = subMesh._materialDefines;
  38842. if (!defines) {
  38843. return;
  38844. }
  38845. var effect = subMesh.effect;
  38846. if (!effect) {
  38847. return;
  38848. }
  38849. this._activeEffect = effect;
  38850. // Matrices
  38851. this.bindOnlyWorldMatrix(world);
  38852. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38853. // Bones
  38854. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  38855. var reflectionTexture = null;
  38856. if (mustRebind) {
  38857. this._uniformBuffer.bindToEffect(effect, "Material");
  38858. this.bindViewProjection(effect);
  38859. reflectionTexture = this._getReflectionTexture();
  38860. var refractionTexture = this._getRefractionTexture();
  38861. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38862. // Texture uniforms
  38863. if (scene.texturesEnabled) {
  38864. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38865. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  38866. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  38867. }
  38868. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38869. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  38870. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38871. }
  38872. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38873. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38874. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38875. }
  38876. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38877. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  38878. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  38879. var polynomials = reflectionTexture.sphericalPolynomial;
  38880. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  38881. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  38882. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  38883. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  38884. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  38885. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  38886. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  38887. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  38888. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  38889. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  38890. }
  38891. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  38892. }
  38893. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38894. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38895. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38896. }
  38897. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38898. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38899. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38900. }
  38901. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38902. if (this._metallicTexture) {
  38903. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  38904. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  38905. }
  38906. else if (this._reflectivityTexture) {
  38907. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  38908. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  38909. }
  38910. if (this._microSurfaceTexture) {
  38911. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  38912. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  38913. }
  38914. }
  38915. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38916. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  38917. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38918. if (scene._mirroredCameraPosition) {
  38919. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38920. }
  38921. else {
  38922. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38923. }
  38924. }
  38925. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38926. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  38927. var depth = 1.0;
  38928. if (!refractionTexture.isCube) {
  38929. if (refractionTexture.depth) {
  38930. depth = refractionTexture.depth;
  38931. }
  38932. }
  38933. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  38934. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  38935. }
  38936. }
  38937. // Point size
  38938. if (this.pointsCloud) {
  38939. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  38940. }
  38941. // Colors
  38942. if (defines.METALLICWORKFLOW) {
  38943. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  38944. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  38945. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  38946. }
  38947. else {
  38948. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  38949. }
  38950. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  38951. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  38952. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  38953. // Misc
  38954. this._lightingInfos.x = this._directIntensity;
  38955. this._lightingInfos.y = this._emissiveIntensity;
  38956. this._lightingInfos.z = this._environmentIntensity;
  38957. this._lightingInfos.w = this._specularIntensity;
  38958. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  38959. }
  38960. // Textures
  38961. if (scene.texturesEnabled) {
  38962. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38963. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  38964. }
  38965. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38966. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  38967. }
  38968. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38969. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  38970. }
  38971. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38972. if (defines.LODBASEDMICROSFURACE) {
  38973. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  38974. }
  38975. else {
  38976. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  38977. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  38978. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  38979. }
  38980. }
  38981. if (defines.ENVIRONMENTBRDF) {
  38982. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  38983. }
  38984. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38985. if (defines.LODBASEDMICROSFURACE) {
  38986. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  38987. }
  38988. else {
  38989. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  38990. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  38991. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  38992. }
  38993. }
  38994. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38995. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  38996. }
  38997. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38998. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  38999. }
  39000. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39001. if (this._metallicTexture) {
  39002. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  39003. }
  39004. else if (this._reflectivityTexture) {
  39005. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  39006. }
  39007. if (this._microSurfaceTexture) {
  39008. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  39009. }
  39010. }
  39011. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39012. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  39013. }
  39014. }
  39015. // Clip plane
  39016. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  39017. // Colors
  39018. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  39019. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  39020. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  39021. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  39022. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39023. }
  39024. if (mustRebind || !this.isFrozen) {
  39025. // Lights
  39026. if (scene.lightsEnabled && !this._disableLighting) {
  39027. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  39028. }
  39029. // View
  39030. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  39031. this.bindView(effect);
  39032. }
  39033. // Fog
  39034. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  39035. // Morph targets
  39036. if (defines.NUM_MORPH_INFLUENCERS) {
  39037. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  39038. }
  39039. // image processing
  39040. this._imageProcessingConfiguration.bind(this._activeEffect);
  39041. // Log. depth
  39042. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  39043. }
  39044. this._uniformBuffer.update();
  39045. this._afterBind(mesh);
  39046. };
  39047. PBRBaseMaterial.prototype.getAnimatables = function () {
  39048. var results = [];
  39049. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  39050. results.push(this._albedoTexture);
  39051. }
  39052. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39053. results.push(this._ambientTexture);
  39054. }
  39055. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39056. results.push(this._opacityTexture);
  39057. }
  39058. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39059. results.push(this._reflectionTexture);
  39060. }
  39061. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39062. results.push(this._emissiveTexture);
  39063. }
  39064. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  39065. results.push(this._metallicTexture);
  39066. }
  39067. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  39068. results.push(this._reflectivityTexture);
  39069. }
  39070. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39071. results.push(this._bumpTexture);
  39072. }
  39073. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39074. results.push(this._lightmapTexture);
  39075. }
  39076. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39077. results.push(this._refractionTexture);
  39078. }
  39079. return results;
  39080. };
  39081. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  39082. if (this._reflectionTexture) {
  39083. return this._reflectionTexture;
  39084. }
  39085. return this.getScene().environmentTexture;
  39086. };
  39087. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  39088. if (this._refractionTexture) {
  39089. return this._refractionTexture;
  39090. }
  39091. if (this._linkRefractionWithTransparency) {
  39092. return this.getScene().environmentTexture;
  39093. }
  39094. return null;
  39095. };
  39096. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39097. if (forceDisposeTextures) {
  39098. if (this._albedoTexture) {
  39099. this._albedoTexture.dispose();
  39100. }
  39101. if (this._ambientTexture) {
  39102. this._ambientTexture.dispose();
  39103. }
  39104. if (this._opacityTexture) {
  39105. this._opacityTexture.dispose();
  39106. }
  39107. if (this._reflectionTexture) {
  39108. this._reflectionTexture.dispose();
  39109. }
  39110. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  39111. this._environmentBRDFTexture.dispose();
  39112. }
  39113. if (this._emissiveTexture) {
  39114. this._emissiveTexture.dispose();
  39115. }
  39116. if (this._metallicTexture) {
  39117. this._metallicTexture.dispose();
  39118. }
  39119. if (this._reflectivityTexture) {
  39120. this._reflectivityTexture.dispose();
  39121. }
  39122. if (this._bumpTexture) {
  39123. this._bumpTexture.dispose();
  39124. }
  39125. if (this._lightmapTexture) {
  39126. this._lightmapTexture.dispose();
  39127. }
  39128. if (this._refractionTexture) {
  39129. this._refractionTexture.dispose();
  39130. }
  39131. }
  39132. this._renderTargets.dispose();
  39133. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39134. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39135. }
  39136. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39137. };
  39138. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  39139. __decorate([
  39140. BABYLON.serializeAsImageProcessingConfiguration()
  39141. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  39142. __decorate([
  39143. BABYLON.serialize()
  39144. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  39145. __decorate([
  39146. BABYLON.serialize()
  39147. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  39148. return PBRBaseMaterial;
  39149. }(BABYLON.PushMaterial));
  39150. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  39151. })(BABYLON || (BABYLON = {}));
  39152. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  39153. var BABYLON;
  39154. (function (BABYLON) {
  39155. /**
  39156. * The Physically based simple base material of BJS.
  39157. *
  39158. * This enables better naming and convention enforcements on top of the pbrMaterial.
  39159. * It is used as the base class for both the specGloss and metalRough conventions.
  39160. */
  39161. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  39162. __extends(PBRBaseSimpleMaterial, _super);
  39163. /**
  39164. * Instantiates a new PBRMaterial instance.
  39165. *
  39166. * @param name The material name
  39167. * @param scene The scene the material will be use in.
  39168. */
  39169. function PBRBaseSimpleMaterial(name, scene) {
  39170. var _this = _super.call(this, name, scene) || this;
  39171. /**
  39172. * Number of Simultaneous lights allowed on the material.
  39173. */
  39174. _this.maxSimultaneousLights = 4;
  39175. /**
  39176. * If sets to true, disables all the lights affecting the material.
  39177. */
  39178. _this.disableLighting = false;
  39179. /**
  39180. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39181. */
  39182. _this.invertNormalMapX = false;
  39183. /**
  39184. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39185. */
  39186. _this.invertNormalMapY = false;
  39187. /**
  39188. * Emissivie color used to self-illuminate the model.
  39189. */
  39190. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39191. /**
  39192. * Occlusion Channel Strenght.
  39193. */
  39194. _this.occlusionStrength = 1.0;
  39195. _this.useLightmapAsShadowmap = false;
  39196. _this._useAlphaFromAlbedoTexture = true;
  39197. _this._useAmbientInGrayScale = true;
  39198. return _this;
  39199. }
  39200. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  39201. /**
  39202. * Gets the current double sided mode.
  39203. */
  39204. get: function () {
  39205. return this._twoSidedLighting;
  39206. },
  39207. /**
  39208. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39209. */
  39210. set: function (value) {
  39211. if (this._twoSidedLighting === value) {
  39212. return;
  39213. }
  39214. this._twoSidedLighting = value;
  39215. this.backFaceCulling = !value;
  39216. this._markAllSubMeshesAsTexturesDirty();
  39217. },
  39218. enumerable: true,
  39219. configurable: true
  39220. });
  39221. /**
  39222. * Return the active textures of the material.
  39223. */
  39224. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  39225. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39226. if (this.environmentTexture) {
  39227. activeTextures.push(this.environmentTexture);
  39228. }
  39229. if (this.normalTexture) {
  39230. activeTextures.push(this.normalTexture);
  39231. }
  39232. if (this.emissiveTexture) {
  39233. activeTextures.push(this.emissiveTexture);
  39234. }
  39235. if (this.occlusionTexture) {
  39236. activeTextures.push(this.occlusionTexture);
  39237. }
  39238. if (this.lightmapTexture) {
  39239. activeTextures.push(this.lightmapTexture);
  39240. }
  39241. return activeTextures;
  39242. };
  39243. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  39244. if (_super.prototype.hasTexture.call(this, texture)) {
  39245. return true;
  39246. }
  39247. if (this.lightmapTexture === texture) {
  39248. return true;
  39249. }
  39250. return false;
  39251. };
  39252. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  39253. return "PBRBaseSimpleMaterial";
  39254. };
  39255. __decorate([
  39256. BABYLON.serialize(),
  39257. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39258. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  39259. __decorate([
  39260. BABYLON.serialize(),
  39261. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39262. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  39263. __decorate([
  39264. BABYLON.serializeAsTexture(),
  39265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  39266. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  39267. __decorate([
  39268. BABYLON.serialize(),
  39269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39270. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  39271. __decorate([
  39272. BABYLON.serialize(),
  39273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39274. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  39275. __decorate([
  39276. BABYLON.serializeAsTexture(),
  39277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  39278. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  39279. __decorate([
  39280. BABYLON.serializeAsColor3("emissive"),
  39281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39282. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  39283. __decorate([
  39284. BABYLON.serializeAsTexture(),
  39285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39286. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  39287. __decorate([
  39288. BABYLON.serialize(),
  39289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  39290. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  39291. __decorate([
  39292. BABYLON.serializeAsTexture(),
  39293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  39294. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  39295. __decorate([
  39296. BABYLON.serialize(),
  39297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  39298. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39299. __decorate([
  39300. BABYLON.serialize()
  39301. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39302. __decorate([
  39303. BABYLON.serializeAsTexture(),
  39304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39305. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  39306. __decorate([
  39307. BABYLON.serialize(),
  39308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39309. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39310. return PBRBaseSimpleMaterial;
  39311. }(BABYLON.PBRBaseMaterial));
  39312. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39313. })(BABYLON || (BABYLON = {}));
  39314. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39315. var BABYLON;
  39316. (function (BABYLON) {
  39317. /**
  39318. * The Physically based material of BJS.
  39319. *
  39320. * This offers the main features of a standard PBR material.
  39321. * For more information, please refer to the documentation :
  39322. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39323. */
  39324. var PBRMaterial = /** @class */ (function (_super) {
  39325. __extends(PBRMaterial, _super);
  39326. /**
  39327. * Instantiates a new PBRMaterial instance.
  39328. *
  39329. * @param name The material name
  39330. * @param scene The scene the material will be use in.
  39331. */
  39332. function PBRMaterial(name, scene) {
  39333. var _this = _super.call(this, name, scene) || this;
  39334. /**
  39335. * Intensity of the direct lights e.g. the four lights available in your scene.
  39336. * This impacts both the direct diffuse and specular highlights.
  39337. */
  39338. _this.directIntensity = 1.0;
  39339. /**
  39340. * Intensity of the emissive part of the material.
  39341. * This helps controlling the emissive effect without modifying the emissive color.
  39342. */
  39343. _this.emissiveIntensity = 1.0;
  39344. /**
  39345. * Intensity of the environment e.g. how much the environment will light the object
  39346. * either through harmonics for rough material or through the refelction for shiny ones.
  39347. */
  39348. _this.environmentIntensity = 1.0;
  39349. /**
  39350. * This is a special control allowing the reduction of the specular highlights coming from the
  39351. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39352. */
  39353. _this.specularIntensity = 1.0;
  39354. /**
  39355. * Debug Control allowing disabling the bump map on this material.
  39356. */
  39357. _this.disableBumpMap = false;
  39358. /**
  39359. * AKA Occlusion Texture Intensity in other nomenclature.
  39360. */
  39361. _this.ambientTextureStrength = 1.0;
  39362. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39363. /**
  39364. * AKA Diffuse Color in other nomenclature.
  39365. */
  39366. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39367. /**
  39368. * AKA Specular Color in other nomenclature.
  39369. */
  39370. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39371. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  39372. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39373. /**
  39374. * AKA Glossiness in other nomenclature.
  39375. */
  39376. _this.microSurface = 1.0;
  39377. /**
  39378. * source material index of refraction (IOR)' / 'destination material IOR.
  39379. */
  39380. _this.indexOfRefraction = 0.66;
  39381. /**
  39382. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39383. */
  39384. _this.invertRefractionY = false;
  39385. /**
  39386. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39387. * Materials half opaque for instance using refraction could benefit from this control.
  39388. */
  39389. _this.linkRefractionWithTransparency = false;
  39390. _this.useLightmapAsShadowmap = false;
  39391. /**
  39392. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39393. */
  39394. _this.useAlphaFromAlbedoTexture = false;
  39395. /**
  39396. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39397. */
  39398. _this.forceAlphaTest = false;
  39399. /**
  39400. * Defines the alpha limits in alpha test mode.
  39401. */
  39402. _this.alphaCutOff = 0.4;
  39403. /**
  39404. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39405. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39406. */
  39407. _this.useSpecularOverAlpha = true;
  39408. /**
  39409. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39410. */
  39411. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39412. /**
  39413. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39414. */
  39415. _this.useRoughnessFromMetallicTextureAlpha = true;
  39416. /**
  39417. * Specifies if the metallic texture contains the roughness information in its green channel.
  39418. */
  39419. _this.useRoughnessFromMetallicTextureGreen = false;
  39420. /**
  39421. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39422. */
  39423. _this.useMetallnessFromMetallicTextureBlue = false;
  39424. /**
  39425. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39426. */
  39427. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39428. /**
  39429. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39430. */
  39431. _this.useAmbientInGrayScale = false;
  39432. /**
  39433. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39434. * The material will try to infer what glossiness each pixel should be.
  39435. */
  39436. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39437. /**
  39438. * BJS is using an harcoded light falloff based on a manually sets up range.
  39439. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39440. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39441. */
  39442. _this.usePhysicalLightFalloff = true;
  39443. /**
  39444. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39445. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39446. */
  39447. _this.useRadianceOverAlpha = true;
  39448. /**
  39449. * Allows using the bump map in parallax mode.
  39450. */
  39451. _this.useParallax = false;
  39452. /**
  39453. * Allows using the bump map in parallax occlusion mode.
  39454. */
  39455. _this.useParallaxOcclusion = false;
  39456. /**
  39457. * Controls the scale bias of the parallax mode.
  39458. */
  39459. _this.parallaxScaleBias = 0.05;
  39460. /**
  39461. * If sets to true, disables all the lights affecting the material.
  39462. */
  39463. _this.disableLighting = false;
  39464. /**
  39465. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39466. */
  39467. _this.forceIrradianceInFragment = false;
  39468. /**
  39469. * Number of Simultaneous lights allowed on the material.
  39470. */
  39471. _this.maxSimultaneousLights = 4;
  39472. /**
  39473. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39474. */
  39475. _this.invertNormalMapX = false;
  39476. /**
  39477. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39478. */
  39479. _this.invertNormalMapY = false;
  39480. /**
  39481. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39482. */
  39483. _this.twoSidedLighting = false;
  39484. /**
  39485. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39486. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39487. */
  39488. _this.useAlphaFresnel = false;
  39489. /**
  39490. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39491. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39492. */
  39493. _this.useLinearAlphaFresnel = false;
  39494. /**
  39495. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39496. * And/Or occlude the blended part.
  39497. */
  39498. _this.environmentBRDFTexture = null;
  39499. /**
  39500. * Force normal to face away from face.
  39501. */
  39502. _this.forceNormalForward = false;
  39503. /**
  39504. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39505. * makes the reflect vector face the model (under horizon).
  39506. */
  39507. _this.useHorizonOcclusion = true;
  39508. /**
  39509. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39510. * too much the area relying on ambient texture to define their ambient occlusion.
  39511. */
  39512. _this.useRadianceOcclusion = true;
  39513. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39514. return _this;
  39515. }
  39516. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39517. /**
  39518. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39519. */
  39520. get: function () {
  39521. return this._PBRMATERIAL_OPAQUE;
  39522. },
  39523. enumerable: true,
  39524. configurable: true
  39525. });
  39526. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39527. /**
  39528. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39529. */
  39530. get: function () {
  39531. return this._PBRMATERIAL_ALPHATEST;
  39532. },
  39533. enumerable: true,
  39534. configurable: true
  39535. });
  39536. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39537. /**
  39538. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39539. */
  39540. get: function () {
  39541. return this._PBRMATERIAL_ALPHABLEND;
  39542. },
  39543. enumerable: true,
  39544. configurable: true
  39545. });
  39546. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39547. /**
  39548. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39549. * They are also discarded below the alpha cutoff threshold to improve performances.
  39550. */
  39551. get: function () {
  39552. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39553. },
  39554. enumerable: true,
  39555. configurable: true
  39556. });
  39557. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  39558. /**
  39559. * Gets the image processing configuration used either in this material.
  39560. */
  39561. get: function () {
  39562. return this._imageProcessingConfiguration;
  39563. },
  39564. /**
  39565. * Sets the Default image processing configuration used either in the this material.
  39566. *
  39567. * If sets to null, the scene one is in use.
  39568. */
  39569. set: function (value) {
  39570. this._attachImageProcessingConfiguration(value);
  39571. // Ensure the effect will be rebuilt.
  39572. this._markAllSubMeshesAsTexturesDirty();
  39573. },
  39574. enumerable: true,
  39575. configurable: true
  39576. });
  39577. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  39578. /**
  39579. * Gets wether the color curves effect is enabled.
  39580. */
  39581. get: function () {
  39582. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39583. },
  39584. /**
  39585. * Sets wether the color curves effect is enabled.
  39586. */
  39587. set: function (value) {
  39588. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39589. },
  39590. enumerable: true,
  39591. configurable: true
  39592. });
  39593. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  39594. /**
  39595. * Gets wether the color grading effect is enabled.
  39596. */
  39597. get: function () {
  39598. return this.imageProcessingConfiguration.colorGradingEnabled;
  39599. },
  39600. /**
  39601. * Gets wether the color grading effect is enabled.
  39602. */
  39603. set: function (value) {
  39604. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39605. },
  39606. enumerable: true,
  39607. configurable: true
  39608. });
  39609. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  39610. /**
  39611. * Gets wether tonemapping is enabled or not.
  39612. */
  39613. get: function () {
  39614. return this._imageProcessingConfiguration.toneMappingEnabled;
  39615. },
  39616. /**
  39617. * Sets wether tonemapping is enabled or not
  39618. */
  39619. set: function (value) {
  39620. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39621. },
  39622. enumerable: true,
  39623. configurable: true
  39624. });
  39625. ;
  39626. ;
  39627. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  39628. /**
  39629. * The camera exposure used on this material.
  39630. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39631. * This corresponds to a photographic exposure.
  39632. */
  39633. get: function () {
  39634. return this._imageProcessingConfiguration.exposure;
  39635. },
  39636. /**
  39637. * The camera exposure used on this material.
  39638. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39639. * This corresponds to a photographic exposure.
  39640. */
  39641. set: function (value) {
  39642. this._imageProcessingConfiguration.exposure = value;
  39643. },
  39644. enumerable: true,
  39645. configurable: true
  39646. });
  39647. ;
  39648. ;
  39649. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  39650. /**
  39651. * Gets The camera contrast used on this material.
  39652. */
  39653. get: function () {
  39654. return this._imageProcessingConfiguration.contrast;
  39655. },
  39656. /**
  39657. * Sets The camera contrast used on this material.
  39658. */
  39659. set: function (value) {
  39660. this._imageProcessingConfiguration.contrast = value;
  39661. },
  39662. enumerable: true,
  39663. configurable: true
  39664. });
  39665. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  39666. /**
  39667. * Gets the Color Grading 2D Lookup Texture.
  39668. */
  39669. get: function () {
  39670. return this._imageProcessingConfiguration.colorGradingTexture;
  39671. },
  39672. /**
  39673. * Sets the Color Grading 2D Lookup Texture.
  39674. */
  39675. set: function (value) {
  39676. this._imageProcessingConfiguration.colorGradingTexture = value;
  39677. },
  39678. enumerable: true,
  39679. configurable: true
  39680. });
  39681. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  39682. /**
  39683. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39684. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39685. * 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;
  39686. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39687. */
  39688. get: function () {
  39689. return this._imageProcessingConfiguration.colorCurves;
  39690. },
  39691. /**
  39692. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39693. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39694. * 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;
  39695. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39696. */
  39697. set: function (value) {
  39698. this._imageProcessingConfiguration.colorCurves = value;
  39699. },
  39700. enumerable: true,
  39701. configurable: true
  39702. });
  39703. PBRMaterial.prototype.getClassName = function () {
  39704. return "PBRMaterial";
  39705. };
  39706. PBRMaterial.prototype.getActiveTextures = function () {
  39707. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39708. if (this._albedoTexture) {
  39709. activeTextures.push(this._albedoTexture);
  39710. }
  39711. if (this._ambientTexture) {
  39712. activeTextures.push(this._ambientTexture);
  39713. }
  39714. if (this._opacityTexture) {
  39715. activeTextures.push(this._opacityTexture);
  39716. }
  39717. if (this._reflectionTexture) {
  39718. activeTextures.push(this._reflectionTexture);
  39719. }
  39720. if (this._emissiveTexture) {
  39721. activeTextures.push(this._emissiveTexture);
  39722. }
  39723. if (this._reflectivityTexture) {
  39724. activeTextures.push(this._reflectivityTexture);
  39725. }
  39726. if (this._metallicTexture) {
  39727. activeTextures.push(this._metallicTexture);
  39728. }
  39729. if (this._microSurfaceTexture) {
  39730. activeTextures.push(this._microSurfaceTexture);
  39731. }
  39732. if (this._bumpTexture) {
  39733. activeTextures.push(this._bumpTexture);
  39734. }
  39735. if (this._lightmapTexture) {
  39736. activeTextures.push(this._lightmapTexture);
  39737. }
  39738. if (this._refractionTexture) {
  39739. activeTextures.push(this._refractionTexture);
  39740. }
  39741. return activeTextures;
  39742. };
  39743. PBRMaterial.prototype.hasTexture = function (texture) {
  39744. if (_super.prototype.hasTexture.call(this, texture)) {
  39745. return true;
  39746. }
  39747. if (this._albedoTexture === texture) {
  39748. return true;
  39749. }
  39750. if (this._ambientTexture === texture) {
  39751. return true;
  39752. }
  39753. if (this._opacityTexture === texture) {
  39754. return true;
  39755. }
  39756. if (this._reflectionTexture === texture) {
  39757. return true;
  39758. }
  39759. if (this._reflectivityTexture === texture) {
  39760. return true;
  39761. }
  39762. if (this._metallicTexture === texture) {
  39763. return true;
  39764. }
  39765. if (this._microSurfaceTexture === texture) {
  39766. return true;
  39767. }
  39768. if (this._bumpTexture === texture) {
  39769. return true;
  39770. }
  39771. if (this._lightmapTexture === texture) {
  39772. return true;
  39773. }
  39774. if (this._refractionTexture === texture) {
  39775. return true;
  39776. }
  39777. return false;
  39778. };
  39779. PBRMaterial.prototype.clone = function (name) {
  39780. var _this = this;
  39781. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  39782. clone.id = name;
  39783. clone.name = name;
  39784. return clone;
  39785. };
  39786. PBRMaterial.prototype.serialize = function () {
  39787. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39788. serializationObject.customType = "BABYLON.PBRMaterial";
  39789. return serializationObject;
  39790. };
  39791. // Statics
  39792. PBRMaterial.Parse = function (source, scene, rootUrl) {
  39793. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  39794. };
  39795. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  39796. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  39797. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  39798. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  39799. __decorate([
  39800. BABYLON.serialize(),
  39801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39802. ], PBRMaterial.prototype, "directIntensity", void 0);
  39803. __decorate([
  39804. BABYLON.serialize(),
  39805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39806. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  39807. __decorate([
  39808. BABYLON.serialize(),
  39809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39810. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  39811. __decorate([
  39812. BABYLON.serialize(),
  39813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39814. ], PBRMaterial.prototype, "specularIntensity", void 0);
  39815. __decorate([
  39816. BABYLON.serialize(),
  39817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39818. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  39819. __decorate([
  39820. BABYLON.serializeAsTexture(),
  39821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39822. ], PBRMaterial.prototype, "albedoTexture", void 0);
  39823. __decorate([
  39824. BABYLON.serializeAsTexture(),
  39825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39826. ], PBRMaterial.prototype, "ambientTexture", void 0);
  39827. __decorate([
  39828. BABYLON.serialize(),
  39829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39830. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  39831. __decorate([
  39832. BABYLON.serializeAsTexture(),
  39833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39834. ], PBRMaterial.prototype, "opacityTexture", void 0);
  39835. __decorate([
  39836. BABYLON.serializeAsTexture(),
  39837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39838. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  39839. __decorate([
  39840. BABYLON.serializeAsTexture(),
  39841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39842. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  39843. __decorate([
  39844. BABYLON.serializeAsTexture(),
  39845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39846. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  39847. __decorate([
  39848. BABYLON.serializeAsTexture(),
  39849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39850. ], PBRMaterial.prototype, "metallicTexture", void 0);
  39851. __decorate([
  39852. BABYLON.serialize(),
  39853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39854. ], PBRMaterial.prototype, "metallic", void 0);
  39855. __decorate([
  39856. BABYLON.serialize(),
  39857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39858. ], PBRMaterial.prototype, "roughness", void 0);
  39859. __decorate([
  39860. BABYLON.serializeAsTexture(),
  39861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39862. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  39863. __decorate([
  39864. BABYLON.serializeAsTexture(),
  39865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39866. ], PBRMaterial.prototype, "bumpTexture", void 0);
  39867. __decorate([
  39868. BABYLON.serializeAsTexture(),
  39869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39870. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  39871. __decorate([
  39872. BABYLON.serializeAsTexture(),
  39873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39874. ], PBRMaterial.prototype, "refractionTexture", void 0);
  39875. __decorate([
  39876. BABYLON.serializeAsColor3("ambient"),
  39877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39878. ], PBRMaterial.prototype, "ambientColor", void 0);
  39879. __decorate([
  39880. BABYLON.serializeAsColor3("albedo"),
  39881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39882. ], PBRMaterial.prototype, "albedoColor", void 0);
  39883. __decorate([
  39884. BABYLON.serializeAsColor3("reflectivity"),
  39885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39886. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  39887. __decorate([
  39888. BABYLON.serializeAsColor3("reflection"),
  39889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39890. ], PBRMaterial.prototype, "reflectionColor", void 0);
  39891. __decorate([
  39892. BABYLON.serializeAsColor3("emissive"),
  39893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39894. ], PBRMaterial.prototype, "emissiveColor", void 0);
  39895. __decorate([
  39896. BABYLON.serialize(),
  39897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39898. ], PBRMaterial.prototype, "microSurface", void 0);
  39899. __decorate([
  39900. BABYLON.serialize(),
  39901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39902. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  39903. __decorate([
  39904. BABYLON.serialize(),
  39905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39906. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  39907. __decorate([
  39908. BABYLON.serialize(),
  39909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39910. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  39911. __decorate([
  39912. BABYLON.serialize(),
  39913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39914. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39915. __decorate([
  39916. BABYLON.serialize(),
  39917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39918. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  39919. __decorate([
  39920. BABYLON.serialize(),
  39921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39922. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  39923. __decorate([
  39924. BABYLON.serialize(),
  39925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39926. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  39927. __decorate([
  39928. BABYLON.serialize(),
  39929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39930. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  39931. __decorate([
  39932. BABYLON.serialize(),
  39933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39934. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  39935. __decorate([
  39936. BABYLON.serialize(),
  39937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39938. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  39939. __decorate([
  39940. BABYLON.serialize(),
  39941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39942. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  39943. __decorate([
  39944. BABYLON.serialize(),
  39945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39946. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  39947. __decorate([
  39948. BABYLON.serialize(),
  39949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39950. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  39951. __decorate([
  39952. BABYLON.serialize(),
  39953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39954. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  39955. __decorate([
  39956. BABYLON.serialize(),
  39957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39958. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  39959. __decorate([
  39960. BABYLON.serialize(),
  39961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39962. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  39963. __decorate([
  39964. BABYLON.serialize(),
  39965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39966. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  39967. __decorate([
  39968. BABYLON.serialize(),
  39969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39970. ], PBRMaterial.prototype, "useParallax", void 0);
  39971. __decorate([
  39972. BABYLON.serialize(),
  39973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39974. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  39975. __decorate([
  39976. BABYLON.serialize(),
  39977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39978. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  39979. __decorate([
  39980. BABYLON.serialize(),
  39981. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39982. ], PBRMaterial.prototype, "disableLighting", void 0);
  39983. __decorate([
  39984. BABYLON.serialize(),
  39985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39986. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  39987. __decorate([
  39988. BABYLON.serialize(),
  39989. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39990. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  39991. __decorate([
  39992. BABYLON.serialize(),
  39993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39994. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  39995. __decorate([
  39996. BABYLON.serialize(),
  39997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39998. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  39999. __decorate([
  40000. BABYLON.serialize(),
  40001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40002. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  40003. __decorate([
  40004. BABYLON.serialize(),
  40005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40006. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  40007. __decorate([
  40008. BABYLON.serialize(),
  40009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40010. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  40011. __decorate([
  40012. BABYLON.serializeAsTexture(),
  40013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40014. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  40015. __decorate([
  40016. BABYLON.serialize(),
  40017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40018. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  40019. __decorate([
  40020. BABYLON.serialize(),
  40021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40022. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  40023. __decorate([
  40024. BABYLON.serialize(),
  40025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40026. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  40027. return PBRMaterial;
  40028. }(BABYLON.PBRBaseMaterial));
  40029. BABYLON.PBRMaterial = PBRMaterial;
  40030. })(BABYLON || (BABYLON = {}));
  40031. //# sourceMappingURL=babylon.pbrMaterial.js.map
  40032. var BABYLON;
  40033. (function (BABYLON) {
  40034. /**
  40035. * The PBR material of BJS following the metal roughness convention.
  40036. *
  40037. * This fits to the PBR convention in the GLTF definition:
  40038. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  40039. */
  40040. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  40041. __extends(PBRMetallicRoughnessMaterial, _super);
  40042. /**
  40043. * Instantiates a new PBRMetalRoughnessMaterial instance.
  40044. *
  40045. * @param name The material name
  40046. * @param scene The scene the material will be use in.
  40047. */
  40048. function PBRMetallicRoughnessMaterial(name, scene) {
  40049. var _this = _super.call(this, name, scene) || this;
  40050. _this._useRoughnessFromMetallicTextureAlpha = false;
  40051. _this._useRoughnessFromMetallicTextureGreen = true;
  40052. _this._useMetallnessFromMetallicTextureBlue = true;
  40053. _this._forceMetallicWorkflow = true;
  40054. return _this;
  40055. }
  40056. /**
  40057. * Return the currrent class name of the material.
  40058. */
  40059. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  40060. return "PBRMetallicRoughnessMaterial";
  40061. };
  40062. /**
  40063. * Return the active textures of the material.
  40064. */
  40065. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  40066. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40067. if (this.baseTexture) {
  40068. activeTextures.push(this.baseTexture);
  40069. }
  40070. if (this.metallicRoughnessTexture) {
  40071. activeTextures.push(this.metallicRoughnessTexture);
  40072. }
  40073. return activeTextures;
  40074. };
  40075. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  40076. if (_super.prototype.hasTexture.call(this, texture)) {
  40077. return true;
  40078. }
  40079. if (this.baseTexture === texture) {
  40080. return true;
  40081. }
  40082. if (this.metallicRoughnessTexture === texture) {
  40083. return true;
  40084. }
  40085. return false;
  40086. };
  40087. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  40088. var _this = this;
  40089. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  40090. clone.id = name;
  40091. clone.name = name;
  40092. return clone;
  40093. };
  40094. /**
  40095. * Serialize the material to a parsable JSON object.
  40096. */
  40097. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  40098. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40099. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  40100. return serializationObject;
  40101. };
  40102. /**
  40103. * Parses a JSON object correponding to the serialize function.
  40104. */
  40105. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  40106. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  40107. };
  40108. __decorate([
  40109. BABYLON.serializeAsColor3(),
  40110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40111. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  40112. __decorate([
  40113. BABYLON.serializeAsTexture(),
  40114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40115. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  40116. __decorate([
  40117. BABYLON.serialize(),
  40118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40119. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  40120. __decorate([
  40121. BABYLON.serialize(),
  40122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40123. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  40124. __decorate([
  40125. BABYLON.serializeAsTexture(),
  40126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  40127. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  40128. return PBRMetallicRoughnessMaterial;
  40129. }(BABYLON.PBRBaseSimpleMaterial));
  40130. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  40131. })(BABYLON || (BABYLON = {}));
  40132. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  40133. var BABYLON;
  40134. (function (BABYLON) {
  40135. /**
  40136. * The PBR material of BJS following the specular glossiness convention.
  40137. *
  40138. * This fits to the PBR convention in the GLTF definition:
  40139. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  40140. */
  40141. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  40142. __extends(PBRSpecularGlossinessMaterial, _super);
  40143. /**
  40144. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  40145. *
  40146. * @param name The material name
  40147. * @param scene The scene the material will be use in.
  40148. */
  40149. function PBRSpecularGlossinessMaterial(name, scene) {
  40150. var _this = _super.call(this, name, scene) || this;
  40151. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  40152. return _this;
  40153. }
  40154. /**
  40155. * Return the currrent class name of the material.
  40156. */
  40157. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  40158. return "PBRSpecularGlossinessMaterial";
  40159. };
  40160. /**
  40161. * Return the active textures of the material.
  40162. */
  40163. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  40164. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40165. if (this.diffuseTexture) {
  40166. activeTextures.push(this.diffuseTexture);
  40167. }
  40168. if (this.specularGlossinessTexture) {
  40169. activeTextures.push(this.specularGlossinessTexture);
  40170. }
  40171. return activeTextures;
  40172. };
  40173. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  40174. if (_super.prototype.hasTexture.call(this, texture)) {
  40175. return true;
  40176. }
  40177. if (this.diffuseTexture === texture) {
  40178. return true;
  40179. }
  40180. if (this.specularGlossinessTexture === texture) {
  40181. return true;
  40182. }
  40183. return false;
  40184. };
  40185. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  40186. var _this = this;
  40187. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  40188. clone.id = name;
  40189. clone.name = name;
  40190. return clone;
  40191. };
  40192. /**
  40193. * Serialize the material to a parsable JSON object.
  40194. */
  40195. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  40196. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40197. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  40198. return serializationObject;
  40199. };
  40200. /**
  40201. * Parses a JSON object correponding to the serialize function.
  40202. */
  40203. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  40204. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  40205. };
  40206. __decorate([
  40207. BABYLON.serializeAsColor3("diffuse"),
  40208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40209. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  40210. __decorate([
  40211. BABYLON.serializeAsTexture(),
  40212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40213. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  40214. __decorate([
  40215. BABYLON.serializeAsColor3("specular"),
  40216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  40217. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  40218. __decorate([
  40219. BABYLON.serialize(),
  40220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  40221. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  40222. __decorate([
  40223. BABYLON.serializeAsTexture(),
  40224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  40225. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  40226. return PBRSpecularGlossinessMaterial;
  40227. }(BABYLON.PBRBaseSimpleMaterial));
  40228. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  40229. })(BABYLON || (BABYLON = {}));
  40230. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  40231. var BABYLON;
  40232. (function (BABYLON) {
  40233. BABYLON.CameraInputTypes = {};
  40234. var CameraInputsManager = /** @class */ (function () {
  40235. function CameraInputsManager(camera) {
  40236. this.attached = {};
  40237. this.camera = camera;
  40238. this.checkInputs = function () { };
  40239. }
  40240. /**
  40241. * Add an input method to a camera.
  40242. * builtin inputs example: camera.inputs.addGamepad();
  40243. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  40244. * @param input camera input method
  40245. */
  40246. CameraInputsManager.prototype.add = function (input) {
  40247. var type = input.getSimpleName();
  40248. if (this.attached[type]) {
  40249. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  40250. return;
  40251. }
  40252. this.attached[type] = input;
  40253. input.camera = this.camera;
  40254. //for checkInputs, we are dynamically creating a function
  40255. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  40256. if (input.checkInputs) {
  40257. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40258. }
  40259. if (this.attachedElement) {
  40260. input.attachControl(this.attachedElement);
  40261. }
  40262. };
  40263. /**
  40264. * Remove a specific input method from a camera
  40265. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  40266. * @param inputToRemove camera input method
  40267. */
  40268. CameraInputsManager.prototype.remove = function (inputToRemove) {
  40269. for (var cam in this.attached) {
  40270. var input = this.attached[cam];
  40271. if (input === inputToRemove) {
  40272. input.detachControl(this.attachedElement);
  40273. input.camera = null;
  40274. delete this.attached[cam];
  40275. this.rebuildInputCheck();
  40276. }
  40277. }
  40278. };
  40279. CameraInputsManager.prototype.removeByType = function (inputType) {
  40280. for (var cam in this.attached) {
  40281. var input = this.attached[cam];
  40282. if (input.getClassName() === inputType) {
  40283. input.detachControl(this.attachedElement);
  40284. input.camera = null;
  40285. delete this.attached[cam];
  40286. this.rebuildInputCheck();
  40287. }
  40288. }
  40289. };
  40290. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  40291. var current = this.checkInputs;
  40292. return function () {
  40293. current();
  40294. fn();
  40295. };
  40296. };
  40297. CameraInputsManager.prototype.attachInput = function (input) {
  40298. if (this.attachedElement) {
  40299. input.attachControl(this.attachedElement, this.noPreventDefault);
  40300. }
  40301. };
  40302. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  40303. if (noPreventDefault === void 0) { noPreventDefault = false; }
  40304. if (this.attachedElement) {
  40305. return;
  40306. }
  40307. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  40308. this.attachedElement = element;
  40309. this.noPreventDefault = noPreventDefault;
  40310. for (var cam in this.attached) {
  40311. this.attached[cam].attachControl(element, noPreventDefault);
  40312. }
  40313. };
  40314. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  40315. if (disconnect === void 0) { disconnect = false; }
  40316. if (this.attachedElement !== element) {
  40317. return;
  40318. }
  40319. for (var cam in this.attached) {
  40320. this.attached[cam].detachControl(element);
  40321. if (disconnect) {
  40322. this.attached[cam].camera = null;
  40323. }
  40324. }
  40325. this.attachedElement = null;
  40326. };
  40327. CameraInputsManager.prototype.rebuildInputCheck = function () {
  40328. this.checkInputs = function () { };
  40329. for (var cam in this.attached) {
  40330. var input = this.attached[cam];
  40331. if (input.checkInputs) {
  40332. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40333. }
  40334. }
  40335. };
  40336. /**
  40337. * Remove all attached input methods from a camera
  40338. */
  40339. CameraInputsManager.prototype.clear = function () {
  40340. if (this.attachedElement) {
  40341. this.detachElement(this.attachedElement, true);
  40342. }
  40343. this.attached = {};
  40344. this.attachedElement = null;
  40345. this.checkInputs = function () { };
  40346. };
  40347. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  40348. var inputs = {};
  40349. for (var cam in this.attached) {
  40350. var input = this.attached[cam];
  40351. var res = BABYLON.SerializationHelper.Serialize(input);
  40352. inputs[input.getClassName()] = res;
  40353. }
  40354. serializedCamera.inputsmgr = inputs;
  40355. };
  40356. CameraInputsManager.prototype.parse = function (parsedCamera) {
  40357. var parsedInputs = parsedCamera.inputsmgr;
  40358. if (parsedInputs) {
  40359. this.clear();
  40360. for (var n in parsedInputs) {
  40361. var construct = BABYLON.CameraInputTypes[n];
  40362. if (construct) {
  40363. var parsedinput = parsedInputs[n];
  40364. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  40365. this.add(input);
  40366. }
  40367. }
  40368. }
  40369. else {
  40370. //2016-03-08 this part is for managing backward compatibility
  40371. for (var n in this.attached) {
  40372. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  40373. if (construct) {
  40374. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  40375. this.remove(this.attached[n]);
  40376. this.add(input);
  40377. }
  40378. }
  40379. }
  40380. };
  40381. return CameraInputsManager;
  40382. }());
  40383. BABYLON.CameraInputsManager = CameraInputsManager;
  40384. })(BABYLON || (BABYLON = {}));
  40385. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  40386. var BABYLON;
  40387. (function (BABYLON) {
  40388. var TargetCamera = /** @class */ (function (_super) {
  40389. __extends(TargetCamera, _super);
  40390. function TargetCamera(name, position, scene) {
  40391. var _this = _super.call(this, name, position, scene) || this;
  40392. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40393. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  40394. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  40395. _this.speed = 2.0;
  40396. _this.noRotationConstraint = false;
  40397. _this.lockedTarget = null;
  40398. _this._currentTarget = BABYLON.Vector3.Zero();
  40399. _this._viewMatrix = BABYLON.Matrix.Zero();
  40400. _this._camMatrix = BABYLON.Matrix.Zero();
  40401. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  40402. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  40403. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  40404. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  40405. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  40406. _this._lookAtTemp = BABYLON.Matrix.Zero();
  40407. _this._tempMatrix = BABYLON.Matrix.Zero();
  40408. return _this;
  40409. }
  40410. TargetCamera.prototype.getFrontPosition = function (distance) {
  40411. this.getWorldMatrix();
  40412. var direction = this.getTarget().subtract(this.position);
  40413. direction.normalize();
  40414. direction.scaleInPlace(distance);
  40415. return this.globalPosition.add(direction);
  40416. };
  40417. TargetCamera.prototype._getLockedTargetPosition = function () {
  40418. if (!this.lockedTarget) {
  40419. return null;
  40420. }
  40421. if (this.lockedTarget.absolutePosition) {
  40422. this.lockedTarget.computeWorldMatrix();
  40423. }
  40424. return this.lockedTarget.absolutePosition || this.lockedTarget;
  40425. };
  40426. TargetCamera.prototype.storeState = function () {
  40427. this._storedPosition = this.position.clone();
  40428. this._storedRotation = this.rotation.clone();
  40429. if (this.rotationQuaternion) {
  40430. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  40431. }
  40432. return _super.prototype.storeState.call(this);
  40433. };
  40434. /**
  40435. * Restored camera state. You must call storeState() first
  40436. */
  40437. TargetCamera.prototype._restoreStateValues = function () {
  40438. if (!_super.prototype._restoreStateValues.call(this)) {
  40439. return false;
  40440. }
  40441. this.position = this._storedPosition.clone();
  40442. this.rotation = this._storedRotation.clone();
  40443. if (this.rotationQuaternion) {
  40444. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  40445. }
  40446. this.cameraDirection.copyFromFloats(0, 0, 0);
  40447. this.cameraRotation.copyFromFloats(0, 0);
  40448. return true;
  40449. };
  40450. // Cache
  40451. TargetCamera.prototype._initCache = function () {
  40452. _super.prototype._initCache.call(this);
  40453. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40454. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40455. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40456. };
  40457. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  40458. if (!ignoreParentClass) {
  40459. _super.prototype._updateCache.call(this);
  40460. }
  40461. var lockedTargetPosition = this._getLockedTargetPosition();
  40462. if (!lockedTargetPosition) {
  40463. this._cache.lockedTarget = null;
  40464. }
  40465. else {
  40466. if (!this._cache.lockedTarget) {
  40467. this._cache.lockedTarget = lockedTargetPosition.clone();
  40468. }
  40469. else {
  40470. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  40471. }
  40472. }
  40473. this._cache.rotation.copyFrom(this.rotation);
  40474. if (this.rotationQuaternion)
  40475. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40476. };
  40477. // Synchronized
  40478. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  40479. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  40480. return false;
  40481. }
  40482. var lockedTargetPosition = this._getLockedTargetPosition();
  40483. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  40484. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  40485. };
  40486. // Methods
  40487. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  40488. var engine = this.getEngine();
  40489. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  40490. };
  40491. // Target
  40492. TargetCamera.prototype.setTarget = function (target) {
  40493. this.upVector.normalize();
  40494. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  40495. this._camMatrix.invert();
  40496. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  40497. var vDir = target.subtract(this.position);
  40498. if (vDir.x >= 0.0) {
  40499. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  40500. }
  40501. else {
  40502. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  40503. }
  40504. this.rotation.z = 0;
  40505. if (isNaN(this.rotation.x)) {
  40506. this.rotation.x = 0;
  40507. }
  40508. if (isNaN(this.rotation.y)) {
  40509. this.rotation.y = 0;
  40510. }
  40511. if (isNaN(this.rotation.z)) {
  40512. this.rotation.z = 0;
  40513. }
  40514. if (this.rotationQuaternion) {
  40515. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40516. }
  40517. };
  40518. /**
  40519. * Return the current target position of the camera. This value is expressed in local space.
  40520. */
  40521. TargetCamera.prototype.getTarget = function () {
  40522. return this._currentTarget;
  40523. };
  40524. TargetCamera.prototype._decideIfNeedsToMove = function () {
  40525. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40526. };
  40527. TargetCamera.prototype._updatePosition = function () {
  40528. if (this.parent) {
  40529. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  40530. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  40531. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  40532. return;
  40533. }
  40534. this.position.addInPlace(this.cameraDirection);
  40535. };
  40536. TargetCamera.prototype._checkInputs = function () {
  40537. var needToMove = this._decideIfNeedsToMove();
  40538. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  40539. // Move
  40540. if (needToMove) {
  40541. this._updatePosition();
  40542. }
  40543. // Rotate
  40544. if (needToRotate) {
  40545. this.rotation.x += this.cameraRotation.x;
  40546. this.rotation.y += this.cameraRotation.y;
  40547. //rotate, if quaternion is set and rotation was used
  40548. if (this.rotationQuaternion) {
  40549. var len = this.rotation.lengthSquared();
  40550. if (len) {
  40551. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40552. }
  40553. }
  40554. if (!this.noRotationConstraint) {
  40555. var limit = (Math.PI / 2) * 0.95;
  40556. if (this.rotation.x > limit)
  40557. this.rotation.x = limit;
  40558. if (this.rotation.x < -limit)
  40559. this.rotation.x = -limit;
  40560. }
  40561. }
  40562. // Inertia
  40563. if (needToMove) {
  40564. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  40565. this.cameraDirection.x = 0;
  40566. }
  40567. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  40568. this.cameraDirection.y = 0;
  40569. }
  40570. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  40571. this.cameraDirection.z = 0;
  40572. }
  40573. this.cameraDirection.scaleInPlace(this.inertia);
  40574. }
  40575. if (needToRotate) {
  40576. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  40577. this.cameraRotation.x = 0;
  40578. }
  40579. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  40580. this.cameraRotation.y = 0;
  40581. }
  40582. this.cameraRotation.scaleInPlace(this.inertia);
  40583. }
  40584. _super.prototype._checkInputs.call(this);
  40585. };
  40586. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  40587. if (this.rotationQuaternion) {
  40588. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  40589. }
  40590. else {
  40591. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  40592. }
  40593. //update the up vector!
  40594. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  40595. };
  40596. TargetCamera.prototype._getViewMatrix = function () {
  40597. if (this.lockedTarget) {
  40598. this.setTarget(this._getLockedTargetPosition());
  40599. }
  40600. // Compute
  40601. this._updateCameraRotationMatrix();
  40602. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  40603. // Computing target and final matrix
  40604. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  40605. if (this.getScene().useRightHandedSystem) {
  40606. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40607. }
  40608. else {
  40609. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40610. }
  40611. return this._viewMatrix;
  40612. };
  40613. /**
  40614. * @override
  40615. * Override Camera.createRigCamera
  40616. */
  40617. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40618. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  40619. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  40620. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  40621. if (!this.rotationQuaternion) {
  40622. this.rotationQuaternion = new BABYLON.Quaternion();
  40623. }
  40624. rigCamera._cameraRigParams = {};
  40625. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  40626. }
  40627. return rigCamera;
  40628. }
  40629. return null;
  40630. };
  40631. /**
  40632. * @override
  40633. * Override Camera._updateRigCameras
  40634. */
  40635. TargetCamera.prototype._updateRigCameras = function () {
  40636. var camLeft = this._rigCameras[0];
  40637. var camRight = this._rigCameras[1];
  40638. switch (this.cameraRigMode) {
  40639. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40640. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40641. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40642. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40643. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  40644. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  40645. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  40646. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  40647. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  40648. camLeft.setTarget(this.getTarget());
  40649. camRight.setTarget(this.getTarget());
  40650. break;
  40651. case BABYLON.Camera.RIG_MODE_VR:
  40652. if (camLeft.rotationQuaternion) {
  40653. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40654. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40655. }
  40656. else {
  40657. camLeft.rotation.copyFrom(this.rotation);
  40658. camRight.rotation.copyFrom(this.rotation);
  40659. }
  40660. camLeft.position.copyFrom(this.position);
  40661. camRight.position.copyFrom(this.position);
  40662. break;
  40663. }
  40664. _super.prototype._updateRigCameras.call(this);
  40665. };
  40666. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  40667. if (!this._rigCamTransformMatrix) {
  40668. this._rigCamTransformMatrix = new BABYLON.Matrix();
  40669. }
  40670. var target = this.getTarget();
  40671. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  40672. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  40673. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  40674. };
  40675. TargetCamera.prototype.getClassName = function () {
  40676. return "TargetCamera";
  40677. };
  40678. __decorate([
  40679. BABYLON.serializeAsVector3()
  40680. ], TargetCamera.prototype, "rotation", void 0);
  40681. __decorate([
  40682. BABYLON.serialize()
  40683. ], TargetCamera.prototype, "speed", void 0);
  40684. __decorate([
  40685. BABYLON.serializeAsMeshReference("lockedTargetId")
  40686. ], TargetCamera.prototype, "lockedTarget", void 0);
  40687. return TargetCamera;
  40688. }(BABYLON.Camera));
  40689. BABYLON.TargetCamera = TargetCamera;
  40690. })(BABYLON || (BABYLON = {}));
  40691. //# sourceMappingURL=babylon.targetCamera.js.map
  40692. var BABYLON;
  40693. (function (BABYLON) {
  40694. var FreeCameraMouseInput = /** @class */ (function () {
  40695. function FreeCameraMouseInput(touchEnabled) {
  40696. if (touchEnabled === void 0) { touchEnabled = true; }
  40697. this.touchEnabled = touchEnabled;
  40698. this.buttons = [0, 1, 2];
  40699. this.angularSensibility = 2000.0;
  40700. this.previousPosition = null;
  40701. }
  40702. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  40703. var _this = this;
  40704. var engine = this.camera.getEngine();
  40705. if (!this._pointerInput) {
  40706. this._pointerInput = function (p, s) {
  40707. var evt = p.event;
  40708. if (engine.isInVRExclusivePointerMode) {
  40709. return;
  40710. }
  40711. if (!_this.touchEnabled && evt.pointerType === "touch") {
  40712. return;
  40713. }
  40714. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  40715. return;
  40716. }
  40717. var srcElement = (evt.srcElement || evt.target);
  40718. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40719. try {
  40720. srcElement.setPointerCapture(evt.pointerId);
  40721. }
  40722. catch (e) {
  40723. //Nothing to do with the error. Execution will continue.
  40724. }
  40725. _this.previousPosition = {
  40726. x: evt.clientX,
  40727. y: evt.clientY
  40728. };
  40729. if (!noPreventDefault) {
  40730. evt.preventDefault();
  40731. element.focus();
  40732. }
  40733. }
  40734. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40735. try {
  40736. srcElement.releasePointerCapture(evt.pointerId);
  40737. }
  40738. catch (e) {
  40739. //Nothing to do with the error.
  40740. }
  40741. _this.previousPosition = null;
  40742. if (!noPreventDefault) {
  40743. evt.preventDefault();
  40744. }
  40745. }
  40746. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40747. if (!_this.previousPosition || engine.isPointerLock) {
  40748. return;
  40749. }
  40750. var offsetX = evt.clientX - _this.previousPosition.x;
  40751. var offsetY = evt.clientY - _this.previousPosition.y;
  40752. if (_this.camera.getScene().useRightHandedSystem) {
  40753. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40754. }
  40755. else {
  40756. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40757. }
  40758. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40759. _this.previousPosition = {
  40760. x: evt.clientX,
  40761. y: evt.clientY
  40762. };
  40763. if (!noPreventDefault) {
  40764. evt.preventDefault();
  40765. }
  40766. }
  40767. };
  40768. }
  40769. this._onMouseMove = function (evt) {
  40770. if (!engine.isPointerLock) {
  40771. return;
  40772. }
  40773. if (engine.isInVRExclusivePointerMode) {
  40774. return;
  40775. }
  40776. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40777. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40778. if (_this.camera.getScene().useRightHandedSystem) {
  40779. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40780. }
  40781. else {
  40782. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40783. }
  40784. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40785. _this.previousPosition = null;
  40786. if (!noPreventDefault) {
  40787. evt.preventDefault();
  40788. }
  40789. };
  40790. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  40791. element.addEventListener("mousemove", this._onMouseMove, false);
  40792. };
  40793. FreeCameraMouseInput.prototype.detachControl = function (element) {
  40794. if (this._observer && element) {
  40795. this.camera.getScene().onPointerObservable.remove(this._observer);
  40796. if (this._onMouseMove) {
  40797. element.removeEventListener("mousemove", this._onMouseMove);
  40798. }
  40799. this._observer = null;
  40800. this._onMouseMove = null;
  40801. this.previousPosition = null;
  40802. }
  40803. };
  40804. FreeCameraMouseInput.prototype.getClassName = function () {
  40805. return "FreeCameraMouseInput";
  40806. };
  40807. FreeCameraMouseInput.prototype.getSimpleName = function () {
  40808. return "mouse";
  40809. };
  40810. __decorate([
  40811. BABYLON.serialize()
  40812. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  40813. __decorate([
  40814. BABYLON.serialize()
  40815. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  40816. return FreeCameraMouseInput;
  40817. }());
  40818. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  40819. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  40820. })(BABYLON || (BABYLON = {}));
  40821. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  40822. var BABYLON;
  40823. (function (BABYLON) {
  40824. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  40825. function FreeCameraKeyboardMoveInput() {
  40826. this._keys = new Array();
  40827. this.keysUp = [38];
  40828. this.keysDown = [40];
  40829. this.keysLeft = [37];
  40830. this.keysRight = [39];
  40831. }
  40832. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  40833. var _this = this;
  40834. if (this._onCanvasBlurObserver) {
  40835. return;
  40836. }
  40837. this._scene = this.camera.getScene();
  40838. this._engine = this._scene.getEngine();
  40839. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  40840. _this._keys = [];
  40841. });
  40842. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  40843. var evt = info.event;
  40844. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  40845. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40846. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40847. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40848. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40849. var index = _this._keys.indexOf(evt.keyCode);
  40850. if (index === -1) {
  40851. _this._keys.push(evt.keyCode);
  40852. }
  40853. if (!noPreventDefault) {
  40854. evt.preventDefault();
  40855. }
  40856. }
  40857. }
  40858. else {
  40859. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40860. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40861. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40862. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40863. var index = _this._keys.indexOf(evt.keyCode);
  40864. if (index >= 0) {
  40865. _this._keys.splice(index, 1);
  40866. }
  40867. if (!noPreventDefault) {
  40868. evt.preventDefault();
  40869. }
  40870. }
  40871. }
  40872. });
  40873. };
  40874. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  40875. if (this._scene) {
  40876. if (this._onKeyboardObserver) {
  40877. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  40878. }
  40879. if (this._onCanvasBlurObserver) {
  40880. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  40881. }
  40882. this._onKeyboardObserver = null;
  40883. this._onCanvasBlurObserver = null;
  40884. }
  40885. this._keys = [];
  40886. };
  40887. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  40888. if (this._onKeyboardObserver) {
  40889. var camera = this.camera;
  40890. // Keyboard
  40891. for (var index = 0; index < this._keys.length; index++) {
  40892. var keyCode = this._keys[index];
  40893. var speed = camera._computeLocalCameraSpeed();
  40894. if (this.keysLeft.indexOf(keyCode) !== -1) {
  40895. camera._localDirection.copyFromFloats(-speed, 0, 0);
  40896. }
  40897. else if (this.keysUp.indexOf(keyCode) !== -1) {
  40898. camera._localDirection.copyFromFloats(0, 0, speed);
  40899. }
  40900. else if (this.keysRight.indexOf(keyCode) !== -1) {
  40901. camera._localDirection.copyFromFloats(speed, 0, 0);
  40902. }
  40903. else if (this.keysDown.indexOf(keyCode) !== -1) {
  40904. camera._localDirection.copyFromFloats(0, 0, -speed);
  40905. }
  40906. if (camera.getScene().useRightHandedSystem) {
  40907. camera._localDirection.z *= -1;
  40908. }
  40909. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  40910. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  40911. camera.cameraDirection.addInPlace(camera._transformedDirection);
  40912. }
  40913. }
  40914. };
  40915. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  40916. return "FreeCameraKeyboardMoveInput";
  40917. };
  40918. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  40919. this._keys = [];
  40920. };
  40921. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  40922. return "keyboard";
  40923. };
  40924. __decorate([
  40925. BABYLON.serialize()
  40926. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  40927. __decorate([
  40928. BABYLON.serialize()
  40929. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  40930. __decorate([
  40931. BABYLON.serialize()
  40932. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  40933. __decorate([
  40934. BABYLON.serialize()
  40935. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  40936. return FreeCameraKeyboardMoveInput;
  40937. }());
  40938. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  40939. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  40940. })(BABYLON || (BABYLON = {}));
  40941. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  40942. var BABYLON;
  40943. (function (BABYLON) {
  40944. var FreeCameraInputsManager = /** @class */ (function (_super) {
  40945. __extends(FreeCameraInputsManager, _super);
  40946. function FreeCameraInputsManager(camera) {
  40947. return _super.call(this, camera) || this;
  40948. }
  40949. FreeCameraInputsManager.prototype.addKeyboard = function () {
  40950. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  40951. return this;
  40952. };
  40953. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  40954. if (touchEnabled === void 0) { touchEnabled = true; }
  40955. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  40956. return this;
  40957. };
  40958. FreeCameraInputsManager.prototype.addGamepad = function () {
  40959. this.add(new BABYLON.FreeCameraGamepadInput());
  40960. return this;
  40961. };
  40962. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  40963. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  40964. return this;
  40965. };
  40966. FreeCameraInputsManager.prototype.addTouch = function () {
  40967. this.add(new BABYLON.FreeCameraTouchInput());
  40968. return this;
  40969. };
  40970. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  40971. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  40972. return this;
  40973. };
  40974. return FreeCameraInputsManager;
  40975. }(BABYLON.CameraInputsManager));
  40976. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  40977. })(BABYLON || (BABYLON = {}));
  40978. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  40979. var BABYLON;
  40980. (function (BABYLON) {
  40981. var FreeCamera = /** @class */ (function (_super) {
  40982. __extends(FreeCamera, _super);
  40983. function FreeCamera(name, position, scene) {
  40984. var _this = _super.call(this, name, position, scene) || this;
  40985. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  40986. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  40987. _this.checkCollisions = false;
  40988. _this.applyGravity = false;
  40989. _this._needMoveForGravity = false;
  40990. _this._oldPosition = BABYLON.Vector3.Zero();
  40991. _this._diffPosition = BABYLON.Vector3.Zero();
  40992. _this._newPosition = BABYLON.Vector3.Zero();
  40993. // Collisions
  40994. _this._collisionMask = -1;
  40995. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40996. if (collidedMesh === void 0) { collidedMesh = null; }
  40997. //TODO move this to the collision coordinator!
  40998. if (_this.getScene().workerCollisions)
  40999. newPosition.multiplyInPlace(_this._collider._radius);
  41000. var updatePosition = function (newPos) {
  41001. _this._newPosition.copyFrom(newPos);
  41002. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  41003. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  41004. _this.position.addInPlace(_this._diffPosition);
  41005. if (_this.onCollide && collidedMesh) {
  41006. _this.onCollide(collidedMesh);
  41007. }
  41008. }
  41009. };
  41010. updatePosition(newPosition);
  41011. };
  41012. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  41013. _this.inputs.addKeyboard().addMouse();
  41014. return _this;
  41015. }
  41016. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  41017. //-- begin properties for backward compatibility for inputs
  41018. /**
  41019. * Gets the input sensibility for a mouse input. (default is 2000.0)
  41020. * Higher values reduce sensitivity.
  41021. */
  41022. get: function () {
  41023. var mouse = this.inputs.attached["mouse"];
  41024. if (mouse)
  41025. return mouse.angularSensibility;
  41026. return 0;
  41027. },
  41028. /**
  41029. * Sets the input sensibility for a mouse input. (default is 2000.0)
  41030. * Higher values reduce sensitivity.
  41031. */
  41032. set: function (value) {
  41033. var mouse = this.inputs.attached["mouse"];
  41034. if (mouse)
  41035. mouse.angularSensibility = value;
  41036. },
  41037. enumerable: true,
  41038. configurable: true
  41039. });
  41040. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  41041. get: function () {
  41042. var keyboard = this.inputs.attached["keyboard"];
  41043. if (keyboard)
  41044. return keyboard.keysUp;
  41045. return [];
  41046. },
  41047. set: function (value) {
  41048. var keyboard = this.inputs.attached["keyboard"];
  41049. if (keyboard)
  41050. keyboard.keysUp = value;
  41051. },
  41052. enumerable: true,
  41053. configurable: true
  41054. });
  41055. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  41056. get: function () {
  41057. var keyboard = this.inputs.attached["keyboard"];
  41058. if (keyboard)
  41059. return keyboard.keysDown;
  41060. return [];
  41061. },
  41062. set: function (value) {
  41063. var keyboard = this.inputs.attached["keyboard"];
  41064. if (keyboard)
  41065. keyboard.keysDown = value;
  41066. },
  41067. enumerable: true,
  41068. configurable: true
  41069. });
  41070. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  41071. get: function () {
  41072. var keyboard = this.inputs.attached["keyboard"];
  41073. if (keyboard)
  41074. return keyboard.keysLeft;
  41075. return [];
  41076. },
  41077. set: function (value) {
  41078. var keyboard = this.inputs.attached["keyboard"];
  41079. if (keyboard)
  41080. keyboard.keysLeft = value;
  41081. },
  41082. enumerable: true,
  41083. configurable: true
  41084. });
  41085. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  41086. get: function () {
  41087. var keyboard = this.inputs.attached["keyboard"];
  41088. if (keyboard)
  41089. return keyboard.keysRight;
  41090. return [];
  41091. },
  41092. set: function (value) {
  41093. var keyboard = this.inputs.attached["keyboard"];
  41094. if (keyboard)
  41095. keyboard.keysRight = value;
  41096. },
  41097. enumerable: true,
  41098. configurable: true
  41099. });
  41100. // Controls
  41101. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  41102. this.inputs.attachElement(element, noPreventDefault);
  41103. };
  41104. FreeCamera.prototype.detachControl = function (element) {
  41105. this.inputs.detachElement(element);
  41106. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  41107. this.cameraRotation = new BABYLON.Vector2(0, 0);
  41108. };
  41109. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  41110. get: function () {
  41111. return this._collisionMask;
  41112. },
  41113. set: function (mask) {
  41114. this._collisionMask = !isNaN(mask) ? mask : -1;
  41115. },
  41116. enumerable: true,
  41117. configurable: true
  41118. });
  41119. FreeCamera.prototype._collideWithWorld = function (displacement) {
  41120. var globalPosition;
  41121. if (this.parent) {
  41122. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  41123. }
  41124. else {
  41125. globalPosition = this.position;
  41126. }
  41127. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  41128. this._oldPosition.addInPlace(this.ellipsoidOffset);
  41129. if (!this._collider) {
  41130. this._collider = new BABYLON.Collider();
  41131. }
  41132. this._collider._radius = this.ellipsoid;
  41133. this._collider.collisionMask = this._collisionMask;
  41134. //no need for clone, as long as gravity is not on.
  41135. var actualDisplacement = displacement;
  41136. //add gravity to the direction to prevent the dual-collision checking
  41137. if (this.applyGravity) {
  41138. //this prevents mending with cameraDirection, a global variable of the free camera class.
  41139. actualDisplacement = displacement.add(this.getScene().gravity);
  41140. }
  41141. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  41142. };
  41143. FreeCamera.prototype._checkInputs = function () {
  41144. if (!this._localDirection) {
  41145. this._localDirection = BABYLON.Vector3.Zero();
  41146. this._transformedDirection = BABYLON.Vector3.Zero();
  41147. }
  41148. this.inputs.checkInputs();
  41149. _super.prototype._checkInputs.call(this);
  41150. };
  41151. FreeCamera.prototype._decideIfNeedsToMove = function () {
  41152. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  41153. };
  41154. FreeCamera.prototype._updatePosition = function () {
  41155. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  41156. this._collideWithWorld(this.cameraDirection);
  41157. }
  41158. else {
  41159. _super.prototype._updatePosition.call(this);
  41160. }
  41161. };
  41162. FreeCamera.prototype.dispose = function () {
  41163. this.inputs.clear();
  41164. _super.prototype.dispose.call(this);
  41165. };
  41166. FreeCamera.prototype.getClassName = function () {
  41167. return "FreeCamera";
  41168. };
  41169. __decorate([
  41170. BABYLON.serializeAsVector3()
  41171. ], FreeCamera.prototype, "ellipsoid", void 0);
  41172. __decorate([
  41173. BABYLON.serializeAsVector3()
  41174. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  41175. __decorate([
  41176. BABYLON.serialize()
  41177. ], FreeCamera.prototype, "checkCollisions", void 0);
  41178. __decorate([
  41179. BABYLON.serialize()
  41180. ], FreeCamera.prototype, "applyGravity", void 0);
  41181. return FreeCamera;
  41182. }(BABYLON.TargetCamera));
  41183. BABYLON.FreeCamera = FreeCamera;
  41184. })(BABYLON || (BABYLON = {}));
  41185. //# sourceMappingURL=babylon.freeCamera.js.map
  41186. var BABYLON;
  41187. (function (BABYLON) {
  41188. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  41189. function ArcRotateCameraKeyboardMoveInput() {
  41190. this._keys = new Array();
  41191. this.keysUp = [38];
  41192. this.keysDown = [40];
  41193. this.keysLeft = [37];
  41194. this.keysRight = [39];
  41195. this.keysReset = [220];
  41196. this.panningSensibility = 50.0;
  41197. this.zoomingSensibility = 25.0;
  41198. this.useAltToZoom = true;
  41199. }
  41200. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  41201. var _this = this;
  41202. if (this._onCanvasBlurObserver) {
  41203. return;
  41204. }
  41205. this._scene = this.camera.getScene();
  41206. this._engine = this._scene.getEngine();
  41207. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  41208. _this._keys = [];
  41209. });
  41210. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  41211. var evt = info.event;
  41212. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  41213. _this._ctrlPressed = evt.ctrlKey;
  41214. _this._altPressed = evt.altKey;
  41215. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41216. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41217. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41218. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41219. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41220. var index = _this._keys.indexOf(evt.keyCode);
  41221. if (index === -1) {
  41222. _this._keys.push(evt.keyCode);
  41223. }
  41224. if (evt.preventDefault) {
  41225. if (!noPreventDefault) {
  41226. evt.preventDefault();
  41227. }
  41228. }
  41229. }
  41230. }
  41231. else {
  41232. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41233. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41234. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41235. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41236. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41237. var index = _this._keys.indexOf(evt.keyCode);
  41238. if (index >= 0) {
  41239. _this._keys.splice(index, 1);
  41240. }
  41241. if (evt.preventDefault) {
  41242. if (!noPreventDefault) {
  41243. evt.preventDefault();
  41244. }
  41245. }
  41246. }
  41247. }
  41248. });
  41249. };
  41250. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41251. if (this._scene) {
  41252. if (this._onKeyboardObserver) {
  41253. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41254. }
  41255. if (this._onCanvasBlurObserver) {
  41256. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41257. }
  41258. this._onKeyboardObserver = null;
  41259. this._onCanvasBlurObserver = null;
  41260. }
  41261. this._keys = [];
  41262. };
  41263. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41264. if (this._onKeyboardObserver) {
  41265. var camera = this.camera;
  41266. for (var index = 0; index < this._keys.length; index++) {
  41267. var keyCode = this._keys[index];
  41268. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41269. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41270. camera.inertialPanningX -= 1 / this.panningSensibility;
  41271. }
  41272. else {
  41273. camera.inertialAlphaOffset -= 0.01;
  41274. }
  41275. }
  41276. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41277. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41278. camera.inertialPanningY += 1 / this.panningSensibility;
  41279. }
  41280. else if (this._altPressed && this.useAltToZoom) {
  41281. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  41282. }
  41283. else {
  41284. camera.inertialBetaOffset -= 0.01;
  41285. }
  41286. }
  41287. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41288. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41289. camera.inertialPanningX += 1 / this.panningSensibility;
  41290. }
  41291. else {
  41292. camera.inertialAlphaOffset += 0.01;
  41293. }
  41294. }
  41295. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41296. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41297. camera.inertialPanningY -= 1 / this.panningSensibility;
  41298. }
  41299. else if (this._altPressed && this.useAltToZoom) {
  41300. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  41301. }
  41302. else {
  41303. camera.inertialBetaOffset += 0.01;
  41304. }
  41305. }
  41306. else if (this.keysReset.indexOf(keyCode) !== -1) {
  41307. camera.restoreState();
  41308. }
  41309. }
  41310. }
  41311. };
  41312. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  41313. return "ArcRotateCameraKeyboardMoveInput";
  41314. };
  41315. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41316. return "keyboard";
  41317. };
  41318. __decorate([
  41319. BABYLON.serialize()
  41320. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41321. __decorate([
  41322. BABYLON.serialize()
  41323. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41324. __decorate([
  41325. BABYLON.serialize()
  41326. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41327. __decorate([
  41328. BABYLON.serialize()
  41329. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41330. __decorate([
  41331. BABYLON.serialize()
  41332. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  41333. __decorate([
  41334. BABYLON.serialize()
  41335. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  41336. __decorate([
  41337. BABYLON.serialize()
  41338. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  41339. __decorate([
  41340. BABYLON.serialize()
  41341. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  41342. return ArcRotateCameraKeyboardMoveInput;
  41343. }());
  41344. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  41345. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  41346. })(BABYLON || (BABYLON = {}));
  41347. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  41348. var BABYLON;
  41349. (function (BABYLON) {
  41350. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  41351. function ArcRotateCameraMouseWheelInput() {
  41352. this.wheelPrecision = 3.0;
  41353. /**
  41354. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  41355. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  41356. */
  41357. this.wheelDeltaPercentage = 0;
  41358. }
  41359. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  41360. var _this = this;
  41361. this._wheel = function (p, s) {
  41362. //sanity check - this should be a PointerWheel event.
  41363. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  41364. return;
  41365. var event = p.event;
  41366. var delta = 0;
  41367. if (event.wheelDelta) {
  41368. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  41369. }
  41370. else if (event.detail) {
  41371. delta = -event.detail / _this.wheelPrecision;
  41372. }
  41373. if (delta)
  41374. _this.camera.inertialRadiusOffset += delta;
  41375. if (event.preventDefault) {
  41376. if (!noPreventDefault) {
  41377. event.preventDefault();
  41378. }
  41379. }
  41380. };
  41381. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  41382. };
  41383. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  41384. if (this._observer && element) {
  41385. this.camera.getScene().onPointerObservable.remove(this._observer);
  41386. this._observer = null;
  41387. this._wheel = null;
  41388. }
  41389. };
  41390. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  41391. return "ArcRotateCameraMouseWheelInput";
  41392. };
  41393. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  41394. return "mousewheel";
  41395. };
  41396. __decorate([
  41397. BABYLON.serialize()
  41398. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  41399. __decorate([
  41400. BABYLON.serialize()
  41401. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  41402. return ArcRotateCameraMouseWheelInput;
  41403. }());
  41404. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  41405. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  41406. })(BABYLON || (BABYLON = {}));
  41407. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  41408. var BABYLON;
  41409. (function (BABYLON) {
  41410. var ArcRotateCameraPointersInput = /** @class */ (function () {
  41411. function ArcRotateCameraPointersInput() {
  41412. this.buttons = [0, 1, 2];
  41413. this.angularSensibilityX = 1000.0;
  41414. this.angularSensibilityY = 1000.0;
  41415. this.pinchPrecision = 12.0;
  41416. /**
  41417. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  41418. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  41419. */
  41420. this.pinchDeltaPercentage = 0;
  41421. this.panningSensibility = 1000.0;
  41422. this.multiTouchPanning = true;
  41423. this.multiTouchPanAndZoom = true;
  41424. this._isPanClick = false;
  41425. this.pinchInwards = true;
  41426. }
  41427. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  41428. var _this = this;
  41429. var engine = this.camera.getEngine();
  41430. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  41431. var pointA = null;
  41432. var pointB = null;
  41433. var previousPinchSquaredDistance = 0;
  41434. var initialDistance = 0;
  41435. var twoFingerActivityCount = 0;
  41436. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  41437. this._pointerInput = function (p, s) {
  41438. var evt = p.event;
  41439. var isTouch = p.event.pointerType === "touch";
  41440. if (engine.isInVRExclusivePointerMode) {
  41441. return;
  41442. }
  41443. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41444. return;
  41445. }
  41446. var srcElement = (evt.srcElement || evt.target);
  41447. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41448. try {
  41449. srcElement.setPointerCapture(evt.pointerId);
  41450. }
  41451. catch (e) {
  41452. //Nothing to do with the error. Execution will continue.
  41453. }
  41454. // Manage panning with pan button click
  41455. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  41456. // manage pointers
  41457. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  41458. if (pointA === null) {
  41459. pointA = cacheSoloPointer;
  41460. }
  41461. else if (pointB === null) {
  41462. pointB = cacheSoloPointer;
  41463. }
  41464. if (!noPreventDefault) {
  41465. evt.preventDefault();
  41466. element.focus();
  41467. }
  41468. }
  41469. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  41470. _this.camera.restoreState();
  41471. }
  41472. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41473. try {
  41474. srcElement.releasePointerCapture(evt.pointerId);
  41475. }
  41476. catch (e) {
  41477. //Nothing to do with the error.
  41478. }
  41479. cacheSoloPointer = null;
  41480. previousPinchSquaredDistance = 0;
  41481. previousMultiTouchPanPosition.isPaning = false;
  41482. previousMultiTouchPanPosition.isPinching = false;
  41483. twoFingerActivityCount = 0;
  41484. initialDistance = 0;
  41485. if (!isTouch) {
  41486. pointB = null; // Mouse and pen are mono pointer
  41487. }
  41488. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  41489. //but emptying completly pointers collection is required to fix a bug on iPhone :
  41490. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  41491. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  41492. if (engine.badOS) {
  41493. pointA = pointB = null;
  41494. }
  41495. else {
  41496. //only remove the impacted pointer in case of multitouch allowing on most
  41497. //platforms switching from rotate to zoom and pan seamlessly.
  41498. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  41499. pointA = pointB;
  41500. pointB = null;
  41501. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41502. }
  41503. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  41504. pointB = null;
  41505. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41506. }
  41507. else {
  41508. pointA = pointB = null;
  41509. }
  41510. }
  41511. if (!noPreventDefault) {
  41512. evt.preventDefault();
  41513. }
  41514. }
  41515. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41516. if (!noPreventDefault) {
  41517. evt.preventDefault();
  41518. }
  41519. // One button down
  41520. if (pointA && pointB === null && cacheSoloPointer) {
  41521. if (_this.panningSensibility !== 0 &&
  41522. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  41523. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  41524. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  41525. }
  41526. else {
  41527. var offsetX = evt.clientX - cacheSoloPointer.x;
  41528. var offsetY = evt.clientY - cacheSoloPointer.y;
  41529. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41530. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41531. }
  41532. cacheSoloPointer.x = evt.clientX;
  41533. cacheSoloPointer.y = evt.clientY;
  41534. }
  41535. else if (pointA && pointB) {
  41536. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  41537. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  41538. ed.x = evt.clientX;
  41539. ed.y = evt.clientY;
  41540. var direction = _this.pinchInwards ? 1 : -1;
  41541. var distX = pointA.x - pointB.x;
  41542. var distY = pointA.y - pointB.y;
  41543. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  41544. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  41545. if (previousPinchSquaredDistance === 0) {
  41546. initialDistance = pinchDistance;
  41547. previousPinchSquaredDistance = pinchSquaredDistance;
  41548. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  41549. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  41550. return;
  41551. }
  41552. if (_this.multiTouchPanAndZoom) {
  41553. if (_this.pinchDeltaPercentage) {
  41554. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41555. }
  41556. else {
  41557. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41558. (_this.pinchPrecision *
  41559. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41560. direction);
  41561. }
  41562. if (_this.panningSensibility !== 0) {
  41563. var pointersCenterX = (pointA.x + pointB.x) / 2;
  41564. var pointersCenterY = (pointA.y + pointB.y) / 2;
  41565. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  41566. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  41567. previousMultiTouchPanPosition.x = pointersCenterX;
  41568. previousMultiTouchPanPosition.y = pointersCenterY;
  41569. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  41570. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  41571. }
  41572. }
  41573. else {
  41574. twoFingerActivityCount++;
  41575. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  41576. if (_this.pinchDeltaPercentage) {
  41577. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41578. }
  41579. else {
  41580. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41581. (_this.pinchPrecision *
  41582. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41583. direction);
  41584. }
  41585. previousMultiTouchPanPosition.isPaning = false;
  41586. previousMultiTouchPanPosition.isPinching = true;
  41587. }
  41588. else {
  41589. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  41590. if (!previousMultiTouchPanPosition.isPaning) {
  41591. previousMultiTouchPanPosition.isPaning = true;
  41592. previousMultiTouchPanPosition.isPinching = false;
  41593. previousMultiTouchPanPosition.x = ed.x;
  41594. previousMultiTouchPanPosition.y = ed.y;
  41595. return;
  41596. }
  41597. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  41598. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  41599. }
  41600. }
  41601. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  41602. previousMultiTouchPanPosition.x = ed.x;
  41603. previousMultiTouchPanPosition.y = ed.y;
  41604. }
  41605. }
  41606. previousPinchSquaredDistance = pinchSquaredDistance;
  41607. }
  41608. }
  41609. };
  41610. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  41611. this._onContextMenu = function (evt) {
  41612. evt.preventDefault();
  41613. };
  41614. if (!this.camera._useCtrlForPanning) {
  41615. element.addEventListener("contextmenu", this._onContextMenu, false);
  41616. }
  41617. this._onLostFocus = function () {
  41618. //this._keys = [];
  41619. pointA = pointB = null;
  41620. previousPinchSquaredDistance = 0;
  41621. previousMultiTouchPanPosition.isPaning = false;
  41622. previousMultiTouchPanPosition.isPinching = false;
  41623. twoFingerActivityCount = 0;
  41624. cacheSoloPointer = null;
  41625. initialDistance = 0;
  41626. };
  41627. this._onMouseMove = function (evt) {
  41628. if (!engine.isPointerLock) {
  41629. return;
  41630. }
  41631. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41632. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41633. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41634. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41635. if (!noPreventDefault) {
  41636. evt.preventDefault();
  41637. }
  41638. };
  41639. this._onGestureStart = function (e) {
  41640. if (window.MSGesture === undefined) {
  41641. return;
  41642. }
  41643. if (!_this._MSGestureHandler) {
  41644. _this._MSGestureHandler = new MSGesture();
  41645. _this._MSGestureHandler.target = element;
  41646. }
  41647. _this._MSGestureHandler.addPointer(e.pointerId);
  41648. };
  41649. this._onGesture = function (e) {
  41650. _this.camera.radius *= e.scale;
  41651. if (e.preventDefault) {
  41652. if (!noPreventDefault) {
  41653. e.stopPropagation();
  41654. e.preventDefault();
  41655. }
  41656. }
  41657. };
  41658. element.addEventListener("mousemove", this._onMouseMove, false);
  41659. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  41660. element.addEventListener("MSGestureChange", this._onGesture, false);
  41661. BABYLON.Tools.RegisterTopRootEvents([
  41662. { name: "blur", handler: this._onLostFocus }
  41663. ]);
  41664. };
  41665. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  41666. if (this._onLostFocus) {
  41667. BABYLON.Tools.UnregisterTopRootEvents([
  41668. { name: "blur", handler: this._onLostFocus }
  41669. ]);
  41670. }
  41671. if (element && this._observer) {
  41672. this.camera.getScene().onPointerObservable.remove(this._observer);
  41673. this._observer = null;
  41674. if (this._onContextMenu) {
  41675. element.removeEventListener("contextmenu", this._onContextMenu);
  41676. }
  41677. if (this._onMouseMove) {
  41678. element.removeEventListener("mousemove", this._onMouseMove);
  41679. }
  41680. if (this._onGestureStart) {
  41681. element.removeEventListener("MSPointerDown", this._onGestureStart);
  41682. }
  41683. if (this._onGesture) {
  41684. element.removeEventListener("MSGestureChange", this._onGesture);
  41685. }
  41686. this._isPanClick = false;
  41687. this.pinchInwards = true;
  41688. this._onMouseMove = null;
  41689. this._onGestureStart = null;
  41690. this._onGesture = null;
  41691. this._MSGestureHandler = null;
  41692. this._onLostFocus = null;
  41693. this._onContextMenu = null;
  41694. }
  41695. };
  41696. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  41697. return "ArcRotateCameraPointersInput";
  41698. };
  41699. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  41700. return "pointers";
  41701. };
  41702. __decorate([
  41703. BABYLON.serialize()
  41704. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  41705. __decorate([
  41706. BABYLON.serialize()
  41707. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  41708. __decorate([
  41709. BABYLON.serialize()
  41710. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  41711. __decorate([
  41712. BABYLON.serialize()
  41713. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  41714. __decorate([
  41715. BABYLON.serialize()
  41716. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  41717. __decorate([
  41718. BABYLON.serialize()
  41719. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  41720. __decorate([
  41721. BABYLON.serialize()
  41722. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  41723. __decorate([
  41724. BABYLON.serialize()
  41725. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  41726. return ArcRotateCameraPointersInput;
  41727. }());
  41728. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  41729. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  41730. })(BABYLON || (BABYLON = {}));
  41731. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  41732. var BABYLON;
  41733. (function (BABYLON) {
  41734. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  41735. __extends(ArcRotateCameraInputsManager, _super);
  41736. function ArcRotateCameraInputsManager(camera) {
  41737. return _super.call(this, camera) || this;
  41738. }
  41739. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  41740. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  41741. return this;
  41742. };
  41743. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  41744. this.add(new BABYLON.ArcRotateCameraPointersInput());
  41745. return this;
  41746. };
  41747. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  41748. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  41749. return this;
  41750. };
  41751. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  41752. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  41753. return this;
  41754. };
  41755. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  41756. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  41757. return this;
  41758. };
  41759. return ArcRotateCameraInputsManager;
  41760. }(BABYLON.CameraInputsManager));
  41761. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  41762. })(BABYLON || (BABYLON = {}));
  41763. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  41764. var BABYLON;
  41765. (function (BABYLON) {
  41766. var ArcRotateCamera = /** @class */ (function (_super) {
  41767. __extends(ArcRotateCamera, _super);
  41768. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  41769. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  41770. _this.inertialAlphaOffset = 0;
  41771. _this.inertialBetaOffset = 0;
  41772. _this.inertialRadiusOffset = 0;
  41773. _this.lowerAlphaLimit = null;
  41774. _this.upperAlphaLimit = null;
  41775. _this.lowerBetaLimit = 0.01;
  41776. _this.upperBetaLimit = Math.PI;
  41777. _this.lowerRadiusLimit = null;
  41778. _this.upperRadiusLimit = null;
  41779. _this.inertialPanningX = 0;
  41780. _this.inertialPanningY = 0;
  41781. _this.pinchToPanMaxDistance = 20;
  41782. _this.panningDistanceLimit = null;
  41783. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  41784. _this.panningInertia = 0.9;
  41785. //-- end properties for backward compatibility for inputs
  41786. _this.zoomOnFactor = 1;
  41787. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  41788. _this.allowUpsideDown = true;
  41789. _this._viewMatrix = new BABYLON.Matrix();
  41790. // Panning
  41791. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  41792. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  41793. _this.checkCollisions = false;
  41794. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  41795. _this._previousPosition = BABYLON.Vector3.Zero();
  41796. _this._collisionVelocity = BABYLON.Vector3.Zero();
  41797. _this._newPosition = BABYLON.Vector3.Zero();
  41798. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41799. if (collidedMesh === void 0) { collidedMesh = null; }
  41800. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  41801. newPosition.multiplyInPlace(_this._collider._radius);
  41802. }
  41803. if (!collidedMesh) {
  41804. _this._previousPosition.copyFrom(_this.position);
  41805. }
  41806. else {
  41807. _this.setPosition(newPosition);
  41808. if (_this.onCollide) {
  41809. _this.onCollide(collidedMesh);
  41810. }
  41811. }
  41812. // Recompute because of constraints
  41813. var cosa = Math.cos(_this.alpha);
  41814. var sina = Math.sin(_this.alpha);
  41815. var cosb = Math.cos(_this.beta);
  41816. var sinb = Math.sin(_this.beta);
  41817. if (sinb === 0) {
  41818. sinb = 0.0001;
  41819. }
  41820. var target = _this._getTargetPosition();
  41821. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  41822. _this.position.copyFrom(_this._newPosition);
  41823. var up = _this.upVector;
  41824. if (_this.allowUpsideDown && _this.beta < 0) {
  41825. up = up.clone();
  41826. up = up.negate();
  41827. }
  41828. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  41829. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  41830. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  41831. _this._collisionTriggered = false;
  41832. };
  41833. _this._target = BABYLON.Vector3.Zero();
  41834. if (target) {
  41835. _this.setTarget(target);
  41836. }
  41837. _this.alpha = alpha;
  41838. _this.beta = beta;
  41839. _this.radius = radius;
  41840. _this.getViewMatrix();
  41841. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  41842. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  41843. return _this;
  41844. }
  41845. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  41846. get: function () {
  41847. return this._target;
  41848. },
  41849. set: function (value) {
  41850. this.setTarget(value);
  41851. },
  41852. enumerable: true,
  41853. configurable: true
  41854. });
  41855. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  41856. //-- begin properties for backward compatibility for inputs
  41857. get: function () {
  41858. var pointers = this.inputs.attached["pointers"];
  41859. if (pointers)
  41860. return pointers.angularSensibilityX;
  41861. return 0;
  41862. },
  41863. set: function (value) {
  41864. var pointers = this.inputs.attached["pointers"];
  41865. if (pointers) {
  41866. pointers.angularSensibilityX = value;
  41867. }
  41868. },
  41869. enumerable: true,
  41870. configurable: true
  41871. });
  41872. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  41873. get: function () {
  41874. var pointers = this.inputs.attached["pointers"];
  41875. if (pointers)
  41876. return pointers.angularSensibilityY;
  41877. return 0;
  41878. },
  41879. set: function (value) {
  41880. var pointers = this.inputs.attached["pointers"];
  41881. if (pointers) {
  41882. pointers.angularSensibilityY = value;
  41883. }
  41884. },
  41885. enumerable: true,
  41886. configurable: true
  41887. });
  41888. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  41889. get: function () {
  41890. var pointers = this.inputs.attached["pointers"];
  41891. if (pointers)
  41892. return pointers.pinchPrecision;
  41893. return 0;
  41894. },
  41895. set: function (value) {
  41896. var pointers = this.inputs.attached["pointers"];
  41897. if (pointers) {
  41898. pointers.pinchPrecision = value;
  41899. }
  41900. },
  41901. enumerable: true,
  41902. configurable: true
  41903. });
  41904. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  41905. get: function () {
  41906. var pointers = this.inputs.attached["pointers"];
  41907. if (pointers)
  41908. return pointers.pinchDeltaPercentage;
  41909. return 0;
  41910. },
  41911. set: function (value) {
  41912. var pointers = this.inputs.attached["pointers"];
  41913. if (pointers) {
  41914. pointers.pinchDeltaPercentage = value;
  41915. }
  41916. },
  41917. enumerable: true,
  41918. configurable: true
  41919. });
  41920. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  41921. get: function () {
  41922. var pointers = this.inputs.attached["pointers"];
  41923. if (pointers)
  41924. return pointers.panningSensibility;
  41925. return 0;
  41926. },
  41927. set: function (value) {
  41928. var pointers = this.inputs.attached["pointers"];
  41929. if (pointers) {
  41930. pointers.panningSensibility = value;
  41931. }
  41932. },
  41933. enumerable: true,
  41934. configurable: true
  41935. });
  41936. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  41937. get: function () {
  41938. var keyboard = this.inputs.attached["keyboard"];
  41939. if (keyboard)
  41940. return keyboard.keysUp;
  41941. return [];
  41942. },
  41943. set: function (value) {
  41944. var keyboard = this.inputs.attached["keyboard"];
  41945. if (keyboard)
  41946. keyboard.keysUp = value;
  41947. },
  41948. enumerable: true,
  41949. configurable: true
  41950. });
  41951. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  41952. get: function () {
  41953. var keyboard = this.inputs.attached["keyboard"];
  41954. if (keyboard)
  41955. return keyboard.keysDown;
  41956. return [];
  41957. },
  41958. set: function (value) {
  41959. var keyboard = this.inputs.attached["keyboard"];
  41960. if (keyboard)
  41961. keyboard.keysDown = value;
  41962. },
  41963. enumerable: true,
  41964. configurable: true
  41965. });
  41966. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  41967. get: function () {
  41968. var keyboard = this.inputs.attached["keyboard"];
  41969. if (keyboard)
  41970. return keyboard.keysLeft;
  41971. return [];
  41972. },
  41973. set: function (value) {
  41974. var keyboard = this.inputs.attached["keyboard"];
  41975. if (keyboard)
  41976. keyboard.keysLeft = value;
  41977. },
  41978. enumerable: true,
  41979. configurable: true
  41980. });
  41981. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  41982. get: function () {
  41983. var keyboard = this.inputs.attached["keyboard"];
  41984. if (keyboard)
  41985. return keyboard.keysRight;
  41986. return [];
  41987. },
  41988. set: function (value) {
  41989. var keyboard = this.inputs.attached["keyboard"];
  41990. if (keyboard)
  41991. keyboard.keysRight = value;
  41992. },
  41993. enumerable: true,
  41994. configurable: true
  41995. });
  41996. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  41997. get: function () {
  41998. var mousewheel = this.inputs.attached["mousewheel"];
  41999. if (mousewheel)
  42000. return mousewheel.wheelPrecision;
  42001. return 0;
  42002. },
  42003. set: function (value) {
  42004. var mousewheel = this.inputs.attached["mousewheel"];
  42005. if (mousewheel)
  42006. mousewheel.wheelPrecision = value;
  42007. },
  42008. enumerable: true,
  42009. configurable: true
  42010. });
  42011. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  42012. get: function () {
  42013. var mousewheel = this.inputs.attached["mousewheel"];
  42014. if (mousewheel)
  42015. return mousewheel.wheelDeltaPercentage;
  42016. return 0;
  42017. },
  42018. set: function (value) {
  42019. var mousewheel = this.inputs.attached["mousewheel"];
  42020. if (mousewheel)
  42021. mousewheel.wheelDeltaPercentage = value;
  42022. },
  42023. enumerable: true,
  42024. configurable: true
  42025. });
  42026. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  42027. get: function () {
  42028. return this._bouncingBehavior;
  42029. },
  42030. enumerable: true,
  42031. configurable: true
  42032. });
  42033. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  42034. get: function () {
  42035. return this._bouncingBehavior != null;
  42036. },
  42037. set: function (value) {
  42038. if (value === this.useBouncingBehavior) {
  42039. return;
  42040. }
  42041. if (value) {
  42042. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  42043. this.addBehavior(this._bouncingBehavior);
  42044. }
  42045. else if (this._bouncingBehavior) {
  42046. this.removeBehavior(this._bouncingBehavior);
  42047. this._bouncingBehavior = null;
  42048. }
  42049. },
  42050. enumerable: true,
  42051. configurable: true
  42052. });
  42053. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  42054. get: function () {
  42055. return this._framingBehavior;
  42056. },
  42057. enumerable: true,
  42058. configurable: true
  42059. });
  42060. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  42061. get: function () {
  42062. return this._framingBehavior != null;
  42063. },
  42064. set: function (value) {
  42065. if (value === this.useFramingBehavior) {
  42066. return;
  42067. }
  42068. if (value) {
  42069. this._framingBehavior = new BABYLON.FramingBehavior();
  42070. this.addBehavior(this._framingBehavior);
  42071. }
  42072. else if (this._framingBehavior) {
  42073. this.removeBehavior(this._framingBehavior);
  42074. this._framingBehavior = null;
  42075. }
  42076. },
  42077. enumerable: true,
  42078. configurable: true
  42079. });
  42080. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  42081. get: function () {
  42082. return this._autoRotationBehavior;
  42083. },
  42084. enumerable: true,
  42085. configurable: true
  42086. });
  42087. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  42088. get: function () {
  42089. return this._autoRotationBehavior != null;
  42090. },
  42091. set: function (value) {
  42092. if (value === this.useAutoRotationBehavior) {
  42093. return;
  42094. }
  42095. if (value) {
  42096. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  42097. this.addBehavior(this._autoRotationBehavior);
  42098. }
  42099. else if (this._autoRotationBehavior) {
  42100. this.removeBehavior(this._autoRotationBehavior);
  42101. this._autoRotationBehavior = null;
  42102. }
  42103. },
  42104. enumerable: true,
  42105. configurable: true
  42106. });
  42107. // Cache
  42108. ArcRotateCamera.prototype._initCache = function () {
  42109. _super.prototype._initCache.call(this);
  42110. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42111. this._cache.alpha = undefined;
  42112. this._cache.beta = undefined;
  42113. this._cache.radius = undefined;
  42114. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  42115. };
  42116. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  42117. if (!ignoreParentClass) {
  42118. _super.prototype._updateCache.call(this);
  42119. }
  42120. this._cache._target.copyFrom(this._getTargetPosition());
  42121. this._cache.alpha = this.alpha;
  42122. this._cache.beta = this.beta;
  42123. this._cache.radius = this.radius;
  42124. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  42125. };
  42126. ArcRotateCamera.prototype._getTargetPosition = function () {
  42127. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  42128. var pos = this._targetHost.getAbsolutePosition();
  42129. if (this._targetBoundingCenter) {
  42130. pos.addToRef(this._targetBoundingCenter, this._target);
  42131. }
  42132. else {
  42133. this._target.copyFrom(pos);
  42134. }
  42135. }
  42136. var lockedTargetPosition = this._getLockedTargetPosition();
  42137. if (lockedTargetPosition) {
  42138. return lockedTargetPosition;
  42139. }
  42140. return this._target;
  42141. };
  42142. ArcRotateCamera.prototype.storeState = function () {
  42143. this._storedAlpha = this.alpha;
  42144. this._storedBeta = this.beta;
  42145. this._storedRadius = this.radius;
  42146. this._storedTarget = this._getTargetPosition().clone();
  42147. return _super.prototype.storeState.call(this);
  42148. };
  42149. /**
  42150. * Restored camera state. You must call storeState() first
  42151. */
  42152. ArcRotateCamera.prototype._restoreStateValues = function () {
  42153. if (!_super.prototype._restoreStateValues.call(this)) {
  42154. return false;
  42155. }
  42156. this.alpha = this._storedAlpha;
  42157. this.beta = this._storedBeta;
  42158. this.radius = this._storedRadius;
  42159. this.setTarget(this._storedTarget.clone());
  42160. this.inertialAlphaOffset = 0;
  42161. this.inertialBetaOffset = 0;
  42162. this.inertialRadiusOffset = 0;
  42163. this.inertialPanningX = 0;
  42164. this.inertialPanningY = 0;
  42165. return true;
  42166. };
  42167. // Synchronized
  42168. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  42169. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  42170. return false;
  42171. return this._cache._target.equals(this._getTargetPosition())
  42172. && this._cache.alpha === this.alpha
  42173. && this._cache.beta === this.beta
  42174. && this._cache.radius === this.radius
  42175. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  42176. };
  42177. // Methods
  42178. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  42179. var _this = this;
  42180. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  42181. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  42182. this._useCtrlForPanning = useCtrlForPanning;
  42183. this._panningMouseButton = panningMouseButton;
  42184. this.inputs.attachElement(element, noPreventDefault);
  42185. this._reset = function () {
  42186. _this.inertialAlphaOffset = 0;
  42187. _this.inertialBetaOffset = 0;
  42188. _this.inertialRadiusOffset = 0;
  42189. _this.inertialPanningX = 0;
  42190. _this.inertialPanningY = 0;
  42191. };
  42192. };
  42193. ArcRotateCamera.prototype.detachControl = function (element) {
  42194. this.inputs.detachElement(element);
  42195. if (this._reset) {
  42196. this._reset();
  42197. }
  42198. };
  42199. ArcRotateCamera.prototype._checkInputs = function () {
  42200. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  42201. if (this._collisionTriggered) {
  42202. return;
  42203. }
  42204. this.inputs.checkInputs();
  42205. // Inertia
  42206. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  42207. if (this.getScene().useRightHandedSystem) {
  42208. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42209. }
  42210. else {
  42211. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  42212. }
  42213. this.beta += this.inertialBetaOffset;
  42214. this.radius -= this.inertialRadiusOffset;
  42215. this.inertialAlphaOffset *= this.inertia;
  42216. this.inertialBetaOffset *= this.inertia;
  42217. this.inertialRadiusOffset *= this.inertia;
  42218. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  42219. this.inertialAlphaOffset = 0;
  42220. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  42221. this.inertialBetaOffset = 0;
  42222. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  42223. this.inertialRadiusOffset = 0;
  42224. }
  42225. // Panning inertia
  42226. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  42227. if (!this._localDirection) {
  42228. this._localDirection = BABYLON.Vector3.Zero();
  42229. this._transformedDirection = BABYLON.Vector3.Zero();
  42230. }
  42231. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  42232. this._localDirection.multiplyInPlace(this.panningAxis);
  42233. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  42234. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  42235. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  42236. if (!this.panningAxis.y) {
  42237. this._transformedDirection.y = 0;
  42238. }
  42239. if (!this._targetHost) {
  42240. if (this.panningDistanceLimit) {
  42241. this._transformedDirection.addInPlace(this._target);
  42242. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  42243. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  42244. this._target.copyFrom(this._transformedDirection);
  42245. }
  42246. }
  42247. else {
  42248. this._target.addInPlace(this._transformedDirection);
  42249. }
  42250. }
  42251. this.inertialPanningX *= this.panningInertia;
  42252. this.inertialPanningY *= this.panningInertia;
  42253. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  42254. this.inertialPanningX = 0;
  42255. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  42256. this.inertialPanningY = 0;
  42257. }
  42258. // Limits
  42259. this._checkLimits();
  42260. _super.prototype._checkInputs.call(this);
  42261. };
  42262. ArcRotateCamera.prototype._checkLimits = function () {
  42263. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  42264. if (this.allowUpsideDown && this.beta > Math.PI) {
  42265. this.beta = this.beta - (2 * Math.PI);
  42266. }
  42267. }
  42268. else {
  42269. if (this.beta < this.lowerBetaLimit) {
  42270. this.beta = this.lowerBetaLimit;
  42271. }
  42272. }
  42273. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  42274. if (this.allowUpsideDown && this.beta < -Math.PI) {
  42275. this.beta = this.beta + (2 * Math.PI);
  42276. }
  42277. }
  42278. else {
  42279. if (this.beta > this.upperBetaLimit) {
  42280. this.beta = this.upperBetaLimit;
  42281. }
  42282. }
  42283. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  42284. this.alpha = this.lowerAlphaLimit;
  42285. }
  42286. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  42287. this.alpha = this.upperAlphaLimit;
  42288. }
  42289. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  42290. this.radius = this.lowerRadiusLimit;
  42291. }
  42292. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  42293. this.radius = this.upperRadiusLimit;
  42294. }
  42295. };
  42296. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  42297. var radiusv3 = this.position.subtract(this._getTargetPosition());
  42298. this.radius = radiusv3.length();
  42299. if (this.radius === 0) {
  42300. this.radius = 0.0001; // Just to avoid division by zero
  42301. }
  42302. // Alpha
  42303. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  42304. if (radiusv3.z < 0) {
  42305. this.alpha = 2 * Math.PI - this.alpha;
  42306. }
  42307. // Beta
  42308. this.beta = Math.acos(radiusv3.y / this.radius);
  42309. this._checkLimits();
  42310. };
  42311. ArcRotateCamera.prototype.setPosition = function (position) {
  42312. if (this.position.equals(position)) {
  42313. return;
  42314. }
  42315. this.position.copyFrom(position);
  42316. this.rebuildAnglesAndRadius();
  42317. };
  42318. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  42319. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  42320. if (allowSamePosition === void 0) { allowSamePosition = false; }
  42321. if (target.getBoundingInfo) {
  42322. if (toBoundingCenter) {
  42323. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  42324. }
  42325. else {
  42326. this._targetBoundingCenter = null;
  42327. }
  42328. this._targetHost = target;
  42329. this._target = this._getTargetPosition();
  42330. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  42331. }
  42332. else {
  42333. var newTarget = target;
  42334. var currentTarget = this._getTargetPosition();
  42335. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  42336. return;
  42337. }
  42338. this._targetHost = null;
  42339. this._target = newTarget;
  42340. this._targetBoundingCenter = null;
  42341. this.onMeshTargetChangedObservable.notifyObservers(null);
  42342. }
  42343. this.rebuildAnglesAndRadius();
  42344. };
  42345. ArcRotateCamera.prototype._getViewMatrix = function () {
  42346. // Compute
  42347. var cosa = Math.cos(this.alpha);
  42348. var sina = Math.sin(this.alpha);
  42349. var cosb = Math.cos(this.beta);
  42350. var sinb = Math.sin(this.beta);
  42351. if (sinb === 0) {
  42352. sinb = 0.0001;
  42353. }
  42354. var target = this._getTargetPosition();
  42355. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  42356. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  42357. if (!this._collider) {
  42358. this._collider = new BABYLON.Collider();
  42359. }
  42360. this._collider._radius = this.collisionRadius;
  42361. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  42362. this._collisionTriggered = true;
  42363. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42364. }
  42365. else {
  42366. this.position.copyFrom(this._newPosition);
  42367. var up = this.upVector;
  42368. if (this.allowUpsideDown && sinb < 0) {
  42369. up = up.clone();
  42370. up = up.negate();
  42371. }
  42372. if (this.getScene().useRightHandedSystem) {
  42373. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  42374. }
  42375. else {
  42376. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  42377. }
  42378. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  42379. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  42380. }
  42381. this._currentTarget = target;
  42382. return this._viewMatrix;
  42383. };
  42384. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  42385. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42386. meshes = meshes || this.getScene().meshes;
  42387. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  42388. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  42389. this.radius = distance * this.zoomOnFactor;
  42390. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  42391. };
  42392. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  42393. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42394. var meshesOrMinMaxVector;
  42395. var distance;
  42396. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  42397. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  42398. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  42399. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  42400. }
  42401. else {
  42402. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  42403. meshesOrMinMaxVector = minMaxVectorAndDistance;
  42404. distance = minMaxVectorAndDistance.distance;
  42405. }
  42406. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  42407. if (!doNotUpdateMaxZ) {
  42408. this.maxZ = distance * 2;
  42409. }
  42410. };
  42411. /**
  42412. * @override
  42413. * Override Camera.createRigCamera
  42414. */
  42415. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42416. var alphaShift = 0;
  42417. switch (this.cameraRigMode) {
  42418. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42419. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42420. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42421. case BABYLON.Camera.RIG_MODE_VR:
  42422. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  42423. break;
  42424. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42425. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  42426. break;
  42427. }
  42428. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  42429. rigCam._cameraRigParams = {};
  42430. return rigCam;
  42431. };
  42432. /**
  42433. * @override
  42434. * Override Camera._updateRigCameras
  42435. */
  42436. ArcRotateCamera.prototype._updateRigCameras = function () {
  42437. var camLeft = this._rigCameras[0];
  42438. var camRight = this._rigCameras[1];
  42439. camLeft.beta = camRight.beta = this.beta;
  42440. camLeft.radius = camRight.radius = this.radius;
  42441. switch (this.cameraRigMode) {
  42442. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42443. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42444. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42445. case BABYLON.Camera.RIG_MODE_VR:
  42446. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42447. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42448. break;
  42449. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42450. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42451. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42452. break;
  42453. }
  42454. _super.prototype._updateRigCameras.call(this);
  42455. };
  42456. ArcRotateCamera.prototype.dispose = function () {
  42457. this.inputs.clear();
  42458. _super.prototype.dispose.call(this);
  42459. };
  42460. ArcRotateCamera.prototype.getClassName = function () {
  42461. return "ArcRotateCamera";
  42462. };
  42463. __decorate([
  42464. BABYLON.serialize()
  42465. ], ArcRotateCamera.prototype, "alpha", void 0);
  42466. __decorate([
  42467. BABYLON.serialize()
  42468. ], ArcRotateCamera.prototype, "beta", void 0);
  42469. __decorate([
  42470. BABYLON.serialize()
  42471. ], ArcRotateCamera.prototype, "radius", void 0);
  42472. __decorate([
  42473. BABYLON.serializeAsVector3("target")
  42474. ], ArcRotateCamera.prototype, "_target", void 0);
  42475. __decorate([
  42476. BABYLON.serialize()
  42477. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  42478. __decorate([
  42479. BABYLON.serialize()
  42480. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  42481. __decorate([
  42482. BABYLON.serialize()
  42483. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  42484. __decorate([
  42485. BABYLON.serialize()
  42486. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  42487. __decorate([
  42488. BABYLON.serialize()
  42489. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  42490. __decorate([
  42491. BABYLON.serialize()
  42492. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  42493. __decorate([
  42494. BABYLON.serialize()
  42495. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  42496. __decorate([
  42497. BABYLON.serialize()
  42498. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  42499. __decorate([
  42500. BABYLON.serialize()
  42501. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  42502. __decorate([
  42503. BABYLON.serialize()
  42504. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  42505. __decorate([
  42506. BABYLON.serialize()
  42507. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  42508. __decorate([
  42509. BABYLON.serialize()
  42510. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  42511. __decorate([
  42512. BABYLON.serialize()
  42513. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  42514. __decorate([
  42515. BABYLON.serializeAsVector3()
  42516. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  42517. __decorate([
  42518. BABYLON.serialize()
  42519. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  42520. __decorate([
  42521. BABYLON.serialize()
  42522. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  42523. __decorate([
  42524. BABYLON.serialize()
  42525. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  42526. return ArcRotateCamera;
  42527. }(BABYLON.TargetCamera));
  42528. BABYLON.ArcRotateCamera = ArcRotateCamera;
  42529. })(BABYLON || (BABYLON = {}));
  42530. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  42531. var BABYLON;
  42532. (function (BABYLON) {
  42533. var HemisphericLight = /** @class */ (function (_super) {
  42534. __extends(HemisphericLight, _super);
  42535. /**
  42536. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  42537. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  42538. * The HemisphericLight can't cast shadows.
  42539. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42540. */
  42541. function HemisphericLight(name, direction, scene) {
  42542. var _this = _super.call(this, name, scene) || this;
  42543. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  42544. _this.direction = direction || BABYLON.Vector3.Up();
  42545. return _this;
  42546. }
  42547. HemisphericLight.prototype._buildUniformLayout = function () {
  42548. this._uniformBuffer.addUniform("vLightData", 4);
  42549. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42550. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42551. this._uniformBuffer.addUniform("vLightGround", 3);
  42552. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42553. this._uniformBuffer.addUniform("depthValues", 2);
  42554. this._uniformBuffer.create();
  42555. };
  42556. /**
  42557. * Returns the string "HemisphericLight".
  42558. */
  42559. HemisphericLight.prototype.getClassName = function () {
  42560. return "HemisphericLight";
  42561. };
  42562. /**
  42563. * Sets the HemisphericLight direction towards the passed target (Vector3).
  42564. * Returns the updated direction.
  42565. */
  42566. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  42567. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  42568. return this.direction;
  42569. };
  42570. HemisphericLight.prototype.getShadowGenerator = function () {
  42571. return null;
  42572. };
  42573. /**
  42574. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  42575. * Returns the HemisphericLight.
  42576. */
  42577. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  42578. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42579. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  42580. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  42581. return this;
  42582. };
  42583. HemisphericLight.prototype._getWorldMatrix = function () {
  42584. if (!this._worldMatrix) {
  42585. this._worldMatrix = BABYLON.Matrix.Identity();
  42586. }
  42587. return this._worldMatrix;
  42588. };
  42589. /**
  42590. * Returns the integer 3.
  42591. */
  42592. HemisphericLight.prototype.getTypeID = function () {
  42593. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  42594. };
  42595. __decorate([
  42596. BABYLON.serializeAsColor3()
  42597. ], HemisphericLight.prototype, "groundColor", void 0);
  42598. __decorate([
  42599. BABYLON.serializeAsVector3()
  42600. ], HemisphericLight.prototype, "direction", void 0);
  42601. return HemisphericLight;
  42602. }(BABYLON.Light));
  42603. BABYLON.HemisphericLight = HemisphericLight;
  42604. })(BABYLON || (BABYLON = {}));
  42605. //# sourceMappingURL=babylon.hemisphericLight.js.map
  42606. var BABYLON;
  42607. (function (BABYLON) {
  42608. var ShadowLight = /** @class */ (function (_super) {
  42609. __extends(ShadowLight, _super);
  42610. function ShadowLight() {
  42611. var _this = _super !== null && _super.apply(this, arguments) || this;
  42612. _this._needProjectionMatrixCompute = true;
  42613. return _this;
  42614. }
  42615. Object.defineProperty(ShadowLight.prototype, "direction", {
  42616. get: function () {
  42617. return this._direction;
  42618. },
  42619. set: function (value) {
  42620. this._direction = value;
  42621. },
  42622. enumerable: true,
  42623. configurable: true
  42624. });
  42625. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  42626. get: function () {
  42627. return this._shadowMinZ;
  42628. },
  42629. set: function (value) {
  42630. this._shadowMinZ = value;
  42631. this.forceProjectionMatrixCompute();
  42632. },
  42633. enumerable: true,
  42634. configurable: true
  42635. });
  42636. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  42637. get: function () {
  42638. return this._shadowMaxZ;
  42639. },
  42640. set: function (value) {
  42641. this._shadowMaxZ = value;
  42642. this.forceProjectionMatrixCompute();
  42643. },
  42644. enumerable: true,
  42645. configurable: true
  42646. });
  42647. /**
  42648. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  42649. */
  42650. ShadowLight.prototype.computeTransformedInformation = function () {
  42651. if (this.parent && this.parent.getWorldMatrix) {
  42652. if (!this.transformedPosition) {
  42653. this.transformedPosition = BABYLON.Vector3.Zero();
  42654. }
  42655. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  42656. // In case the direction is present.
  42657. if (this.direction) {
  42658. if (!this.transformedDirection) {
  42659. this.transformedDirection = BABYLON.Vector3.Zero();
  42660. }
  42661. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  42662. }
  42663. return true;
  42664. }
  42665. return false;
  42666. };
  42667. /**
  42668. * Return the depth scale used for the shadow map.
  42669. */
  42670. ShadowLight.prototype.getDepthScale = function () {
  42671. return 50.0;
  42672. };
  42673. /**
  42674. * Returns the light direction (Vector3) for any passed face index.
  42675. */
  42676. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  42677. return this.transformedDirection ? this.transformedDirection : this.direction;
  42678. };
  42679. /**
  42680. * Returns the ShadowLight absolute position in the World.
  42681. */
  42682. ShadowLight.prototype.getAbsolutePosition = function () {
  42683. return this.transformedPosition ? this.transformedPosition : this.position;
  42684. };
  42685. /**
  42686. * Sets the ShadowLight direction toward the passed target (Vector3).
  42687. * Returns the updated ShadowLight direction (Vector3).
  42688. */
  42689. ShadowLight.prototype.setDirectionToTarget = function (target) {
  42690. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  42691. return this.direction;
  42692. };
  42693. /**
  42694. * Returns the light rotation (Vector3).
  42695. */
  42696. ShadowLight.prototype.getRotation = function () {
  42697. this.direction.normalize();
  42698. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  42699. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  42700. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  42701. };
  42702. /**
  42703. * Boolean : false by default.
  42704. */
  42705. ShadowLight.prototype.needCube = function () {
  42706. return false;
  42707. };
  42708. /**
  42709. * Specifies wether or not the projection matrix should be recomputed this frame.
  42710. */
  42711. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  42712. return this._needProjectionMatrixCompute;
  42713. };
  42714. /**
  42715. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  42716. */
  42717. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  42718. this._needProjectionMatrixCompute = true;
  42719. };
  42720. /**
  42721. * Get the world matrix of the sahdow lights.
  42722. */
  42723. ShadowLight.prototype._getWorldMatrix = function () {
  42724. if (!this._worldMatrix) {
  42725. this._worldMatrix = BABYLON.Matrix.Identity();
  42726. }
  42727. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  42728. return this._worldMatrix;
  42729. };
  42730. /**
  42731. * Gets the minZ used for shadow according to both the scene and the light.
  42732. * @param activeCamera
  42733. */
  42734. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  42735. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  42736. };
  42737. /**
  42738. * Gets the maxZ used for shadow according to both the scene and the light.
  42739. * @param activeCamera
  42740. */
  42741. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  42742. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  42743. };
  42744. /**
  42745. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  42746. * Returns the light.
  42747. */
  42748. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42749. if (this.customProjectionMatrixBuilder) {
  42750. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  42751. }
  42752. else {
  42753. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42754. }
  42755. return this;
  42756. };
  42757. __decorate([
  42758. BABYLON.serializeAsVector3()
  42759. ], ShadowLight.prototype, "position", void 0);
  42760. __decorate([
  42761. BABYLON.serializeAsVector3()
  42762. ], ShadowLight.prototype, "direction", null);
  42763. __decorate([
  42764. BABYLON.serialize()
  42765. ], ShadowLight.prototype, "shadowMinZ", null);
  42766. __decorate([
  42767. BABYLON.serialize()
  42768. ], ShadowLight.prototype, "shadowMaxZ", null);
  42769. return ShadowLight;
  42770. }(BABYLON.Light));
  42771. BABYLON.ShadowLight = ShadowLight;
  42772. })(BABYLON || (BABYLON = {}));
  42773. //# sourceMappingURL=babylon.shadowLight.js.map
  42774. var BABYLON;
  42775. (function (BABYLON) {
  42776. var PointLight = /** @class */ (function (_super) {
  42777. __extends(PointLight, _super);
  42778. /**
  42779. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  42780. * A PointLight emits the light in every direction.
  42781. * It can cast shadows.
  42782. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  42783. * ```javascript
  42784. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  42785. * ```
  42786. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42787. */
  42788. function PointLight(name, position, scene) {
  42789. var _this = _super.call(this, name, scene) || this;
  42790. _this._shadowAngle = Math.PI / 2;
  42791. _this.position = position;
  42792. return _this;
  42793. }
  42794. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  42795. /**
  42796. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42797. * This specifies what angle the shadow will use to be created.
  42798. *
  42799. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42800. */
  42801. get: function () {
  42802. return this._shadowAngle;
  42803. },
  42804. /**
  42805. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42806. * This specifies what angle the shadow will use to be created.
  42807. *
  42808. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42809. */
  42810. set: function (value) {
  42811. this._shadowAngle = value;
  42812. this.forceProjectionMatrixCompute();
  42813. },
  42814. enumerable: true,
  42815. configurable: true
  42816. });
  42817. Object.defineProperty(PointLight.prototype, "direction", {
  42818. get: function () {
  42819. return this._direction;
  42820. },
  42821. /**
  42822. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42823. */
  42824. set: function (value) {
  42825. var previousNeedCube = this.needCube();
  42826. this._direction = value;
  42827. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  42828. this._shadowGenerator.recreateShadowMap();
  42829. }
  42830. },
  42831. enumerable: true,
  42832. configurable: true
  42833. });
  42834. /**
  42835. * Returns the string "PointLight"
  42836. */
  42837. PointLight.prototype.getClassName = function () {
  42838. return "PointLight";
  42839. };
  42840. /**
  42841. * Returns the integer 0.
  42842. */
  42843. PointLight.prototype.getTypeID = function () {
  42844. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  42845. };
  42846. /**
  42847. * Specifies wether or not the shadowmap should be a cube texture.
  42848. */
  42849. PointLight.prototype.needCube = function () {
  42850. return !this.direction;
  42851. };
  42852. /**
  42853. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  42854. */
  42855. PointLight.prototype.getShadowDirection = function (faceIndex) {
  42856. if (this.direction) {
  42857. return _super.prototype.getShadowDirection.call(this, faceIndex);
  42858. }
  42859. else {
  42860. switch (faceIndex) {
  42861. case 0:
  42862. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  42863. case 1:
  42864. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  42865. case 2:
  42866. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  42867. case 3:
  42868. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  42869. case 4:
  42870. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  42871. case 5:
  42872. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  42873. }
  42874. }
  42875. return BABYLON.Vector3.Zero();
  42876. };
  42877. /**
  42878. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  42879. * - fov = PI / 2
  42880. * - aspect ratio : 1.0
  42881. * - z-near and far equal to the active camera minZ and maxZ.
  42882. * Returns the PointLight.
  42883. */
  42884. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42885. var activeCamera = this.getScene().activeCamera;
  42886. if (!activeCamera) {
  42887. return;
  42888. }
  42889. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  42890. };
  42891. PointLight.prototype._buildUniformLayout = function () {
  42892. this._uniformBuffer.addUniform("vLightData", 4);
  42893. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42894. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42895. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42896. this._uniformBuffer.addUniform("depthValues", 2);
  42897. this._uniformBuffer.create();
  42898. };
  42899. /**
  42900. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  42901. * Returns the PointLight.
  42902. */
  42903. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  42904. if (this.computeTransformedInformation()) {
  42905. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  42906. return this;
  42907. }
  42908. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  42909. return this;
  42910. };
  42911. __decorate([
  42912. BABYLON.serialize()
  42913. ], PointLight.prototype, "shadowAngle", null);
  42914. return PointLight;
  42915. }(BABYLON.ShadowLight));
  42916. BABYLON.PointLight = PointLight;
  42917. })(BABYLON || (BABYLON = {}));
  42918. //# sourceMappingURL=babylon.pointLight.js.map
  42919. var BABYLON;
  42920. (function (BABYLON) {
  42921. var DirectionalLight = /** @class */ (function (_super) {
  42922. __extends(DirectionalLight, _super);
  42923. /**
  42924. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  42925. * The directional light is emitted from everywhere in the given direction.
  42926. * It can cast shawdows.
  42927. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42928. */
  42929. function DirectionalLight(name, direction, scene) {
  42930. var _this = _super.call(this, name, scene) || this;
  42931. _this._shadowFrustumSize = 0;
  42932. _this._shadowOrthoScale = 0.5;
  42933. _this.autoUpdateExtends = true;
  42934. // Cache
  42935. _this._orthoLeft = Number.MAX_VALUE;
  42936. _this._orthoRight = Number.MIN_VALUE;
  42937. _this._orthoTop = Number.MIN_VALUE;
  42938. _this._orthoBottom = Number.MAX_VALUE;
  42939. _this.position = direction.scale(-1.0);
  42940. _this.direction = direction;
  42941. return _this;
  42942. }
  42943. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  42944. /**
  42945. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  42946. */
  42947. get: function () {
  42948. return this._shadowFrustumSize;
  42949. },
  42950. /**
  42951. * Specifies a fix frustum size for the shadow generation.
  42952. */
  42953. set: function (value) {
  42954. this._shadowFrustumSize = value;
  42955. this.forceProjectionMatrixCompute();
  42956. },
  42957. enumerable: true,
  42958. configurable: true
  42959. });
  42960. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  42961. get: function () {
  42962. return this._shadowOrthoScale;
  42963. },
  42964. set: function (value) {
  42965. this._shadowOrthoScale = value;
  42966. this.forceProjectionMatrixCompute();
  42967. },
  42968. enumerable: true,
  42969. configurable: true
  42970. });
  42971. /**
  42972. * Returns the string "DirectionalLight".
  42973. */
  42974. DirectionalLight.prototype.getClassName = function () {
  42975. return "DirectionalLight";
  42976. };
  42977. /**
  42978. * Returns the integer 1.
  42979. */
  42980. DirectionalLight.prototype.getTypeID = function () {
  42981. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  42982. };
  42983. /**
  42984. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  42985. * Returns the DirectionalLight Shadow projection matrix.
  42986. */
  42987. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42988. if (this.shadowFrustumSize > 0) {
  42989. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  42990. }
  42991. else {
  42992. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42993. }
  42994. };
  42995. /**
  42996. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  42997. * Returns the DirectionalLight Shadow projection matrix.
  42998. */
  42999. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  43000. var activeCamera = this.getScene().activeCamera;
  43001. if (!activeCamera) {
  43002. return;
  43003. }
  43004. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  43005. };
  43006. /**
  43007. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  43008. * Returns the DirectionalLight Shadow projection matrix.
  43009. */
  43010. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43011. var activeCamera = this.getScene().activeCamera;
  43012. if (!activeCamera) {
  43013. return;
  43014. }
  43015. // Check extends
  43016. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  43017. var tempVector3 = BABYLON.Vector3.Zero();
  43018. this._orthoLeft = Number.MAX_VALUE;
  43019. this._orthoRight = Number.MIN_VALUE;
  43020. this._orthoTop = Number.MIN_VALUE;
  43021. this._orthoBottom = Number.MAX_VALUE;
  43022. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  43023. var mesh = renderList[meshIndex];
  43024. if (!mesh) {
  43025. continue;
  43026. }
  43027. var boundingInfo = mesh.getBoundingInfo();
  43028. var boundingBox = boundingInfo.boundingBox;
  43029. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  43030. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  43031. if (tempVector3.x < this._orthoLeft)
  43032. this._orthoLeft = tempVector3.x;
  43033. if (tempVector3.y < this._orthoBottom)
  43034. this._orthoBottom = tempVector3.y;
  43035. if (tempVector3.x > this._orthoRight)
  43036. this._orthoRight = tempVector3.x;
  43037. if (tempVector3.y > this._orthoTop)
  43038. this._orthoTop = tempVector3.y;
  43039. }
  43040. }
  43041. }
  43042. var xOffset = this._orthoRight - this._orthoLeft;
  43043. var yOffset = this._orthoTop - this._orthoBottom;
  43044. 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);
  43045. };
  43046. DirectionalLight.prototype._buildUniformLayout = function () {
  43047. this._uniformBuffer.addUniform("vLightData", 4);
  43048. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43049. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43050. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43051. this._uniformBuffer.addUniform("depthValues", 2);
  43052. this._uniformBuffer.create();
  43053. };
  43054. /**
  43055. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  43056. * Returns the DirectionalLight.
  43057. */
  43058. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  43059. if (this.computeTransformedInformation()) {
  43060. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  43061. return this;
  43062. }
  43063. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  43064. return this;
  43065. };
  43066. /**
  43067. * Gets the minZ used for shadow according to both the scene and the light.
  43068. *
  43069. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43070. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43071. * @param activeCamera
  43072. */
  43073. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  43074. return 1;
  43075. };
  43076. /**
  43077. * Gets the maxZ used for shadow according to both the scene and the light.
  43078. *
  43079. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  43080. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  43081. * @param activeCamera
  43082. */
  43083. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  43084. return 1;
  43085. };
  43086. __decorate([
  43087. BABYLON.serialize()
  43088. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  43089. __decorate([
  43090. BABYLON.serialize()
  43091. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  43092. __decorate([
  43093. BABYLON.serialize()
  43094. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  43095. return DirectionalLight;
  43096. }(BABYLON.ShadowLight));
  43097. BABYLON.DirectionalLight = DirectionalLight;
  43098. })(BABYLON || (BABYLON = {}));
  43099. //# sourceMappingURL=babylon.directionalLight.js.map
  43100. var BABYLON;
  43101. (function (BABYLON) {
  43102. var SpotLight = /** @class */ (function (_super) {
  43103. __extends(SpotLight, _super);
  43104. /**
  43105. * Creates a SpotLight object in the scene with the passed parameters :
  43106. * - `position` (Vector3) is the initial SpotLight position,
  43107. * - `direction` (Vector3) is the initial SpotLight direction,
  43108. * - `angle` (float, in radians) is the spot light cone angle,
  43109. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  43110. * A spot light is a simply light oriented cone.
  43111. * It can cast shadows.
  43112. * Documentation : http://doc.babylonjs.com/tutorials/lights
  43113. */
  43114. function SpotLight(name, position, direction, angle, exponent, scene) {
  43115. var _this = _super.call(this, name, scene) || this;
  43116. _this.position = position;
  43117. _this.direction = direction;
  43118. _this.angle = angle;
  43119. _this.exponent = exponent;
  43120. return _this;
  43121. }
  43122. Object.defineProperty(SpotLight.prototype, "angle", {
  43123. get: function () {
  43124. return this._angle;
  43125. },
  43126. set: function (value) {
  43127. this._angle = value;
  43128. this.forceProjectionMatrixCompute();
  43129. },
  43130. enumerable: true,
  43131. configurable: true
  43132. });
  43133. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  43134. get: function () {
  43135. return this._shadowAngleScale;
  43136. },
  43137. /**
  43138. * Allows scaling the angle of the light for shadow generation only.
  43139. */
  43140. set: function (value) {
  43141. this._shadowAngleScale = value;
  43142. this.forceProjectionMatrixCompute();
  43143. },
  43144. enumerable: true,
  43145. configurable: true
  43146. });
  43147. /**
  43148. * Returns the string "SpotLight".
  43149. */
  43150. SpotLight.prototype.getClassName = function () {
  43151. return "SpotLight";
  43152. };
  43153. /**
  43154. * Returns the integer 2.
  43155. */
  43156. SpotLight.prototype.getTypeID = function () {
  43157. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  43158. };
  43159. /**
  43160. * 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.
  43161. * Returns the SpotLight.
  43162. */
  43163. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  43164. var activeCamera = this.getScene().activeCamera;
  43165. if (!activeCamera) {
  43166. return;
  43167. }
  43168. this._shadowAngleScale = this._shadowAngleScale || 1;
  43169. var angle = this._shadowAngleScale * this._angle;
  43170. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  43171. };
  43172. SpotLight.prototype._buildUniformLayout = function () {
  43173. this._uniformBuffer.addUniform("vLightData", 4);
  43174. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  43175. this._uniformBuffer.addUniform("vLightSpecular", 3);
  43176. this._uniformBuffer.addUniform("vLightDirection", 3);
  43177. this._uniformBuffer.addUniform("shadowsInfo", 3);
  43178. this._uniformBuffer.addUniform("depthValues", 2);
  43179. this._uniformBuffer.create();
  43180. };
  43181. /**
  43182. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  43183. * Return the SpotLight.
  43184. */
  43185. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  43186. var normalizeDirection;
  43187. if (this.computeTransformedInformation()) {
  43188. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  43189. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  43190. }
  43191. else {
  43192. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  43193. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  43194. }
  43195. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  43196. return this;
  43197. };
  43198. __decorate([
  43199. BABYLON.serialize()
  43200. ], SpotLight.prototype, "angle", null);
  43201. __decorate([
  43202. BABYLON.serialize()
  43203. /**
  43204. * Allows scaling the angle of the light for shadow generation only.
  43205. */
  43206. ], SpotLight.prototype, "shadowAngleScale", null);
  43207. __decorate([
  43208. BABYLON.serialize()
  43209. ], SpotLight.prototype, "exponent", void 0);
  43210. return SpotLight;
  43211. }(BABYLON.ShadowLight));
  43212. BABYLON.SpotLight = SpotLight;
  43213. })(BABYLON || (BABYLON = {}));
  43214. //# sourceMappingURL=babylon.spotLight.js.map
  43215. var BABYLON;
  43216. (function (BABYLON) {
  43217. var AnimationRange = /** @class */ (function () {
  43218. function AnimationRange(name, from, to) {
  43219. this.name = name;
  43220. this.from = from;
  43221. this.to = to;
  43222. }
  43223. AnimationRange.prototype.clone = function () {
  43224. return new AnimationRange(this.name, this.from, this.to);
  43225. };
  43226. return AnimationRange;
  43227. }());
  43228. BABYLON.AnimationRange = AnimationRange;
  43229. /**
  43230. * Composed of a frame, and an action function
  43231. */
  43232. var AnimationEvent = /** @class */ (function () {
  43233. function AnimationEvent(frame, action, onlyOnce) {
  43234. this.frame = frame;
  43235. this.action = action;
  43236. this.onlyOnce = onlyOnce;
  43237. this.isDone = false;
  43238. }
  43239. return AnimationEvent;
  43240. }());
  43241. BABYLON.AnimationEvent = AnimationEvent;
  43242. var PathCursor = /** @class */ (function () {
  43243. function PathCursor(path) {
  43244. this.path = path;
  43245. this._onchange = new Array();
  43246. this.value = 0;
  43247. this.animations = new Array();
  43248. }
  43249. PathCursor.prototype.getPoint = function () {
  43250. var point = this.path.getPointAtLengthPosition(this.value);
  43251. return new BABYLON.Vector3(point.x, 0, point.y);
  43252. };
  43253. PathCursor.prototype.moveAhead = function (step) {
  43254. if (step === void 0) { step = 0.002; }
  43255. this.move(step);
  43256. return this;
  43257. };
  43258. PathCursor.prototype.moveBack = function (step) {
  43259. if (step === void 0) { step = 0.002; }
  43260. this.move(-step);
  43261. return this;
  43262. };
  43263. PathCursor.prototype.move = function (step) {
  43264. if (Math.abs(step) > 1) {
  43265. throw "step size should be less than 1.";
  43266. }
  43267. this.value += step;
  43268. this.ensureLimits();
  43269. this.raiseOnChange();
  43270. return this;
  43271. };
  43272. PathCursor.prototype.ensureLimits = function () {
  43273. while (this.value > 1) {
  43274. this.value -= 1;
  43275. }
  43276. while (this.value < 0) {
  43277. this.value += 1;
  43278. }
  43279. return this;
  43280. };
  43281. // used by animation engine
  43282. PathCursor.prototype.raiseOnChange = function () {
  43283. var _this = this;
  43284. this._onchange.forEach(function (f) { return f(_this); });
  43285. return this;
  43286. };
  43287. PathCursor.prototype.onchange = function (f) {
  43288. this._onchange.push(f);
  43289. return this;
  43290. };
  43291. return PathCursor;
  43292. }());
  43293. BABYLON.PathCursor = PathCursor;
  43294. var AnimationKeyInterpolation;
  43295. (function (AnimationKeyInterpolation) {
  43296. /**
  43297. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  43298. */
  43299. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  43300. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  43301. var Animation = /** @class */ (function () {
  43302. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  43303. this.name = name;
  43304. this.targetProperty = targetProperty;
  43305. this.framePerSecond = framePerSecond;
  43306. this.dataType = dataType;
  43307. this.loopMode = loopMode;
  43308. this.enableBlending = enableBlending;
  43309. this._runtimeAnimations = new Array();
  43310. // The set of event that will be linked to this animation
  43311. this._events = new Array();
  43312. this.blendingSpeed = 0.01;
  43313. this._ranges = {};
  43314. this.targetPropertyPath = targetProperty.split(".");
  43315. this.dataType = dataType;
  43316. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  43317. }
  43318. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  43319. var dataType = undefined;
  43320. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  43321. dataType = Animation.ANIMATIONTYPE_FLOAT;
  43322. }
  43323. else if (from instanceof BABYLON.Quaternion) {
  43324. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  43325. }
  43326. else if (from instanceof BABYLON.Vector3) {
  43327. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  43328. }
  43329. else if (from instanceof BABYLON.Vector2) {
  43330. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  43331. }
  43332. else if (from instanceof BABYLON.Color3) {
  43333. dataType = Animation.ANIMATIONTYPE_COLOR3;
  43334. }
  43335. else if (from instanceof BABYLON.Size) {
  43336. dataType = Animation.ANIMATIONTYPE_SIZE;
  43337. }
  43338. if (dataType == undefined) {
  43339. return null;
  43340. }
  43341. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  43342. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  43343. animation.setKeys(keys);
  43344. if (easingFunction !== undefined) {
  43345. animation.setEasingFunction(easingFunction);
  43346. }
  43347. return animation;
  43348. };
  43349. /**
  43350. * Sets up an animation.
  43351. * @param property the property to animate
  43352. * @param animationType the animation type to apply
  43353. * @param easingFunction the easing function used in the animation
  43354. * @returns The created animation
  43355. */
  43356. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  43357. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  43358. animation.setEasingFunction(easingFunction);
  43359. return animation;
  43360. };
  43361. /**
  43362. * Create and start an animation on a node
  43363. * @param {string} name defines the name of the global animation that will be run on all nodes
  43364. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43365. * @param {string} targetProperty defines property to animate
  43366. * @param {number} framePerSecond defines the number of frame per second yo use
  43367. * @param {number} totalFrame defines the number of frames in total
  43368. * @param {any} from defines the initial value
  43369. * @param {any} to defines the final value
  43370. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43371. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43372. * @param onAnimationEnd defines the callback to call when animation end
  43373. * @returns the animatable created for this animation
  43374. */
  43375. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43376. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43377. if (!animation) {
  43378. return null;
  43379. }
  43380. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43381. };
  43382. /**
  43383. * Create and start an animation on a node and its descendants
  43384. * @param {string} name defines the name of the global animation that will be run on all nodes
  43385. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43386. * @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.
  43387. * @param {string} targetProperty defines property to animate
  43388. * @param {number} framePerSecond defines the number of frame per second yo use
  43389. * @param {number} totalFrame defines the number of frames in total
  43390. * @param {any} from defines the initial value
  43391. * @param {any} to defines the final value
  43392. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43393. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43394. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  43395. * @returns the list of animatables created for all nodes
  43396. * @example https://www.babylonjs-playground.com/#MH0VLI
  43397. */
  43398. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43399. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43400. if (!animation) {
  43401. return null;
  43402. }
  43403. var scene = node.getScene();
  43404. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43405. };
  43406. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43407. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43408. if (!animation) {
  43409. return null;
  43410. }
  43411. node.animations.push(animation);
  43412. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43413. };
  43414. /**
  43415. * Transition property of the Camera to the target Value.
  43416. * @param property The property to transition
  43417. * @param targetValue The target Value of the property
  43418. * @param host The object where the property to animate belongs
  43419. * @param scene Scene used to run the animation
  43420. * @param frameRate Framerate (in frame/s) to use
  43421. * @param transition The transition type we want to use
  43422. * @param duration The duration of the animation, in milliseconds
  43423. * @param onAnimationEnd Call back trigger at the end of the animation.
  43424. */
  43425. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  43426. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  43427. if (duration <= 0) {
  43428. host[property] = targetValue;
  43429. if (onAnimationEnd) {
  43430. onAnimationEnd();
  43431. }
  43432. return null;
  43433. }
  43434. var endFrame = frameRate * (duration / 1000);
  43435. transition.setKeys([{
  43436. frame: 0,
  43437. value: host[property].clone ? host[property].clone() : host[property]
  43438. },
  43439. {
  43440. frame: endFrame,
  43441. value: targetValue
  43442. }]);
  43443. if (!host.animations) {
  43444. host.animations = [];
  43445. }
  43446. host.animations.push(transition);
  43447. var animation = scene.beginAnimation(host, 0, endFrame, false);
  43448. animation.onAnimationEnd = onAnimationEnd;
  43449. return animation;
  43450. };
  43451. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  43452. /**
  43453. * Return the array of runtime animations currently using this animation
  43454. */
  43455. get: function () {
  43456. return this._runtimeAnimations;
  43457. },
  43458. enumerable: true,
  43459. configurable: true
  43460. });
  43461. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  43462. get: function () {
  43463. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  43464. var runtimeAnimation = _a[_i];
  43465. if (!runtimeAnimation.isStopped) {
  43466. return true;
  43467. }
  43468. }
  43469. return false;
  43470. },
  43471. enumerable: true,
  43472. configurable: true
  43473. });
  43474. // Methods
  43475. /**
  43476. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  43477. */
  43478. Animation.prototype.toString = function (fullDetails) {
  43479. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  43480. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  43481. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  43482. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  43483. if (fullDetails) {
  43484. ret += ", Ranges: {";
  43485. var first = true;
  43486. for (var name in this._ranges) {
  43487. if (first) {
  43488. ret += ", ";
  43489. first = false;
  43490. }
  43491. ret += name;
  43492. }
  43493. ret += "}";
  43494. }
  43495. return ret;
  43496. };
  43497. /**
  43498. * Add an event to this animation.
  43499. */
  43500. Animation.prototype.addEvent = function (event) {
  43501. this._events.push(event);
  43502. };
  43503. /**
  43504. * Remove all events found at the given frame
  43505. * @param frame
  43506. */
  43507. Animation.prototype.removeEvents = function (frame) {
  43508. for (var index = 0; index < this._events.length; index++) {
  43509. if (this._events[index].frame === frame) {
  43510. this._events.splice(index, 1);
  43511. index--;
  43512. }
  43513. }
  43514. };
  43515. Animation.prototype.getEvents = function () {
  43516. return this._events;
  43517. };
  43518. Animation.prototype.createRange = function (name, from, to) {
  43519. // check name not already in use; could happen for bones after serialized
  43520. if (!this._ranges[name]) {
  43521. this._ranges[name] = new AnimationRange(name, from, to);
  43522. }
  43523. };
  43524. Animation.prototype.deleteRange = function (name, deleteFrames) {
  43525. if (deleteFrames === void 0) { deleteFrames = true; }
  43526. var range = this._ranges[name];
  43527. if (!range) {
  43528. return;
  43529. }
  43530. if (deleteFrames) {
  43531. var from = range.from;
  43532. var to = range.to;
  43533. // this loop MUST go high to low for multiple splices to work
  43534. for (var key = this._keys.length - 1; key >= 0; key--) {
  43535. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  43536. this._keys.splice(key, 1);
  43537. }
  43538. }
  43539. }
  43540. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  43541. };
  43542. Animation.prototype.getRange = function (name) {
  43543. return this._ranges[name];
  43544. };
  43545. Animation.prototype.getKeys = function () {
  43546. return this._keys;
  43547. };
  43548. Animation.prototype.getHighestFrame = function () {
  43549. var ret = 0;
  43550. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  43551. if (ret < this._keys[key].frame) {
  43552. ret = this._keys[key].frame;
  43553. }
  43554. }
  43555. return ret;
  43556. };
  43557. Animation.prototype.getEasingFunction = function () {
  43558. return this._easingFunction;
  43559. };
  43560. Animation.prototype.setEasingFunction = function (easingFunction) {
  43561. this._easingFunction = easingFunction;
  43562. };
  43563. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  43564. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  43565. };
  43566. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43567. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43568. };
  43569. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  43570. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  43571. };
  43572. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43573. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  43574. };
  43575. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  43576. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  43577. };
  43578. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43579. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43580. };
  43581. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  43582. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  43583. };
  43584. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43585. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43586. };
  43587. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  43588. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  43589. };
  43590. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  43591. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  43592. };
  43593. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  43594. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  43595. };
  43596. Animation.prototype.clone = function () {
  43597. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  43598. clone.enableBlending = this.enableBlending;
  43599. clone.blendingSpeed = this.blendingSpeed;
  43600. if (this._keys) {
  43601. clone.setKeys(this._keys);
  43602. }
  43603. if (this._ranges) {
  43604. clone._ranges = {};
  43605. for (var name in this._ranges) {
  43606. var range = this._ranges[name];
  43607. if (!range) {
  43608. continue;
  43609. }
  43610. clone._ranges[name] = range.clone();
  43611. }
  43612. }
  43613. return clone;
  43614. };
  43615. Animation.prototype.setKeys = function (values) {
  43616. this._keys = values.slice(0);
  43617. };
  43618. Animation.prototype.serialize = function () {
  43619. var serializationObject = {};
  43620. serializationObject.name = this.name;
  43621. serializationObject.property = this.targetProperty;
  43622. serializationObject.framePerSecond = this.framePerSecond;
  43623. serializationObject.dataType = this.dataType;
  43624. serializationObject.loopBehavior = this.loopMode;
  43625. serializationObject.enableBlending = this.enableBlending;
  43626. serializationObject.blendingSpeed = this.blendingSpeed;
  43627. var dataType = this.dataType;
  43628. serializationObject.keys = [];
  43629. var keys = this.getKeys();
  43630. for (var index = 0; index < keys.length; index++) {
  43631. var animationKey = keys[index];
  43632. var key = {};
  43633. key.frame = animationKey.frame;
  43634. switch (dataType) {
  43635. case Animation.ANIMATIONTYPE_FLOAT:
  43636. key.values = [animationKey.value];
  43637. break;
  43638. case Animation.ANIMATIONTYPE_QUATERNION:
  43639. case Animation.ANIMATIONTYPE_MATRIX:
  43640. case Animation.ANIMATIONTYPE_VECTOR3:
  43641. case Animation.ANIMATIONTYPE_COLOR3:
  43642. key.values = animationKey.value.asArray();
  43643. break;
  43644. }
  43645. serializationObject.keys.push(key);
  43646. }
  43647. serializationObject.ranges = [];
  43648. for (var name in this._ranges) {
  43649. var source = this._ranges[name];
  43650. if (!source) {
  43651. continue;
  43652. }
  43653. var range = {};
  43654. range.name = name;
  43655. range.from = source.from;
  43656. range.to = source.to;
  43657. serializationObject.ranges.push(range);
  43658. }
  43659. return serializationObject;
  43660. };
  43661. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  43662. get: function () {
  43663. return Animation._ANIMATIONTYPE_FLOAT;
  43664. },
  43665. enumerable: true,
  43666. configurable: true
  43667. });
  43668. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  43669. get: function () {
  43670. return Animation._ANIMATIONTYPE_VECTOR3;
  43671. },
  43672. enumerable: true,
  43673. configurable: true
  43674. });
  43675. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  43676. get: function () {
  43677. return Animation._ANIMATIONTYPE_VECTOR2;
  43678. },
  43679. enumerable: true,
  43680. configurable: true
  43681. });
  43682. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  43683. get: function () {
  43684. return Animation._ANIMATIONTYPE_SIZE;
  43685. },
  43686. enumerable: true,
  43687. configurable: true
  43688. });
  43689. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  43690. get: function () {
  43691. return Animation._ANIMATIONTYPE_QUATERNION;
  43692. },
  43693. enumerable: true,
  43694. configurable: true
  43695. });
  43696. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  43697. get: function () {
  43698. return Animation._ANIMATIONTYPE_MATRIX;
  43699. },
  43700. enumerable: true,
  43701. configurable: true
  43702. });
  43703. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  43704. get: function () {
  43705. return Animation._ANIMATIONTYPE_COLOR3;
  43706. },
  43707. enumerable: true,
  43708. configurable: true
  43709. });
  43710. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  43711. get: function () {
  43712. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  43713. },
  43714. enumerable: true,
  43715. configurable: true
  43716. });
  43717. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  43718. get: function () {
  43719. return Animation._ANIMATIONLOOPMODE_CYCLE;
  43720. },
  43721. enumerable: true,
  43722. configurable: true
  43723. });
  43724. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  43725. get: function () {
  43726. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  43727. },
  43728. enumerable: true,
  43729. configurable: true
  43730. });
  43731. Animation.Parse = function (parsedAnimation) {
  43732. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  43733. var dataType = parsedAnimation.dataType;
  43734. var keys = [];
  43735. var data;
  43736. var index;
  43737. if (parsedAnimation.enableBlending) {
  43738. animation.enableBlending = parsedAnimation.enableBlending;
  43739. }
  43740. if (parsedAnimation.blendingSpeed) {
  43741. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  43742. }
  43743. for (index = 0; index < parsedAnimation.keys.length; index++) {
  43744. var key = parsedAnimation.keys[index];
  43745. var inTangent;
  43746. var outTangent;
  43747. switch (dataType) {
  43748. case Animation.ANIMATIONTYPE_FLOAT:
  43749. data = key.values[0];
  43750. if (key.values.length >= 1) {
  43751. inTangent = key.values[1];
  43752. }
  43753. if (key.values.length >= 2) {
  43754. outTangent = key.values[2];
  43755. }
  43756. break;
  43757. case Animation.ANIMATIONTYPE_QUATERNION:
  43758. data = BABYLON.Quaternion.FromArray(key.values);
  43759. if (key.values.length >= 8) {
  43760. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  43761. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  43762. inTangent = _inTangent;
  43763. }
  43764. }
  43765. if (key.values.length >= 12) {
  43766. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  43767. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  43768. outTangent = _outTangent;
  43769. }
  43770. }
  43771. break;
  43772. case Animation.ANIMATIONTYPE_MATRIX:
  43773. data = BABYLON.Matrix.FromArray(key.values);
  43774. break;
  43775. case Animation.ANIMATIONTYPE_COLOR3:
  43776. data = BABYLON.Color3.FromArray(key.values);
  43777. break;
  43778. case Animation.ANIMATIONTYPE_VECTOR3:
  43779. default:
  43780. data = BABYLON.Vector3.FromArray(key.values);
  43781. break;
  43782. }
  43783. var keyData = {};
  43784. keyData.frame = key.frame;
  43785. keyData.value = data;
  43786. if (inTangent != undefined) {
  43787. keyData.inTangent = inTangent;
  43788. }
  43789. if (outTangent != undefined) {
  43790. keyData.outTangent = outTangent;
  43791. }
  43792. keys.push(keyData);
  43793. }
  43794. animation.setKeys(keys);
  43795. if (parsedAnimation.ranges) {
  43796. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  43797. data = parsedAnimation.ranges[index];
  43798. animation.createRange(data.name, data.from, data.to);
  43799. }
  43800. }
  43801. return animation;
  43802. };
  43803. Animation.AppendSerializedAnimations = function (source, destination) {
  43804. if (source.animations) {
  43805. destination.animations = [];
  43806. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  43807. var animation = source.animations[animationIndex];
  43808. destination.animations.push(animation.serialize());
  43809. }
  43810. }
  43811. };
  43812. Animation.AllowMatricesInterpolation = false;
  43813. // Statics
  43814. Animation._ANIMATIONTYPE_FLOAT = 0;
  43815. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  43816. Animation._ANIMATIONTYPE_QUATERNION = 2;
  43817. Animation._ANIMATIONTYPE_MATRIX = 3;
  43818. Animation._ANIMATIONTYPE_COLOR3 = 4;
  43819. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  43820. Animation._ANIMATIONTYPE_SIZE = 6;
  43821. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  43822. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  43823. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  43824. return Animation;
  43825. }());
  43826. BABYLON.Animation = Animation;
  43827. })(BABYLON || (BABYLON = {}));
  43828. //# sourceMappingURL=babylon.animation.js.map
  43829. var BABYLON;
  43830. (function (BABYLON) {
  43831. /**
  43832. * This class defines the direct association between an animation and a target
  43833. */
  43834. var TargetedAnimation = /** @class */ (function () {
  43835. function TargetedAnimation() {
  43836. }
  43837. return TargetedAnimation;
  43838. }());
  43839. BABYLON.TargetedAnimation = TargetedAnimation;
  43840. /**
  43841. * Use this class to create coordinated animations on multiple targets
  43842. */
  43843. var AnimationGroup = /** @class */ (function () {
  43844. function AnimationGroup(name, scene) {
  43845. if (scene === void 0) { scene = null; }
  43846. this.name = name;
  43847. this._targetedAnimations = new Array();
  43848. this._animatables = new Array();
  43849. this._from = Number.MAX_VALUE;
  43850. this._to = -Number.MAX_VALUE;
  43851. this._speedRatio = 1;
  43852. this.onAnimationEndObservable = new BABYLON.Observable();
  43853. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43854. this._scene.animationGroups.push(this);
  43855. }
  43856. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  43857. /**
  43858. * Define if the animations are started
  43859. */
  43860. get: function () {
  43861. return this._isStarted;
  43862. },
  43863. enumerable: true,
  43864. configurable: true
  43865. });
  43866. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  43867. /**
  43868. * Gets or sets the speed ratio to use for all animations
  43869. */
  43870. get: function () {
  43871. return this._speedRatio;
  43872. },
  43873. /**
  43874. * Gets or sets the speed ratio to use for all animations
  43875. */
  43876. set: function (value) {
  43877. if (this._speedRatio === value) {
  43878. return;
  43879. }
  43880. this._speedRatio = value;
  43881. for (var index = 0; index < this._animatables.length; index++) {
  43882. var animatable = this._animatables[index];
  43883. animatable.speedRatio = this._speedRatio;
  43884. }
  43885. },
  43886. enumerable: true,
  43887. configurable: true
  43888. });
  43889. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  43890. /**
  43891. * Gets the targeted animations for this animation group
  43892. */
  43893. get: function () {
  43894. return this._targetedAnimations;
  43895. },
  43896. enumerable: true,
  43897. configurable: true
  43898. });
  43899. /**
  43900. * Add an animation (with its target) in the group
  43901. * @param animation defines the animation we want to add
  43902. * @param target defines the target of the animation
  43903. * @returns the {BABYLON.TargetedAnimation} object
  43904. */
  43905. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  43906. var targetedAnimation = {
  43907. animation: animation,
  43908. target: target
  43909. };
  43910. var keys = animation.getKeys();
  43911. if (this._from > keys[0].frame) {
  43912. this._from = keys[0].frame;
  43913. }
  43914. if (this._to < keys[keys.length - 1].frame) {
  43915. this._to = keys[keys.length - 1].frame;
  43916. }
  43917. this._targetedAnimations.push(targetedAnimation);
  43918. return targetedAnimation;
  43919. };
  43920. /**
  43921. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  43922. * It can add constant keys at begin or end
  43923. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  43924. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  43925. */
  43926. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  43927. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  43928. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  43929. beginFrame = Math.max(beginFrame, this._from);
  43930. endFrame = Math.min(endFrame, this._to);
  43931. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43932. var targetedAnimation = this._targetedAnimations[index];
  43933. var keys = targetedAnimation.animation.getKeys();
  43934. var startKey = keys[0];
  43935. var endKey = keys[keys.length - 1];
  43936. if (startKey.frame > beginFrame) {
  43937. var newKey = {
  43938. frame: beginFrame,
  43939. value: startKey.value,
  43940. inTangent: startKey.inTangent,
  43941. outTangent: startKey.outTangent,
  43942. interpolation: startKey.interpolation
  43943. };
  43944. keys.splice(0, 0, newKey);
  43945. }
  43946. if (endKey.frame < endFrame) {
  43947. var newKey = {
  43948. frame: endFrame,
  43949. value: endKey.value,
  43950. inTangent: endKey.outTangent,
  43951. outTangent: endKey.outTangent,
  43952. interpolation: endKey.interpolation
  43953. };
  43954. keys.push(newKey);
  43955. }
  43956. }
  43957. return this;
  43958. };
  43959. /**
  43960. * Start all animations on given targets
  43961. * @param loop defines if animations must loop
  43962. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  43963. */
  43964. AnimationGroup.prototype.start = function (loop, speedRatio) {
  43965. var _this = this;
  43966. if (loop === void 0) { loop = false; }
  43967. if (speedRatio === void 0) { speedRatio = 1; }
  43968. if (this._isStarted || this._targetedAnimations.length === 0) {
  43969. return this;
  43970. }
  43971. var _loop_1 = function () {
  43972. var targetedAnimation = this_1._targetedAnimations[index];
  43973. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  43974. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  43975. }));
  43976. };
  43977. var this_1 = this;
  43978. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43979. _loop_1();
  43980. }
  43981. this._speedRatio = speedRatio;
  43982. this._isStarted = true;
  43983. return this;
  43984. };
  43985. /**
  43986. * Pause all animations
  43987. */
  43988. AnimationGroup.prototype.pause = function () {
  43989. if (!this._isStarted) {
  43990. return this;
  43991. }
  43992. for (var index = 0; index < this._animatables.length; index++) {
  43993. var animatable = this._animatables[index];
  43994. animatable.pause();
  43995. }
  43996. return this;
  43997. };
  43998. /**
  43999. * Play all animations to initial state
  44000. * This function will start() the animations if they were not started or will restart() them if they were paused
  44001. * @param loop defines if animations must loop
  44002. */
  44003. AnimationGroup.prototype.play = function (loop) {
  44004. if (this.isStarted) {
  44005. if (loop !== undefined) {
  44006. for (var index = 0; index < this._animatables.length; index++) {
  44007. var animatable = this._animatables[index];
  44008. animatable.loopAnimation = loop;
  44009. }
  44010. }
  44011. this.restart();
  44012. }
  44013. else {
  44014. this.start(loop, this._speedRatio);
  44015. }
  44016. return this;
  44017. };
  44018. /**
  44019. * Reset all animations to initial state
  44020. */
  44021. AnimationGroup.prototype.reset = function () {
  44022. if (!this._isStarted) {
  44023. return this;
  44024. }
  44025. for (var index = 0; index < this._animatables.length; index++) {
  44026. var animatable = this._animatables[index];
  44027. animatable.reset();
  44028. }
  44029. return this;
  44030. };
  44031. /**
  44032. * Restart animations from key 0
  44033. */
  44034. AnimationGroup.prototype.restart = function () {
  44035. if (!this._isStarted) {
  44036. return this;
  44037. }
  44038. for (var index = 0; index < this._animatables.length; index++) {
  44039. var animatable = this._animatables[index];
  44040. animatable.restart();
  44041. }
  44042. return this;
  44043. };
  44044. /**
  44045. * Stop all animations
  44046. */
  44047. AnimationGroup.prototype.stop = function () {
  44048. if (!this._isStarted) {
  44049. return this;
  44050. }
  44051. for (var index = 0; index < this._animatables.length; index++) {
  44052. var animatable = this._animatables[index];
  44053. animatable.stop();
  44054. }
  44055. this._isStarted = false;
  44056. return this;
  44057. };
  44058. /**
  44059. * Dispose all associated resources
  44060. */
  44061. AnimationGroup.prototype.dispose = function () {
  44062. this._targetedAnimations = [];
  44063. this._animatables = [];
  44064. var index = this._scene.animationGroups.indexOf(this);
  44065. if (index > -1) {
  44066. this._scene.animationGroups.splice(index, 1);
  44067. }
  44068. };
  44069. return AnimationGroup;
  44070. }());
  44071. BABYLON.AnimationGroup = AnimationGroup;
  44072. })(BABYLON || (BABYLON = {}));
  44073. //# sourceMappingURL=babylon.animationGroup.js.map
  44074. var BABYLON;
  44075. (function (BABYLON) {
  44076. var RuntimeAnimation = /** @class */ (function () {
  44077. function RuntimeAnimation(target, animation) {
  44078. this._offsetsCache = {};
  44079. this._highLimitsCache = {};
  44080. this._stopped = false;
  44081. this._blendingFactor = 0;
  44082. this._ratioOffset = 0;
  44083. this._animation = animation;
  44084. this._target = target;
  44085. animation._runtimeAnimations.push(this);
  44086. }
  44087. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  44088. get: function () {
  44089. return this._animation;
  44090. },
  44091. enumerable: true,
  44092. configurable: true
  44093. });
  44094. RuntimeAnimation.prototype.reset = function () {
  44095. this._offsetsCache = {};
  44096. this._highLimitsCache = {};
  44097. this.currentFrame = 0;
  44098. this._blendingFactor = 0;
  44099. this._originalBlendValue = null;
  44100. };
  44101. RuntimeAnimation.prototype.isStopped = function () {
  44102. return this._stopped;
  44103. };
  44104. RuntimeAnimation.prototype.dispose = function () {
  44105. var index = this._animation.runtimeAnimations.indexOf(this);
  44106. if (index > -1) {
  44107. this._animation.runtimeAnimations.splice(index, 1);
  44108. }
  44109. };
  44110. RuntimeAnimation.prototype._getKeyValue = function (value) {
  44111. if (typeof value === "function") {
  44112. return value();
  44113. }
  44114. return value;
  44115. };
  44116. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  44117. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  44118. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  44119. }
  44120. this.currentFrame = currentFrame;
  44121. var keys = this._animation.getKeys();
  44122. // Try to get a hash to find the right key
  44123. 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));
  44124. if (keys[startKeyIndex].frame >= currentFrame) {
  44125. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  44126. startKeyIndex--;
  44127. }
  44128. }
  44129. for (var key = startKeyIndex; key < keys.length; key++) {
  44130. var endKey = keys[key + 1];
  44131. if (endKey.frame >= currentFrame) {
  44132. var startKey = keys[key];
  44133. var startValue = this._getKeyValue(startKey.value);
  44134. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  44135. return startValue;
  44136. }
  44137. var endValue = this._getKeyValue(endKey.value);
  44138. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  44139. var frameDelta = endKey.frame - startKey.frame;
  44140. // gradient : percent of currentFrame between the frame inf and the frame sup
  44141. var gradient = (currentFrame - startKey.frame) / frameDelta;
  44142. // check for easingFunction and correction of gradient
  44143. var easingFunction = this._animation.getEasingFunction();
  44144. if (easingFunction != null) {
  44145. gradient = easingFunction.ease(gradient);
  44146. }
  44147. switch (this._animation.dataType) {
  44148. // Float
  44149. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44150. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  44151. switch (loopMode) {
  44152. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44153. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44154. return floatValue;
  44155. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44156. return offsetValue * repeatCount + floatValue;
  44157. }
  44158. break;
  44159. // Quaternion
  44160. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44161. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  44162. switch (loopMode) {
  44163. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44164. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44165. return quatValue;
  44166. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44167. return quatValue.add(offsetValue.scale(repeatCount));
  44168. }
  44169. return quatValue;
  44170. // Vector3
  44171. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44172. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  44173. switch (loopMode) {
  44174. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44175. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44176. return vec3Value;
  44177. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44178. return vec3Value.add(offsetValue.scale(repeatCount));
  44179. }
  44180. // Vector2
  44181. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44182. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  44183. switch (loopMode) {
  44184. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44185. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44186. return vec2Value;
  44187. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44188. return vec2Value.add(offsetValue.scale(repeatCount));
  44189. }
  44190. // Size
  44191. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44192. switch (loopMode) {
  44193. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44194. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44195. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  44196. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44197. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44198. }
  44199. // Color3
  44200. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44201. switch (loopMode) {
  44202. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44203. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44204. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  44205. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44206. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  44207. }
  44208. // Matrix
  44209. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  44210. switch (loopMode) {
  44211. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  44212. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  44213. if (BABYLON.Animation.AllowMatricesInterpolation) {
  44214. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  44215. }
  44216. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  44217. return startValue;
  44218. }
  44219. default:
  44220. break;
  44221. }
  44222. break;
  44223. }
  44224. }
  44225. return this._getKeyValue(keys[keys.length - 1].value);
  44226. };
  44227. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  44228. if (blend === void 0) { blend = false; }
  44229. // Set value
  44230. var path;
  44231. var destination;
  44232. var targetPropertyPath = this._animation.targetPropertyPath;
  44233. if (targetPropertyPath.length > 1) {
  44234. var property = this._target[targetPropertyPath[0]];
  44235. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  44236. property = property[targetPropertyPath[index]];
  44237. }
  44238. path = targetPropertyPath[targetPropertyPath.length - 1];
  44239. destination = property;
  44240. }
  44241. else {
  44242. path = targetPropertyPath[0];
  44243. destination = this._target;
  44244. }
  44245. // Blending
  44246. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  44247. if (!this._originalBlendValue) {
  44248. if (destination[path].clone) {
  44249. this._originalBlendValue = destination[path].clone();
  44250. }
  44251. else {
  44252. this._originalBlendValue = destination[path];
  44253. }
  44254. }
  44255. if (this._originalBlendValue.prototype) {
  44256. if (this._originalBlendValue.prototype.Lerp) {
  44257. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  44258. }
  44259. else {
  44260. destination[path] = currentValue;
  44261. }
  44262. }
  44263. else if (this._originalBlendValue.m) {
  44264. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  44265. }
  44266. else {
  44267. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  44268. }
  44269. this._blendingFactor += this._animation.blendingSpeed;
  44270. }
  44271. else {
  44272. destination[path] = currentValue;
  44273. }
  44274. if (this._target.markAsDirty) {
  44275. this._target.markAsDirty(this._animation.targetProperty);
  44276. }
  44277. };
  44278. RuntimeAnimation.prototype.goToFrame = function (frame) {
  44279. var keys = this._animation.getKeys();
  44280. if (frame < keys[0].frame) {
  44281. frame = keys[0].frame;
  44282. }
  44283. else if (frame > keys[keys.length - 1].frame) {
  44284. frame = keys[keys.length - 1].frame;
  44285. }
  44286. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  44287. this.setValue(currentValue);
  44288. };
  44289. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  44290. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  44291. this._ratioOffset = this._previousRatio - newRatio;
  44292. };
  44293. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  44294. if (blend === void 0) { blend = false; }
  44295. var targetPropertyPath = this._animation.targetPropertyPath;
  44296. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  44297. this._stopped = true;
  44298. return false;
  44299. }
  44300. var returnValue = true;
  44301. var keys = this._animation.getKeys();
  44302. // Adding a start key at frame 0 if missing
  44303. if (keys[0].frame !== 0) {
  44304. var newKey = { frame: 0, value: keys[0].value };
  44305. keys.splice(0, 0, newKey);
  44306. }
  44307. // Check limits
  44308. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  44309. from = keys[0].frame;
  44310. }
  44311. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  44312. to = keys[keys.length - 1].frame;
  44313. }
  44314. //to and from cannot be the same key
  44315. if (from === to) {
  44316. if (from > keys[0].frame) {
  44317. from--;
  44318. }
  44319. else if (to < keys[keys.length - 1].frame) {
  44320. to++;
  44321. }
  44322. }
  44323. // Compute ratio
  44324. var range = to - from;
  44325. var offsetValue;
  44326. // ratio represents the frame delta between from and to
  44327. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  44328. var highLimitValue = 0;
  44329. this._previousDelay = delay;
  44330. this._previousRatio = ratio;
  44331. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  44332. returnValue = false;
  44333. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  44334. }
  44335. else {
  44336. // Get max value if required
  44337. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  44338. var keyOffset = to.toString() + from.toString();
  44339. if (!this._offsetsCache[keyOffset]) {
  44340. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44341. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44342. switch (this._animation.dataType) {
  44343. // Float
  44344. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44345. this._offsetsCache[keyOffset] = toValue - fromValue;
  44346. break;
  44347. // Quaternion
  44348. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44349. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44350. break;
  44351. // Vector3
  44352. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44353. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44354. // Vector2
  44355. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44356. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44357. // Size
  44358. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44359. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44360. // Color3
  44361. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44362. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44363. default:
  44364. break;
  44365. }
  44366. this._highLimitsCache[keyOffset] = toValue;
  44367. }
  44368. highLimitValue = this._highLimitsCache[keyOffset];
  44369. offsetValue = this._offsetsCache[keyOffset];
  44370. }
  44371. }
  44372. if (offsetValue === undefined) {
  44373. switch (this._animation.dataType) {
  44374. // Float
  44375. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44376. offsetValue = 0;
  44377. break;
  44378. // Quaternion
  44379. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44380. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  44381. break;
  44382. // Vector3
  44383. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44384. offsetValue = BABYLON.Vector3.Zero();
  44385. break;
  44386. // Vector2
  44387. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44388. offsetValue = BABYLON.Vector2.Zero();
  44389. break;
  44390. // Size
  44391. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44392. offsetValue = BABYLON.Size.Zero();
  44393. break;
  44394. // Color3
  44395. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44396. offsetValue = BABYLON.Color3.Black();
  44397. }
  44398. }
  44399. // Compute value
  44400. var repeatCount = (ratio / range) >> 0;
  44401. var currentFrame = returnValue ? from + ratio % range : to;
  44402. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  44403. // Set value
  44404. this.setValue(currentValue);
  44405. // Check events
  44406. var events = this._animation.getEvents();
  44407. for (var index = 0; index < events.length; index++) {
  44408. // Make sure current frame has passed event frame and that event frame is within the current range
  44409. // Also, handle both forward and reverse animations
  44410. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  44411. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  44412. var event = events[index];
  44413. if (!event.isDone) {
  44414. // If event should be done only once, remove it.
  44415. if (event.onlyOnce) {
  44416. events.splice(index, 1);
  44417. index--;
  44418. }
  44419. event.isDone = true;
  44420. event.action();
  44421. } // Don't do anything if the event has already be done.
  44422. }
  44423. else if (events[index].isDone && !events[index].onlyOnce) {
  44424. // reset event, the animation is looping
  44425. events[index].isDone = false;
  44426. }
  44427. }
  44428. if (!returnValue) {
  44429. this._stopped = true;
  44430. }
  44431. return returnValue;
  44432. };
  44433. return RuntimeAnimation;
  44434. }());
  44435. BABYLON.RuntimeAnimation = RuntimeAnimation;
  44436. })(BABYLON || (BABYLON = {}));
  44437. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  44438. var BABYLON;
  44439. (function (BABYLON) {
  44440. var Animatable = /** @class */ (function () {
  44441. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  44442. if (fromFrame === void 0) { fromFrame = 0; }
  44443. if (toFrame === void 0) { toFrame = 100; }
  44444. if (loopAnimation === void 0) { loopAnimation = false; }
  44445. if (speedRatio === void 0) { speedRatio = 1.0; }
  44446. this.target = target;
  44447. this.fromFrame = fromFrame;
  44448. this.toFrame = toFrame;
  44449. this.loopAnimation = loopAnimation;
  44450. this.onAnimationEnd = onAnimationEnd;
  44451. this._localDelayOffset = null;
  44452. this._pausedDelay = null;
  44453. this._runtimeAnimations = new Array();
  44454. this._paused = false;
  44455. this._speedRatio = 1;
  44456. this.animationStarted = false;
  44457. if (animations) {
  44458. this.appendAnimations(target, animations);
  44459. }
  44460. this._speedRatio = speedRatio;
  44461. this._scene = scene;
  44462. scene._activeAnimatables.push(this);
  44463. }
  44464. Object.defineProperty(Animatable.prototype, "speedRatio", {
  44465. get: function () {
  44466. return this._speedRatio;
  44467. },
  44468. set: function (value) {
  44469. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  44470. var animation = this._runtimeAnimations[index];
  44471. animation._prepareForSpeedRatioChange(value);
  44472. }
  44473. this._speedRatio = value;
  44474. },
  44475. enumerable: true,
  44476. configurable: true
  44477. });
  44478. // Methods
  44479. Animatable.prototype.getAnimations = function () {
  44480. return this._runtimeAnimations;
  44481. };
  44482. Animatable.prototype.appendAnimations = function (target, animations) {
  44483. for (var index = 0; index < animations.length; index++) {
  44484. var animation = animations[index];
  44485. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  44486. }
  44487. };
  44488. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  44489. var runtimeAnimations = this._runtimeAnimations;
  44490. for (var index = 0; index < runtimeAnimations.length; index++) {
  44491. if (runtimeAnimations[index].animation.targetProperty === property) {
  44492. return runtimeAnimations[index].animation;
  44493. }
  44494. }
  44495. return null;
  44496. };
  44497. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  44498. var runtimeAnimations = this._runtimeAnimations;
  44499. for (var index = 0; index < runtimeAnimations.length; index++) {
  44500. if (runtimeAnimations[index].animation.targetProperty === property) {
  44501. return runtimeAnimations[index];
  44502. }
  44503. }
  44504. return null;
  44505. };
  44506. Animatable.prototype.reset = function () {
  44507. var runtimeAnimations = this._runtimeAnimations;
  44508. for (var index = 0; index < runtimeAnimations.length; index++) {
  44509. runtimeAnimations[index].reset();
  44510. }
  44511. // Reset to original value
  44512. for (index = 0; index < runtimeAnimations.length; index++) {
  44513. var animation = runtimeAnimations[index];
  44514. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  44515. }
  44516. this._localDelayOffset = null;
  44517. this._pausedDelay = null;
  44518. };
  44519. Animatable.prototype.enableBlending = function (blendingSpeed) {
  44520. var runtimeAnimations = this._runtimeAnimations;
  44521. for (var index = 0; index < runtimeAnimations.length; index++) {
  44522. runtimeAnimations[index].animation.enableBlending = true;
  44523. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  44524. }
  44525. };
  44526. Animatable.prototype.disableBlending = function () {
  44527. var runtimeAnimations = this._runtimeAnimations;
  44528. for (var index = 0; index < runtimeAnimations.length; index++) {
  44529. runtimeAnimations[index].animation.enableBlending = false;
  44530. }
  44531. };
  44532. Animatable.prototype.goToFrame = function (frame) {
  44533. var runtimeAnimations = this._runtimeAnimations;
  44534. if (runtimeAnimations[0]) {
  44535. var fps = runtimeAnimations[0].animation.framePerSecond;
  44536. var currentFrame = runtimeAnimations[0].currentFrame;
  44537. var adjustTime = frame - currentFrame;
  44538. var delay = adjustTime * 1000 / fps;
  44539. if (this._localDelayOffset === null) {
  44540. this._localDelayOffset = 0;
  44541. }
  44542. this._localDelayOffset -= delay;
  44543. }
  44544. for (var index = 0; index < runtimeAnimations.length; index++) {
  44545. runtimeAnimations[index].goToFrame(frame);
  44546. }
  44547. };
  44548. Animatable.prototype.pause = function () {
  44549. if (this._paused) {
  44550. return;
  44551. }
  44552. this._paused = true;
  44553. };
  44554. Animatable.prototype.restart = function () {
  44555. this._paused = false;
  44556. };
  44557. Animatable.prototype.stop = function (animationName) {
  44558. if (animationName) {
  44559. var idx = this._scene._activeAnimatables.indexOf(this);
  44560. if (idx > -1) {
  44561. var runtimeAnimations = this._runtimeAnimations;
  44562. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  44563. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  44564. continue;
  44565. }
  44566. runtimeAnimations[index].dispose();
  44567. runtimeAnimations.splice(index, 1);
  44568. }
  44569. if (runtimeAnimations.length == 0) {
  44570. this._scene._activeAnimatables.splice(idx, 1);
  44571. if (this.onAnimationEnd) {
  44572. this.onAnimationEnd();
  44573. }
  44574. }
  44575. }
  44576. }
  44577. else {
  44578. var index = this._scene._activeAnimatables.indexOf(this);
  44579. if (index > -1) {
  44580. this._scene._activeAnimatables.splice(index, 1);
  44581. var runtimeAnimations = this._runtimeAnimations;
  44582. for (var index = 0; index < runtimeAnimations.length; index++) {
  44583. runtimeAnimations[index].dispose();
  44584. }
  44585. if (this.onAnimationEnd) {
  44586. this.onAnimationEnd();
  44587. }
  44588. }
  44589. }
  44590. };
  44591. Animatable.prototype._animate = function (delay) {
  44592. if (this._paused) {
  44593. this.animationStarted = false;
  44594. if (this._pausedDelay === null) {
  44595. this._pausedDelay = delay;
  44596. }
  44597. return true;
  44598. }
  44599. if (this._localDelayOffset === null) {
  44600. this._localDelayOffset = delay;
  44601. this._pausedDelay = null;
  44602. }
  44603. else if (this._pausedDelay !== null) {
  44604. this._localDelayOffset += delay - this._pausedDelay;
  44605. this._pausedDelay = null;
  44606. }
  44607. // Animating
  44608. var running = false;
  44609. var runtimeAnimations = this._runtimeAnimations;
  44610. var index;
  44611. for (index = 0; index < runtimeAnimations.length; index++) {
  44612. var animation = runtimeAnimations[index];
  44613. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  44614. running = running || isRunning;
  44615. }
  44616. this.animationStarted = running;
  44617. if (!running) {
  44618. // Remove from active animatables
  44619. index = this._scene._activeAnimatables.indexOf(this);
  44620. this._scene._activeAnimatables.splice(index, 1);
  44621. // Dispose all runtime animations
  44622. for (index = 0; index < runtimeAnimations.length; index++) {
  44623. runtimeAnimations[index].dispose();
  44624. }
  44625. }
  44626. if (!running && this.onAnimationEnd) {
  44627. this.onAnimationEnd();
  44628. this.onAnimationEnd = null;
  44629. }
  44630. return running;
  44631. };
  44632. return Animatable;
  44633. }());
  44634. BABYLON.Animatable = Animatable;
  44635. })(BABYLON || (BABYLON = {}));
  44636. //# sourceMappingURL=babylon.animatable.js.map
  44637. var BABYLON;
  44638. (function (BABYLON) {
  44639. var EasingFunction = /** @class */ (function () {
  44640. function EasingFunction() {
  44641. // Properties
  44642. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  44643. }
  44644. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  44645. get: function () {
  44646. return EasingFunction._EASINGMODE_EASEIN;
  44647. },
  44648. enumerable: true,
  44649. configurable: true
  44650. });
  44651. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  44652. get: function () {
  44653. return EasingFunction._EASINGMODE_EASEOUT;
  44654. },
  44655. enumerable: true,
  44656. configurable: true
  44657. });
  44658. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  44659. get: function () {
  44660. return EasingFunction._EASINGMODE_EASEINOUT;
  44661. },
  44662. enumerable: true,
  44663. configurable: true
  44664. });
  44665. EasingFunction.prototype.setEasingMode = function (easingMode) {
  44666. var n = Math.min(Math.max(easingMode, 0), 2);
  44667. this._easingMode = n;
  44668. };
  44669. EasingFunction.prototype.getEasingMode = function () {
  44670. return this._easingMode;
  44671. };
  44672. EasingFunction.prototype.easeInCore = function (gradient) {
  44673. throw new Error('You must implement this method');
  44674. };
  44675. EasingFunction.prototype.ease = function (gradient) {
  44676. switch (this._easingMode) {
  44677. case EasingFunction.EASINGMODE_EASEIN:
  44678. return this.easeInCore(gradient);
  44679. case EasingFunction.EASINGMODE_EASEOUT:
  44680. return (1 - this.easeInCore(1 - gradient));
  44681. }
  44682. if (gradient >= 0.5) {
  44683. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  44684. }
  44685. return (this.easeInCore(gradient * 2) * 0.5);
  44686. };
  44687. //Statics
  44688. EasingFunction._EASINGMODE_EASEIN = 0;
  44689. EasingFunction._EASINGMODE_EASEOUT = 1;
  44690. EasingFunction._EASINGMODE_EASEINOUT = 2;
  44691. return EasingFunction;
  44692. }());
  44693. BABYLON.EasingFunction = EasingFunction;
  44694. var CircleEase = /** @class */ (function (_super) {
  44695. __extends(CircleEase, _super);
  44696. function CircleEase() {
  44697. return _super !== null && _super.apply(this, arguments) || this;
  44698. }
  44699. CircleEase.prototype.easeInCore = function (gradient) {
  44700. gradient = Math.max(0, Math.min(1, gradient));
  44701. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  44702. };
  44703. return CircleEase;
  44704. }(EasingFunction));
  44705. BABYLON.CircleEase = CircleEase;
  44706. var BackEase = /** @class */ (function (_super) {
  44707. __extends(BackEase, _super);
  44708. function BackEase(amplitude) {
  44709. if (amplitude === void 0) { amplitude = 1; }
  44710. var _this = _super.call(this) || this;
  44711. _this.amplitude = amplitude;
  44712. return _this;
  44713. }
  44714. BackEase.prototype.easeInCore = function (gradient) {
  44715. var num = Math.max(0, this.amplitude);
  44716. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  44717. };
  44718. return BackEase;
  44719. }(EasingFunction));
  44720. BABYLON.BackEase = BackEase;
  44721. var BounceEase = /** @class */ (function (_super) {
  44722. __extends(BounceEase, _super);
  44723. function BounceEase(bounces, bounciness) {
  44724. if (bounces === void 0) { bounces = 3; }
  44725. if (bounciness === void 0) { bounciness = 2; }
  44726. var _this = _super.call(this) || this;
  44727. _this.bounces = bounces;
  44728. _this.bounciness = bounciness;
  44729. return _this;
  44730. }
  44731. BounceEase.prototype.easeInCore = function (gradient) {
  44732. var y = Math.max(0.0, this.bounces);
  44733. var bounciness = this.bounciness;
  44734. if (bounciness <= 1.0) {
  44735. bounciness = 1.001;
  44736. }
  44737. var num9 = Math.pow(bounciness, y);
  44738. var num5 = 1.0 - bounciness;
  44739. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  44740. var num15 = gradient * num4;
  44741. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  44742. var num3 = Math.floor(num65);
  44743. var num13 = num3 + 1.0;
  44744. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  44745. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  44746. var num7 = (num8 + num12) * 0.5;
  44747. var num6 = gradient - num7;
  44748. var num2 = num7 - num8;
  44749. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  44750. };
  44751. return BounceEase;
  44752. }(EasingFunction));
  44753. BABYLON.BounceEase = BounceEase;
  44754. var CubicEase = /** @class */ (function (_super) {
  44755. __extends(CubicEase, _super);
  44756. function CubicEase() {
  44757. return _super !== null && _super.apply(this, arguments) || this;
  44758. }
  44759. CubicEase.prototype.easeInCore = function (gradient) {
  44760. return (gradient * gradient * gradient);
  44761. };
  44762. return CubicEase;
  44763. }(EasingFunction));
  44764. BABYLON.CubicEase = CubicEase;
  44765. var ElasticEase = /** @class */ (function (_super) {
  44766. __extends(ElasticEase, _super);
  44767. function ElasticEase(oscillations, springiness) {
  44768. if (oscillations === void 0) { oscillations = 3; }
  44769. if (springiness === void 0) { springiness = 3; }
  44770. var _this = _super.call(this) || this;
  44771. _this.oscillations = oscillations;
  44772. _this.springiness = springiness;
  44773. return _this;
  44774. }
  44775. ElasticEase.prototype.easeInCore = function (gradient) {
  44776. var num2;
  44777. var num3 = Math.max(0.0, this.oscillations);
  44778. var num = Math.max(0.0, this.springiness);
  44779. if (num == 0) {
  44780. num2 = gradient;
  44781. }
  44782. else {
  44783. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  44784. }
  44785. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  44786. };
  44787. return ElasticEase;
  44788. }(EasingFunction));
  44789. BABYLON.ElasticEase = ElasticEase;
  44790. var ExponentialEase = /** @class */ (function (_super) {
  44791. __extends(ExponentialEase, _super);
  44792. function ExponentialEase(exponent) {
  44793. if (exponent === void 0) { exponent = 2; }
  44794. var _this = _super.call(this) || this;
  44795. _this.exponent = exponent;
  44796. return _this;
  44797. }
  44798. ExponentialEase.prototype.easeInCore = function (gradient) {
  44799. if (this.exponent <= 0) {
  44800. return gradient;
  44801. }
  44802. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  44803. };
  44804. return ExponentialEase;
  44805. }(EasingFunction));
  44806. BABYLON.ExponentialEase = ExponentialEase;
  44807. var PowerEase = /** @class */ (function (_super) {
  44808. __extends(PowerEase, _super);
  44809. function PowerEase(power) {
  44810. if (power === void 0) { power = 2; }
  44811. var _this = _super.call(this) || this;
  44812. _this.power = power;
  44813. return _this;
  44814. }
  44815. PowerEase.prototype.easeInCore = function (gradient) {
  44816. var y = Math.max(0.0, this.power);
  44817. return Math.pow(gradient, y);
  44818. };
  44819. return PowerEase;
  44820. }(EasingFunction));
  44821. BABYLON.PowerEase = PowerEase;
  44822. var QuadraticEase = /** @class */ (function (_super) {
  44823. __extends(QuadraticEase, _super);
  44824. function QuadraticEase() {
  44825. return _super !== null && _super.apply(this, arguments) || this;
  44826. }
  44827. QuadraticEase.prototype.easeInCore = function (gradient) {
  44828. return (gradient * gradient);
  44829. };
  44830. return QuadraticEase;
  44831. }(EasingFunction));
  44832. BABYLON.QuadraticEase = QuadraticEase;
  44833. var QuarticEase = /** @class */ (function (_super) {
  44834. __extends(QuarticEase, _super);
  44835. function QuarticEase() {
  44836. return _super !== null && _super.apply(this, arguments) || this;
  44837. }
  44838. QuarticEase.prototype.easeInCore = function (gradient) {
  44839. return (gradient * gradient * gradient * gradient);
  44840. };
  44841. return QuarticEase;
  44842. }(EasingFunction));
  44843. BABYLON.QuarticEase = QuarticEase;
  44844. var QuinticEase = /** @class */ (function (_super) {
  44845. __extends(QuinticEase, _super);
  44846. function QuinticEase() {
  44847. return _super !== null && _super.apply(this, arguments) || this;
  44848. }
  44849. QuinticEase.prototype.easeInCore = function (gradient) {
  44850. return (gradient * gradient * gradient * gradient * gradient);
  44851. };
  44852. return QuinticEase;
  44853. }(EasingFunction));
  44854. BABYLON.QuinticEase = QuinticEase;
  44855. var SineEase = /** @class */ (function (_super) {
  44856. __extends(SineEase, _super);
  44857. function SineEase() {
  44858. return _super !== null && _super.apply(this, arguments) || this;
  44859. }
  44860. SineEase.prototype.easeInCore = function (gradient) {
  44861. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  44862. };
  44863. return SineEase;
  44864. }(EasingFunction));
  44865. BABYLON.SineEase = SineEase;
  44866. var BezierCurveEase = /** @class */ (function (_super) {
  44867. __extends(BezierCurveEase, _super);
  44868. function BezierCurveEase(x1, y1, x2, y2) {
  44869. if (x1 === void 0) { x1 = 0; }
  44870. if (y1 === void 0) { y1 = 0; }
  44871. if (x2 === void 0) { x2 = 1; }
  44872. if (y2 === void 0) { y2 = 1; }
  44873. var _this = _super.call(this) || this;
  44874. _this.x1 = x1;
  44875. _this.y1 = y1;
  44876. _this.x2 = x2;
  44877. _this.y2 = y2;
  44878. return _this;
  44879. }
  44880. BezierCurveEase.prototype.easeInCore = function (gradient) {
  44881. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  44882. };
  44883. return BezierCurveEase;
  44884. }(EasingFunction));
  44885. BABYLON.BezierCurveEase = BezierCurveEase;
  44886. })(BABYLON || (BABYLON = {}));
  44887. //# sourceMappingURL=babylon.easing.js.map
  44888. var BABYLON;
  44889. (function (BABYLON) {
  44890. var Condition = /** @class */ (function () {
  44891. function Condition(actionManager) {
  44892. this._actionManager = actionManager;
  44893. }
  44894. Condition.prototype.isValid = function () {
  44895. return true;
  44896. };
  44897. Condition.prototype._getProperty = function (propertyPath) {
  44898. return this._actionManager._getProperty(propertyPath);
  44899. };
  44900. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  44901. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44902. };
  44903. Condition.prototype.serialize = function () {
  44904. };
  44905. Condition.prototype._serialize = function (serializedCondition) {
  44906. return {
  44907. type: 2,
  44908. children: [],
  44909. name: serializedCondition.name,
  44910. properties: serializedCondition.properties
  44911. };
  44912. };
  44913. return Condition;
  44914. }());
  44915. BABYLON.Condition = Condition;
  44916. var ValueCondition = /** @class */ (function (_super) {
  44917. __extends(ValueCondition, _super);
  44918. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  44919. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  44920. var _this = _super.call(this, actionManager) || this;
  44921. _this.propertyPath = propertyPath;
  44922. _this.value = value;
  44923. _this.operator = operator;
  44924. _this._target = target;
  44925. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  44926. _this._property = _this._getProperty(_this.propertyPath);
  44927. return _this;
  44928. }
  44929. Object.defineProperty(ValueCondition, "IsEqual", {
  44930. get: function () {
  44931. return ValueCondition._IsEqual;
  44932. },
  44933. enumerable: true,
  44934. configurable: true
  44935. });
  44936. Object.defineProperty(ValueCondition, "IsDifferent", {
  44937. get: function () {
  44938. return ValueCondition._IsDifferent;
  44939. },
  44940. enumerable: true,
  44941. configurable: true
  44942. });
  44943. Object.defineProperty(ValueCondition, "IsGreater", {
  44944. get: function () {
  44945. return ValueCondition._IsGreater;
  44946. },
  44947. enumerable: true,
  44948. configurable: true
  44949. });
  44950. Object.defineProperty(ValueCondition, "IsLesser", {
  44951. get: function () {
  44952. return ValueCondition._IsLesser;
  44953. },
  44954. enumerable: true,
  44955. configurable: true
  44956. });
  44957. // Methods
  44958. ValueCondition.prototype.isValid = function () {
  44959. switch (this.operator) {
  44960. case ValueCondition.IsGreater:
  44961. return this._effectiveTarget[this._property] > this.value;
  44962. case ValueCondition.IsLesser:
  44963. return this._effectiveTarget[this._property] < this.value;
  44964. case ValueCondition.IsEqual:
  44965. case ValueCondition.IsDifferent:
  44966. var check;
  44967. if (this.value.equals) {
  44968. check = this.value.equals(this._effectiveTarget[this._property]);
  44969. }
  44970. else {
  44971. check = this.value === this._effectiveTarget[this._property];
  44972. }
  44973. return this.operator === ValueCondition.IsEqual ? check : !check;
  44974. }
  44975. return false;
  44976. };
  44977. ValueCondition.prototype.serialize = function () {
  44978. return this._serialize({
  44979. name: "ValueCondition",
  44980. properties: [
  44981. BABYLON.Action._GetTargetProperty(this._target),
  44982. { name: "propertyPath", value: this.propertyPath },
  44983. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44984. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  44985. ]
  44986. });
  44987. };
  44988. ValueCondition.GetOperatorName = function (operator) {
  44989. switch (operator) {
  44990. case ValueCondition._IsEqual: return "IsEqual";
  44991. case ValueCondition._IsDifferent: return "IsDifferent";
  44992. case ValueCondition._IsGreater: return "IsGreater";
  44993. case ValueCondition._IsLesser: return "IsLesser";
  44994. default: return "";
  44995. }
  44996. };
  44997. // Statics
  44998. ValueCondition._IsEqual = 0;
  44999. ValueCondition._IsDifferent = 1;
  45000. ValueCondition._IsGreater = 2;
  45001. ValueCondition._IsLesser = 3;
  45002. return ValueCondition;
  45003. }(Condition));
  45004. BABYLON.ValueCondition = ValueCondition;
  45005. var PredicateCondition = /** @class */ (function (_super) {
  45006. __extends(PredicateCondition, _super);
  45007. function PredicateCondition(actionManager, predicate) {
  45008. var _this = _super.call(this, actionManager) || this;
  45009. _this.predicate = predicate;
  45010. return _this;
  45011. }
  45012. PredicateCondition.prototype.isValid = function () {
  45013. return this.predicate();
  45014. };
  45015. return PredicateCondition;
  45016. }(Condition));
  45017. BABYLON.PredicateCondition = PredicateCondition;
  45018. var StateCondition = /** @class */ (function (_super) {
  45019. __extends(StateCondition, _super);
  45020. function StateCondition(actionManager, target, value) {
  45021. var _this = _super.call(this, actionManager) || this;
  45022. _this.value = value;
  45023. _this._target = target;
  45024. return _this;
  45025. }
  45026. // Methods
  45027. StateCondition.prototype.isValid = function () {
  45028. return this._target.state === this.value;
  45029. };
  45030. StateCondition.prototype.serialize = function () {
  45031. return this._serialize({
  45032. name: "StateCondition",
  45033. properties: [
  45034. BABYLON.Action._GetTargetProperty(this._target),
  45035. { name: "value", value: this.value }
  45036. ]
  45037. });
  45038. };
  45039. return StateCondition;
  45040. }(Condition));
  45041. BABYLON.StateCondition = StateCondition;
  45042. })(BABYLON || (BABYLON = {}));
  45043. //# sourceMappingURL=babylon.condition.js.map
  45044. var BABYLON;
  45045. (function (BABYLON) {
  45046. var Action = /** @class */ (function () {
  45047. function Action(triggerOptions, condition) {
  45048. this.triggerOptions = triggerOptions;
  45049. this.onBeforeExecuteObservable = new BABYLON.Observable();
  45050. if (triggerOptions.parameter) {
  45051. this.trigger = triggerOptions.trigger;
  45052. this._triggerParameter = triggerOptions.parameter;
  45053. }
  45054. else {
  45055. this.trigger = triggerOptions;
  45056. }
  45057. this._nextActiveAction = this;
  45058. this._condition = condition;
  45059. }
  45060. // Methods
  45061. Action.prototype._prepare = function () {
  45062. };
  45063. Action.prototype.getTriggerParameter = function () {
  45064. return this._triggerParameter;
  45065. };
  45066. Action.prototype._executeCurrent = function (evt) {
  45067. if (this._nextActiveAction._condition) {
  45068. var condition = this._nextActiveAction._condition;
  45069. var currentRenderId = this._actionManager.getScene().getRenderId();
  45070. // We cache the current evaluation for the current frame
  45071. if (condition._evaluationId === currentRenderId) {
  45072. if (!condition._currentResult) {
  45073. return;
  45074. }
  45075. }
  45076. else {
  45077. condition._evaluationId = currentRenderId;
  45078. if (!condition.isValid()) {
  45079. condition._currentResult = false;
  45080. return;
  45081. }
  45082. condition._currentResult = true;
  45083. }
  45084. }
  45085. this.onBeforeExecuteObservable.notifyObservers(this);
  45086. this._nextActiveAction.execute(evt);
  45087. this.skipToNextActiveAction();
  45088. };
  45089. Action.prototype.execute = function (evt) {
  45090. };
  45091. Action.prototype.skipToNextActiveAction = function () {
  45092. if (this._nextActiveAction._child) {
  45093. if (!this._nextActiveAction._child._actionManager) {
  45094. this._nextActiveAction._child._actionManager = this._actionManager;
  45095. }
  45096. this._nextActiveAction = this._nextActiveAction._child;
  45097. }
  45098. else {
  45099. this._nextActiveAction = this;
  45100. }
  45101. };
  45102. Action.prototype.then = function (action) {
  45103. this._child = action;
  45104. action._actionManager = this._actionManager;
  45105. action._prepare();
  45106. return action;
  45107. };
  45108. Action.prototype._getProperty = function (propertyPath) {
  45109. return this._actionManager._getProperty(propertyPath);
  45110. };
  45111. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  45112. return this._actionManager._getEffectiveTarget(target, propertyPath);
  45113. };
  45114. Action.prototype.serialize = function (parent) {
  45115. };
  45116. // Called by BABYLON.Action objects in serialize(...). Internal use
  45117. Action.prototype._serialize = function (serializedAction, parent) {
  45118. var serializationObject = {
  45119. type: 1,
  45120. children: [],
  45121. name: serializedAction.name,
  45122. properties: serializedAction.properties || []
  45123. };
  45124. // Serialize child
  45125. if (this._child) {
  45126. this._child.serialize(serializationObject);
  45127. }
  45128. // Check if "this" has a condition
  45129. if (this._condition) {
  45130. var serializedCondition = this._condition.serialize();
  45131. serializedCondition.children.push(serializationObject);
  45132. if (parent) {
  45133. parent.children.push(serializedCondition);
  45134. }
  45135. return serializedCondition;
  45136. }
  45137. if (parent) {
  45138. parent.children.push(serializationObject);
  45139. }
  45140. return serializationObject;
  45141. };
  45142. Action._SerializeValueAsString = function (value) {
  45143. if (typeof value === "number") {
  45144. return value.toString();
  45145. }
  45146. if (typeof value === "boolean") {
  45147. return value ? "true" : "false";
  45148. }
  45149. if (value instanceof BABYLON.Vector2) {
  45150. return value.x + ", " + value.y;
  45151. }
  45152. if (value instanceof BABYLON.Vector3) {
  45153. return value.x + ", " + value.y + ", " + value.z;
  45154. }
  45155. if (value instanceof BABYLON.Color3) {
  45156. return value.r + ", " + value.g + ", " + value.b;
  45157. }
  45158. if (value instanceof BABYLON.Color4) {
  45159. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  45160. }
  45161. return value; // string
  45162. };
  45163. Action._GetTargetProperty = function (target) {
  45164. return {
  45165. name: "target",
  45166. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  45167. : target instanceof BABYLON.Light ? "LightProperties"
  45168. : target instanceof BABYLON.Camera ? "CameraProperties"
  45169. : "SceneProperties",
  45170. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  45171. };
  45172. };
  45173. return Action;
  45174. }());
  45175. BABYLON.Action = Action;
  45176. })(BABYLON || (BABYLON = {}));
  45177. //# sourceMappingURL=babylon.action.js.map
  45178. var BABYLON;
  45179. (function (BABYLON) {
  45180. /**
  45181. * ActionEvent is the event beint sent when an action is triggered.
  45182. */
  45183. var ActionEvent = /** @class */ (function () {
  45184. /**
  45185. * @param source The mesh or sprite that triggered the action.
  45186. * @param pointerX The X mouse cursor position at the time of the event
  45187. * @param pointerY The Y mouse cursor position at the time of the event
  45188. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  45189. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  45190. */
  45191. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  45192. this.source = source;
  45193. this.pointerX = pointerX;
  45194. this.pointerY = pointerY;
  45195. this.meshUnderPointer = meshUnderPointer;
  45196. this.sourceEvent = sourceEvent;
  45197. this.additionalData = additionalData;
  45198. }
  45199. /**
  45200. * Helper function to auto-create an ActionEvent from a source mesh.
  45201. * @param source The source mesh that triggered the event
  45202. * @param evt {Event} The original (browser) event
  45203. */
  45204. ActionEvent.CreateNew = function (source, evt, additionalData) {
  45205. var scene = source.getScene();
  45206. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45207. };
  45208. /**
  45209. * Helper function to auto-create an ActionEvent from a source mesh.
  45210. * @param source The source sprite that triggered the event
  45211. * @param scene Scene associated with the sprite
  45212. * @param evt {Event} The original (browser) event
  45213. */
  45214. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  45215. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  45216. };
  45217. /**
  45218. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  45219. * @param scene the scene where the event occurred
  45220. * @param evt {Event} The original (browser) event
  45221. */
  45222. ActionEvent.CreateNewFromScene = function (scene, evt) {
  45223. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  45224. };
  45225. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  45226. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  45227. };
  45228. return ActionEvent;
  45229. }());
  45230. BABYLON.ActionEvent = ActionEvent;
  45231. /**
  45232. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  45233. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  45234. */
  45235. var ActionManager = /** @class */ (function () {
  45236. function ActionManager(scene) {
  45237. // Members
  45238. this.actions = new Array();
  45239. this.hoverCursor = '';
  45240. this._scene = scene;
  45241. scene._actionManagers.push(this);
  45242. }
  45243. Object.defineProperty(ActionManager, "NothingTrigger", {
  45244. get: function () {
  45245. return ActionManager._NothingTrigger;
  45246. },
  45247. enumerable: true,
  45248. configurable: true
  45249. });
  45250. Object.defineProperty(ActionManager, "OnPickTrigger", {
  45251. get: function () {
  45252. return ActionManager._OnPickTrigger;
  45253. },
  45254. enumerable: true,
  45255. configurable: true
  45256. });
  45257. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  45258. get: function () {
  45259. return ActionManager._OnLeftPickTrigger;
  45260. },
  45261. enumerable: true,
  45262. configurable: true
  45263. });
  45264. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  45265. get: function () {
  45266. return ActionManager._OnRightPickTrigger;
  45267. },
  45268. enumerable: true,
  45269. configurable: true
  45270. });
  45271. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  45272. get: function () {
  45273. return ActionManager._OnCenterPickTrigger;
  45274. },
  45275. enumerable: true,
  45276. configurable: true
  45277. });
  45278. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  45279. get: function () {
  45280. return ActionManager._OnPickDownTrigger;
  45281. },
  45282. enumerable: true,
  45283. configurable: true
  45284. });
  45285. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  45286. get: function () {
  45287. return ActionManager._OnDoublePickTrigger;
  45288. },
  45289. enumerable: true,
  45290. configurable: true
  45291. });
  45292. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  45293. get: function () {
  45294. return ActionManager._OnPickUpTrigger;
  45295. },
  45296. enumerable: true,
  45297. configurable: true
  45298. });
  45299. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  45300. /// This trigger will only be raised if you also declared a OnPickDown
  45301. get: function () {
  45302. return ActionManager._OnPickOutTrigger;
  45303. },
  45304. enumerable: true,
  45305. configurable: true
  45306. });
  45307. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  45308. get: function () {
  45309. return ActionManager._OnLongPressTrigger;
  45310. },
  45311. enumerable: true,
  45312. configurable: true
  45313. });
  45314. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  45315. get: function () {
  45316. return ActionManager._OnPointerOverTrigger;
  45317. },
  45318. enumerable: true,
  45319. configurable: true
  45320. });
  45321. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  45322. get: function () {
  45323. return ActionManager._OnPointerOutTrigger;
  45324. },
  45325. enumerable: true,
  45326. configurable: true
  45327. });
  45328. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  45329. get: function () {
  45330. return ActionManager._OnEveryFrameTrigger;
  45331. },
  45332. enumerable: true,
  45333. configurable: true
  45334. });
  45335. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  45336. get: function () {
  45337. return ActionManager._OnIntersectionEnterTrigger;
  45338. },
  45339. enumerable: true,
  45340. configurable: true
  45341. });
  45342. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  45343. get: function () {
  45344. return ActionManager._OnIntersectionExitTrigger;
  45345. },
  45346. enumerable: true,
  45347. configurable: true
  45348. });
  45349. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  45350. get: function () {
  45351. return ActionManager._OnKeyDownTrigger;
  45352. },
  45353. enumerable: true,
  45354. configurable: true
  45355. });
  45356. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  45357. get: function () {
  45358. return ActionManager._OnKeyUpTrigger;
  45359. },
  45360. enumerable: true,
  45361. configurable: true
  45362. });
  45363. // Methods
  45364. ActionManager.prototype.dispose = function () {
  45365. var index = this._scene._actionManagers.indexOf(this);
  45366. for (var i = 0; i < this.actions.length; i++) {
  45367. var action = this.actions[i];
  45368. ActionManager.Triggers[action.trigger]--;
  45369. if (ActionManager.Triggers[action.trigger] === 0) {
  45370. delete ActionManager.Triggers[action.trigger];
  45371. }
  45372. }
  45373. if (index > -1) {
  45374. this._scene._actionManagers.splice(index, 1);
  45375. }
  45376. };
  45377. ActionManager.prototype.getScene = function () {
  45378. return this._scene;
  45379. };
  45380. /**
  45381. * Does this action manager handles actions of any of the given triggers
  45382. * @param {number[]} triggers - the triggers to be tested
  45383. * @return {boolean} whether one (or more) of the triggers is handeled
  45384. */
  45385. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  45386. for (var index = 0; index < this.actions.length; index++) {
  45387. var action = this.actions[index];
  45388. if (triggers.indexOf(action.trigger) > -1) {
  45389. return true;
  45390. }
  45391. }
  45392. return false;
  45393. };
  45394. /**
  45395. * Does this action manager handles actions of a given trigger
  45396. * @param {number} trigger - the trigger to be tested
  45397. * @return {boolean} whether the trigger is handeled
  45398. */
  45399. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  45400. for (var index = 0; index < this.actions.length; index++) {
  45401. var action = this.actions[index];
  45402. if (action.trigger === trigger) {
  45403. return true;
  45404. }
  45405. }
  45406. return false;
  45407. };
  45408. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  45409. /**
  45410. * Does this action manager has pointer triggers
  45411. * @return {boolean} whether or not it has pointer triggers
  45412. */
  45413. get: function () {
  45414. for (var index = 0; index < this.actions.length; index++) {
  45415. var action = this.actions[index];
  45416. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  45417. return true;
  45418. }
  45419. }
  45420. return false;
  45421. },
  45422. enumerable: true,
  45423. configurable: true
  45424. });
  45425. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  45426. /**
  45427. * Does this action manager has pick triggers
  45428. * @return {boolean} whether or not it has pick triggers
  45429. */
  45430. get: function () {
  45431. for (var index = 0; index < this.actions.length; index++) {
  45432. var action = this.actions[index];
  45433. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  45434. return true;
  45435. }
  45436. }
  45437. return false;
  45438. },
  45439. enumerable: true,
  45440. configurable: true
  45441. });
  45442. Object.defineProperty(ActionManager, "HasTriggers", {
  45443. /**
  45444. * Does exist one action manager with at least one trigger
  45445. * @return {boolean} whether or not it exists one action manager with one trigger
  45446. **/
  45447. get: function () {
  45448. for (var t in ActionManager.Triggers) {
  45449. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45450. return true;
  45451. }
  45452. }
  45453. return false;
  45454. },
  45455. enumerable: true,
  45456. configurable: true
  45457. });
  45458. Object.defineProperty(ActionManager, "HasPickTriggers", {
  45459. /**
  45460. * Does exist one action manager with at least one pick trigger
  45461. * @return {boolean} whether or not it exists one action manager with one pick trigger
  45462. **/
  45463. get: function () {
  45464. for (var t in ActionManager.Triggers) {
  45465. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45466. var t_int = parseInt(t);
  45467. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  45468. return true;
  45469. }
  45470. }
  45471. }
  45472. return false;
  45473. },
  45474. enumerable: true,
  45475. configurable: true
  45476. });
  45477. /**
  45478. * Does exist one action manager that handles actions of a given trigger
  45479. * @param {number} trigger - the trigger to be tested
  45480. * @return {boolean} whether the trigger is handeled by at least one action manager
  45481. **/
  45482. ActionManager.HasSpecificTrigger = function (trigger) {
  45483. for (var t in ActionManager.Triggers) {
  45484. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45485. var t_int = parseInt(t);
  45486. if (t_int === trigger) {
  45487. return true;
  45488. }
  45489. }
  45490. }
  45491. return false;
  45492. };
  45493. /**
  45494. * Registers an action to this action manager
  45495. * @param {BABYLON.Action} action - the action to be registered
  45496. * @return {BABYLON.Action} the action amended (prepared) after registration
  45497. */
  45498. ActionManager.prototype.registerAction = function (action) {
  45499. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  45500. if (this.getScene().actionManager !== this) {
  45501. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  45502. return null;
  45503. }
  45504. }
  45505. this.actions.push(action);
  45506. if (ActionManager.Triggers[action.trigger]) {
  45507. ActionManager.Triggers[action.trigger]++;
  45508. }
  45509. else {
  45510. ActionManager.Triggers[action.trigger] = 1;
  45511. }
  45512. action._actionManager = this;
  45513. action._prepare();
  45514. return action;
  45515. };
  45516. /**
  45517. * Unregisters an action to this action manager
  45518. * @param action The action to be unregistered
  45519. * @return whether the action has been unregistered
  45520. */
  45521. ActionManager.prototype.unregisterAction = function (action) {
  45522. var index = this.actions.indexOf(action);
  45523. if (index !== -1) {
  45524. this.actions.splice(index, 1);
  45525. ActionManager.Triggers[action.trigger] -= 1;
  45526. if (ActionManager.Triggers[action.trigger] === 0) {
  45527. delete ActionManager.Triggers[action.trigger];
  45528. }
  45529. delete action._actionManager;
  45530. return true;
  45531. }
  45532. return false;
  45533. };
  45534. /**
  45535. * Process a specific trigger
  45536. * @param {number} trigger - the trigger to process
  45537. * @param evt {BABYLON.ActionEvent} the event details to be processed
  45538. */
  45539. ActionManager.prototype.processTrigger = function (trigger, evt) {
  45540. for (var index = 0; index < this.actions.length; index++) {
  45541. var action = this.actions[index];
  45542. if (action.trigger === trigger) {
  45543. if (evt) {
  45544. if (trigger === ActionManager.OnKeyUpTrigger
  45545. || trigger === ActionManager.OnKeyDownTrigger) {
  45546. var parameter = action.getTriggerParameter();
  45547. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  45548. if (!parameter.toLowerCase) {
  45549. continue;
  45550. }
  45551. var lowerCase = parameter.toLowerCase();
  45552. if (lowerCase !== evt.sourceEvent.key) {
  45553. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  45554. var actualkey = String.fromCharCode(unicode).toLowerCase();
  45555. if (actualkey !== lowerCase) {
  45556. continue;
  45557. }
  45558. }
  45559. }
  45560. }
  45561. }
  45562. action._executeCurrent(evt);
  45563. }
  45564. }
  45565. };
  45566. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  45567. var properties = propertyPath.split(".");
  45568. for (var index = 0; index < properties.length - 1; index++) {
  45569. target = target[properties[index]];
  45570. }
  45571. return target;
  45572. };
  45573. ActionManager.prototype._getProperty = function (propertyPath) {
  45574. var properties = propertyPath.split(".");
  45575. return properties[properties.length - 1];
  45576. };
  45577. ActionManager.prototype.serialize = function (name) {
  45578. var root = {
  45579. children: new Array(),
  45580. name: name,
  45581. type: 3,
  45582. properties: new Array() // Empty for root but required
  45583. };
  45584. for (var i = 0; i < this.actions.length; i++) {
  45585. var triggerObject = {
  45586. type: 0,
  45587. children: new Array(),
  45588. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  45589. properties: new Array()
  45590. };
  45591. var triggerOptions = this.actions[i].triggerOptions;
  45592. if (triggerOptions && typeof triggerOptions !== "number") {
  45593. if (triggerOptions.parameter instanceof BABYLON.Node) {
  45594. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  45595. }
  45596. else {
  45597. var parameter = {};
  45598. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  45599. if (triggerOptions.parameter.mesh) {
  45600. parameter._meshId = triggerOptions.parameter.mesh.id;
  45601. }
  45602. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  45603. }
  45604. }
  45605. // Serialize child action, recursively
  45606. this.actions[i].serialize(triggerObject);
  45607. // Add serialized trigger
  45608. root.children.push(triggerObject);
  45609. }
  45610. return root;
  45611. };
  45612. ActionManager.Parse = function (parsedActions, object, scene) {
  45613. var actionManager = new ActionManager(scene);
  45614. if (object === null)
  45615. scene.actionManager = actionManager;
  45616. else
  45617. object.actionManager = actionManager;
  45618. // instanciate a new object
  45619. var instanciate = function (name, params) {
  45620. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  45621. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  45622. newInstance.constructor.apply(newInstance, params);
  45623. return newInstance;
  45624. };
  45625. var parseParameter = function (name, value, target, propertyPath) {
  45626. if (propertyPath === null) {
  45627. // String, boolean or float
  45628. var floatValue = parseFloat(value);
  45629. if (value === "true" || value === "false")
  45630. return value === "true";
  45631. else
  45632. return isNaN(floatValue) ? value : floatValue;
  45633. }
  45634. var effectiveTarget = propertyPath.split(".");
  45635. var values = value.split(",");
  45636. // Get effective Target
  45637. for (var i = 0; i < effectiveTarget.length; i++) {
  45638. target = target[effectiveTarget[i]];
  45639. }
  45640. // Return appropriate value with its type
  45641. if (typeof (target) === "boolean")
  45642. return values[0] === "true";
  45643. if (typeof (target) === "string")
  45644. return values[0];
  45645. // Parameters with multiple values such as Vector3 etc.
  45646. var split = new Array();
  45647. for (var i = 0; i < values.length; i++)
  45648. split.push(parseFloat(values[i]));
  45649. if (target instanceof BABYLON.Vector3)
  45650. return BABYLON.Vector3.FromArray(split);
  45651. if (target instanceof BABYLON.Vector4)
  45652. return BABYLON.Vector4.FromArray(split);
  45653. if (target instanceof BABYLON.Color3)
  45654. return BABYLON.Color3.FromArray(split);
  45655. if (target instanceof BABYLON.Color4)
  45656. return BABYLON.Color4.FromArray(split);
  45657. return parseFloat(values[0]);
  45658. };
  45659. // traverse graph per trigger
  45660. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  45661. if (combineArray === void 0) { combineArray = null; }
  45662. if (parsedAction.detached)
  45663. return;
  45664. var parameters = new Array();
  45665. var target = null;
  45666. var propertyPath = null;
  45667. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  45668. // Parameters
  45669. if (parsedAction.type === 2)
  45670. parameters.push(actionManager);
  45671. else
  45672. parameters.push(trigger);
  45673. if (combine) {
  45674. var actions = new Array();
  45675. for (var j = 0; j < parsedAction.combine.length; j++) {
  45676. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  45677. }
  45678. parameters.push(actions);
  45679. }
  45680. else {
  45681. for (var i = 0; i < parsedAction.properties.length; i++) {
  45682. var value = parsedAction.properties[i].value;
  45683. var name = parsedAction.properties[i].name;
  45684. var targetType = parsedAction.properties[i].targetType;
  45685. if (name === "target")
  45686. if (targetType !== null && targetType === "SceneProperties")
  45687. value = target = scene;
  45688. else
  45689. value = target = scene.getNodeByName(value);
  45690. else if (name === "parent")
  45691. value = scene.getNodeByName(value);
  45692. else if (name === "sound")
  45693. value = scene.getSoundByName(value);
  45694. else if (name !== "propertyPath") {
  45695. if (parsedAction.type === 2 && name === "operator")
  45696. value = BABYLON.ValueCondition[value];
  45697. else
  45698. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  45699. }
  45700. else {
  45701. propertyPath = value;
  45702. }
  45703. parameters.push(value);
  45704. }
  45705. }
  45706. if (combineArray === null) {
  45707. parameters.push(condition);
  45708. }
  45709. else {
  45710. parameters.push(null);
  45711. }
  45712. // If interpolate value action
  45713. if (parsedAction.name === "InterpolateValueAction") {
  45714. var param = parameters[parameters.length - 2];
  45715. parameters[parameters.length - 1] = param;
  45716. parameters[parameters.length - 2] = condition;
  45717. }
  45718. // Action or condition(s) and not CombineAction
  45719. var newAction = instanciate(parsedAction.name, parameters);
  45720. if (newAction instanceof BABYLON.Condition && condition !== null) {
  45721. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  45722. if (action)
  45723. action.then(nothing);
  45724. else
  45725. actionManager.registerAction(nothing);
  45726. action = nothing;
  45727. }
  45728. if (combineArray === null) {
  45729. if (newAction instanceof BABYLON.Condition) {
  45730. condition = newAction;
  45731. newAction = action;
  45732. }
  45733. else {
  45734. condition = null;
  45735. if (action)
  45736. action.then(newAction);
  45737. else
  45738. actionManager.registerAction(newAction);
  45739. }
  45740. }
  45741. else {
  45742. combineArray.push(newAction);
  45743. }
  45744. for (var i = 0; i < parsedAction.children.length; i++)
  45745. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  45746. };
  45747. // triggers
  45748. for (var i = 0; i < parsedActions.children.length; i++) {
  45749. var triggerParams;
  45750. var trigger = parsedActions.children[i];
  45751. if (trigger.properties.length > 0) {
  45752. var param = trigger.properties[0].value;
  45753. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  45754. if (value._meshId) {
  45755. value.mesh = scene.getMeshByID(value._meshId);
  45756. }
  45757. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  45758. }
  45759. else
  45760. triggerParams = ActionManager[trigger.name];
  45761. for (var j = 0; j < trigger.children.length; j++) {
  45762. if (!trigger.detached)
  45763. traverse(trigger.children[j], triggerParams, null, null);
  45764. }
  45765. }
  45766. };
  45767. ActionManager.GetTriggerName = function (trigger) {
  45768. switch (trigger) {
  45769. case 0: return "NothingTrigger";
  45770. case 1: return "OnPickTrigger";
  45771. case 2: return "OnLeftPickTrigger";
  45772. case 3: return "OnRightPickTrigger";
  45773. case 4: return "OnCenterPickTrigger";
  45774. case 5: return "OnPickDownTrigger";
  45775. case 6: return "OnPickUpTrigger";
  45776. case 7: return "OnLongPressTrigger";
  45777. case 8: return "OnPointerOverTrigger";
  45778. case 9: return "OnPointerOutTrigger";
  45779. case 10: return "OnEveryFrameTrigger";
  45780. case 11: return "OnIntersectionEnterTrigger";
  45781. case 12: return "OnIntersectionExitTrigger";
  45782. case 13: return "OnKeyDownTrigger";
  45783. case 14: return "OnKeyUpTrigger";
  45784. case 15: return "OnPickOutTrigger";
  45785. default: return "";
  45786. }
  45787. };
  45788. // Statics
  45789. ActionManager._NothingTrigger = 0;
  45790. ActionManager._OnPickTrigger = 1;
  45791. ActionManager._OnLeftPickTrigger = 2;
  45792. ActionManager._OnRightPickTrigger = 3;
  45793. ActionManager._OnCenterPickTrigger = 4;
  45794. ActionManager._OnPickDownTrigger = 5;
  45795. ActionManager._OnDoublePickTrigger = 6;
  45796. ActionManager._OnPickUpTrigger = 7;
  45797. ActionManager._OnLongPressTrigger = 8;
  45798. ActionManager._OnPointerOverTrigger = 9;
  45799. ActionManager._OnPointerOutTrigger = 10;
  45800. ActionManager._OnEveryFrameTrigger = 11;
  45801. ActionManager._OnIntersectionEnterTrigger = 12;
  45802. ActionManager._OnIntersectionExitTrigger = 13;
  45803. ActionManager._OnKeyDownTrigger = 14;
  45804. ActionManager._OnKeyUpTrigger = 15;
  45805. ActionManager._OnPickOutTrigger = 16;
  45806. ActionManager.Triggers = {};
  45807. return ActionManager;
  45808. }());
  45809. BABYLON.ActionManager = ActionManager;
  45810. })(BABYLON || (BABYLON = {}));
  45811. //# sourceMappingURL=babylon.actionManager.js.map
  45812. var BABYLON;
  45813. (function (BABYLON) {
  45814. var InterpolateValueAction = /** @class */ (function (_super) {
  45815. __extends(InterpolateValueAction, _super);
  45816. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  45817. if (duration === void 0) { duration = 1000; }
  45818. var _this = _super.call(this, triggerOptions, condition) || this;
  45819. _this.propertyPath = propertyPath;
  45820. _this.value = value;
  45821. _this.duration = duration;
  45822. _this.stopOtherAnimations = stopOtherAnimations;
  45823. _this.onInterpolationDone = onInterpolationDone;
  45824. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  45825. _this._target = _this._effectiveTarget = target;
  45826. return _this;
  45827. }
  45828. InterpolateValueAction.prototype._prepare = function () {
  45829. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45830. this._property = this._getProperty(this.propertyPath);
  45831. };
  45832. InterpolateValueAction.prototype.execute = function () {
  45833. var _this = this;
  45834. var scene = this._actionManager.getScene();
  45835. var keys = [
  45836. {
  45837. frame: 0,
  45838. value: this._effectiveTarget[this._property]
  45839. }, {
  45840. frame: 100,
  45841. value: this.value
  45842. }
  45843. ];
  45844. var dataType;
  45845. if (typeof this.value === "number") {
  45846. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  45847. }
  45848. else if (this.value instanceof BABYLON.Color3) {
  45849. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  45850. }
  45851. else if (this.value instanceof BABYLON.Vector3) {
  45852. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  45853. }
  45854. else if (this.value instanceof BABYLON.Matrix) {
  45855. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  45856. }
  45857. else if (this.value instanceof BABYLON.Quaternion) {
  45858. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  45859. }
  45860. else {
  45861. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  45862. return;
  45863. }
  45864. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  45865. animation.setKeys(keys);
  45866. if (this.stopOtherAnimations) {
  45867. scene.stopAnimation(this._effectiveTarget);
  45868. }
  45869. var wrapper = function () {
  45870. _this.onInterpolationDoneObservable.notifyObservers(_this);
  45871. if (_this.onInterpolationDone) {
  45872. _this.onInterpolationDone();
  45873. }
  45874. };
  45875. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  45876. };
  45877. InterpolateValueAction.prototype.serialize = function (parent) {
  45878. return _super.prototype._serialize.call(this, {
  45879. name: "InterpolateValueAction",
  45880. properties: [
  45881. BABYLON.Action._GetTargetProperty(this._target),
  45882. { name: "propertyPath", value: this.propertyPath },
  45883. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45884. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  45885. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  45886. ]
  45887. }, parent);
  45888. };
  45889. return InterpolateValueAction;
  45890. }(BABYLON.Action));
  45891. BABYLON.InterpolateValueAction = InterpolateValueAction;
  45892. })(BABYLON || (BABYLON = {}));
  45893. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  45894. var BABYLON;
  45895. (function (BABYLON) {
  45896. var SwitchBooleanAction = /** @class */ (function (_super) {
  45897. __extends(SwitchBooleanAction, _super);
  45898. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  45899. var _this = _super.call(this, triggerOptions, condition) || this;
  45900. _this.propertyPath = propertyPath;
  45901. _this._target = _this._effectiveTarget = target;
  45902. return _this;
  45903. }
  45904. SwitchBooleanAction.prototype._prepare = function () {
  45905. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45906. this._property = this._getProperty(this.propertyPath);
  45907. };
  45908. SwitchBooleanAction.prototype.execute = function () {
  45909. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  45910. };
  45911. SwitchBooleanAction.prototype.serialize = function (parent) {
  45912. return _super.prototype._serialize.call(this, {
  45913. name: "SwitchBooleanAction",
  45914. properties: [
  45915. BABYLON.Action._GetTargetProperty(this._target),
  45916. { name: "propertyPath", value: this.propertyPath }
  45917. ]
  45918. }, parent);
  45919. };
  45920. return SwitchBooleanAction;
  45921. }(BABYLON.Action));
  45922. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  45923. var SetStateAction = /** @class */ (function (_super) {
  45924. __extends(SetStateAction, _super);
  45925. function SetStateAction(triggerOptions, target, value, condition) {
  45926. var _this = _super.call(this, triggerOptions, condition) || this;
  45927. _this.value = value;
  45928. _this._target = target;
  45929. return _this;
  45930. }
  45931. SetStateAction.prototype.execute = function () {
  45932. this._target.state = this.value;
  45933. };
  45934. SetStateAction.prototype.serialize = function (parent) {
  45935. return _super.prototype._serialize.call(this, {
  45936. name: "SetStateAction",
  45937. properties: [
  45938. BABYLON.Action._GetTargetProperty(this._target),
  45939. { name: "value", value: this.value }
  45940. ]
  45941. }, parent);
  45942. };
  45943. return SetStateAction;
  45944. }(BABYLON.Action));
  45945. BABYLON.SetStateAction = SetStateAction;
  45946. var SetValueAction = /** @class */ (function (_super) {
  45947. __extends(SetValueAction, _super);
  45948. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  45949. var _this = _super.call(this, triggerOptions, condition) || this;
  45950. _this.propertyPath = propertyPath;
  45951. _this.value = value;
  45952. _this._target = _this._effectiveTarget = target;
  45953. return _this;
  45954. }
  45955. SetValueAction.prototype._prepare = function () {
  45956. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45957. this._property = this._getProperty(this.propertyPath);
  45958. };
  45959. SetValueAction.prototype.execute = function () {
  45960. this._effectiveTarget[this._property] = this.value;
  45961. if (this._target.markAsDirty) {
  45962. this._target.markAsDirty(this._property);
  45963. }
  45964. };
  45965. SetValueAction.prototype.serialize = function (parent) {
  45966. return _super.prototype._serialize.call(this, {
  45967. name: "SetValueAction",
  45968. properties: [
  45969. BABYLON.Action._GetTargetProperty(this._target),
  45970. { name: "propertyPath", value: this.propertyPath },
  45971. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45972. ]
  45973. }, parent);
  45974. };
  45975. return SetValueAction;
  45976. }(BABYLON.Action));
  45977. BABYLON.SetValueAction = SetValueAction;
  45978. var IncrementValueAction = /** @class */ (function (_super) {
  45979. __extends(IncrementValueAction, _super);
  45980. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  45981. var _this = _super.call(this, triggerOptions, condition) || this;
  45982. _this.propertyPath = propertyPath;
  45983. _this.value = value;
  45984. _this._target = _this._effectiveTarget = target;
  45985. return _this;
  45986. }
  45987. IncrementValueAction.prototype._prepare = function () {
  45988. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45989. this._property = this._getProperty(this.propertyPath);
  45990. if (typeof this._effectiveTarget[this._property] !== "number") {
  45991. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  45992. }
  45993. };
  45994. IncrementValueAction.prototype.execute = function () {
  45995. this._effectiveTarget[this._property] += this.value;
  45996. if (this._target.markAsDirty) {
  45997. this._target.markAsDirty(this._property);
  45998. }
  45999. };
  46000. IncrementValueAction.prototype.serialize = function (parent) {
  46001. return _super.prototype._serialize.call(this, {
  46002. name: "IncrementValueAction",
  46003. properties: [
  46004. BABYLON.Action._GetTargetProperty(this._target),
  46005. { name: "propertyPath", value: this.propertyPath },
  46006. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  46007. ]
  46008. }, parent);
  46009. };
  46010. return IncrementValueAction;
  46011. }(BABYLON.Action));
  46012. BABYLON.IncrementValueAction = IncrementValueAction;
  46013. var PlayAnimationAction = /** @class */ (function (_super) {
  46014. __extends(PlayAnimationAction, _super);
  46015. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  46016. var _this = _super.call(this, triggerOptions, condition) || this;
  46017. _this.from = from;
  46018. _this.to = to;
  46019. _this.loop = loop;
  46020. _this._target = target;
  46021. return _this;
  46022. }
  46023. PlayAnimationAction.prototype._prepare = function () {
  46024. };
  46025. PlayAnimationAction.prototype.execute = function () {
  46026. var scene = this._actionManager.getScene();
  46027. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  46028. };
  46029. PlayAnimationAction.prototype.serialize = function (parent) {
  46030. return _super.prototype._serialize.call(this, {
  46031. name: "PlayAnimationAction",
  46032. properties: [
  46033. BABYLON.Action._GetTargetProperty(this._target),
  46034. { name: "from", value: String(this.from) },
  46035. { name: "to", value: String(this.to) },
  46036. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  46037. ]
  46038. }, parent);
  46039. };
  46040. return PlayAnimationAction;
  46041. }(BABYLON.Action));
  46042. BABYLON.PlayAnimationAction = PlayAnimationAction;
  46043. var StopAnimationAction = /** @class */ (function (_super) {
  46044. __extends(StopAnimationAction, _super);
  46045. function StopAnimationAction(triggerOptions, target, condition) {
  46046. var _this = _super.call(this, triggerOptions, condition) || this;
  46047. _this._target = target;
  46048. return _this;
  46049. }
  46050. StopAnimationAction.prototype._prepare = function () {
  46051. };
  46052. StopAnimationAction.prototype.execute = function () {
  46053. var scene = this._actionManager.getScene();
  46054. scene.stopAnimation(this._target);
  46055. };
  46056. StopAnimationAction.prototype.serialize = function (parent) {
  46057. return _super.prototype._serialize.call(this, {
  46058. name: "StopAnimationAction",
  46059. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  46060. }, parent);
  46061. };
  46062. return StopAnimationAction;
  46063. }(BABYLON.Action));
  46064. BABYLON.StopAnimationAction = StopAnimationAction;
  46065. var DoNothingAction = /** @class */ (function (_super) {
  46066. __extends(DoNothingAction, _super);
  46067. function DoNothingAction(triggerOptions, condition) {
  46068. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  46069. return _super.call(this, triggerOptions, condition) || this;
  46070. }
  46071. DoNothingAction.prototype.execute = function () {
  46072. };
  46073. DoNothingAction.prototype.serialize = function (parent) {
  46074. return _super.prototype._serialize.call(this, {
  46075. name: "DoNothingAction",
  46076. properties: []
  46077. }, parent);
  46078. };
  46079. return DoNothingAction;
  46080. }(BABYLON.Action));
  46081. BABYLON.DoNothingAction = DoNothingAction;
  46082. var CombineAction = /** @class */ (function (_super) {
  46083. __extends(CombineAction, _super);
  46084. function CombineAction(triggerOptions, children, condition) {
  46085. var _this = _super.call(this, triggerOptions, condition) || this;
  46086. _this.children = children;
  46087. return _this;
  46088. }
  46089. CombineAction.prototype._prepare = function () {
  46090. for (var index = 0; index < this.children.length; index++) {
  46091. this.children[index]._actionManager = this._actionManager;
  46092. this.children[index]._prepare();
  46093. }
  46094. };
  46095. CombineAction.prototype.execute = function (evt) {
  46096. for (var index = 0; index < this.children.length; index++) {
  46097. this.children[index].execute(evt);
  46098. }
  46099. };
  46100. CombineAction.prototype.serialize = function (parent) {
  46101. var serializationObject = _super.prototype._serialize.call(this, {
  46102. name: "CombineAction",
  46103. properties: [],
  46104. combine: []
  46105. }, parent);
  46106. for (var i = 0; i < this.children.length; i++) {
  46107. serializationObject.combine.push(this.children[i].serialize(null));
  46108. }
  46109. return serializationObject;
  46110. };
  46111. return CombineAction;
  46112. }(BABYLON.Action));
  46113. BABYLON.CombineAction = CombineAction;
  46114. var ExecuteCodeAction = /** @class */ (function (_super) {
  46115. __extends(ExecuteCodeAction, _super);
  46116. function ExecuteCodeAction(triggerOptions, func, condition) {
  46117. var _this = _super.call(this, triggerOptions, condition) || this;
  46118. _this.func = func;
  46119. return _this;
  46120. }
  46121. ExecuteCodeAction.prototype.execute = function (evt) {
  46122. this.func(evt);
  46123. };
  46124. return ExecuteCodeAction;
  46125. }(BABYLON.Action));
  46126. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  46127. var SetParentAction = /** @class */ (function (_super) {
  46128. __extends(SetParentAction, _super);
  46129. function SetParentAction(triggerOptions, target, parent, condition) {
  46130. var _this = _super.call(this, triggerOptions, condition) || this;
  46131. _this._target = target;
  46132. _this._parent = parent;
  46133. return _this;
  46134. }
  46135. SetParentAction.prototype._prepare = function () {
  46136. };
  46137. SetParentAction.prototype.execute = function () {
  46138. if (this._target.parent === this._parent) {
  46139. return;
  46140. }
  46141. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  46142. invertParentWorldMatrix.invert();
  46143. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  46144. this._target.parent = this._parent;
  46145. };
  46146. SetParentAction.prototype.serialize = function (parent) {
  46147. return _super.prototype._serialize.call(this, {
  46148. name: "SetParentAction",
  46149. properties: [
  46150. BABYLON.Action._GetTargetProperty(this._target),
  46151. BABYLON.Action._GetTargetProperty(this._parent),
  46152. ]
  46153. }, parent);
  46154. };
  46155. return SetParentAction;
  46156. }(BABYLON.Action));
  46157. BABYLON.SetParentAction = SetParentAction;
  46158. var PlaySoundAction = /** @class */ (function (_super) {
  46159. __extends(PlaySoundAction, _super);
  46160. function PlaySoundAction(triggerOptions, sound, condition) {
  46161. var _this = _super.call(this, triggerOptions, condition) || this;
  46162. _this._sound = sound;
  46163. return _this;
  46164. }
  46165. PlaySoundAction.prototype._prepare = function () {
  46166. };
  46167. PlaySoundAction.prototype.execute = function () {
  46168. if (this._sound !== undefined)
  46169. this._sound.play();
  46170. };
  46171. PlaySoundAction.prototype.serialize = function (parent) {
  46172. return _super.prototype._serialize.call(this, {
  46173. name: "PlaySoundAction",
  46174. properties: [{ name: "sound", value: this._sound.name }]
  46175. }, parent);
  46176. };
  46177. return PlaySoundAction;
  46178. }(BABYLON.Action));
  46179. BABYLON.PlaySoundAction = PlaySoundAction;
  46180. var StopSoundAction = /** @class */ (function (_super) {
  46181. __extends(StopSoundAction, _super);
  46182. function StopSoundAction(triggerOptions, sound, condition) {
  46183. var _this = _super.call(this, triggerOptions, condition) || this;
  46184. _this._sound = sound;
  46185. return _this;
  46186. }
  46187. StopSoundAction.prototype._prepare = function () {
  46188. };
  46189. StopSoundAction.prototype.execute = function () {
  46190. if (this._sound !== undefined)
  46191. this._sound.stop();
  46192. };
  46193. StopSoundAction.prototype.serialize = function (parent) {
  46194. return _super.prototype._serialize.call(this, {
  46195. name: "StopSoundAction",
  46196. properties: [{ name: "sound", value: this._sound.name }]
  46197. }, parent);
  46198. };
  46199. return StopSoundAction;
  46200. }(BABYLON.Action));
  46201. BABYLON.StopSoundAction = StopSoundAction;
  46202. })(BABYLON || (BABYLON = {}));
  46203. //# sourceMappingURL=babylon.directActions.js.map
  46204. var BABYLON;
  46205. (function (BABYLON) {
  46206. var SpriteManager = /** @class */ (function () {
  46207. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  46208. if (epsilon === void 0) { epsilon = 0.01; }
  46209. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46210. this.name = name;
  46211. this.sprites = new Array();
  46212. this.renderingGroupId = 0;
  46213. this.layerMask = 0x0FFFFFFF;
  46214. this.fogEnabled = true;
  46215. this.isPickable = false;
  46216. /**
  46217. * An event triggered when the manager is disposed.
  46218. * @type {BABYLON.Observable}
  46219. */
  46220. this.onDisposeObservable = new BABYLON.Observable();
  46221. this._vertexBuffers = {};
  46222. this._capacity = capacity;
  46223. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  46224. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46225. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46226. if (cellSize.width && cellSize.height) {
  46227. this.cellWidth = cellSize.width;
  46228. this.cellHeight = cellSize.height;
  46229. }
  46230. else if (cellSize !== undefined) {
  46231. this.cellWidth = cellSize;
  46232. this.cellHeight = cellSize;
  46233. }
  46234. else {
  46235. return;
  46236. }
  46237. this._epsilon = epsilon;
  46238. this._scene = scene;
  46239. this._scene.spriteManagers.push(this);
  46240. var indices = [];
  46241. var index = 0;
  46242. for (var count = 0; count < capacity; count++) {
  46243. indices.push(index);
  46244. indices.push(index + 1);
  46245. indices.push(index + 2);
  46246. indices.push(index);
  46247. indices.push(index + 2);
  46248. indices.push(index + 3);
  46249. index += 4;
  46250. }
  46251. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  46252. // VBO
  46253. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  46254. this._vertexData = new Float32Array(capacity * 16 * 4);
  46255. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  46256. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  46257. var options = this._buffer.createVertexBuffer("options", 4, 4);
  46258. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  46259. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  46260. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  46261. this._vertexBuffers["options"] = options;
  46262. this._vertexBuffers["cellInfo"] = cellInfo;
  46263. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  46264. // Effects
  46265. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  46266. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  46267. }
  46268. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  46269. set: function (callback) {
  46270. if (this._onDisposeObserver) {
  46271. this.onDisposeObservable.remove(this._onDisposeObserver);
  46272. }
  46273. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  46274. },
  46275. enumerable: true,
  46276. configurable: true
  46277. });
  46278. Object.defineProperty(SpriteManager.prototype, "texture", {
  46279. get: function () {
  46280. return this._spriteTexture;
  46281. },
  46282. set: function (value) {
  46283. this._spriteTexture = value;
  46284. },
  46285. enumerable: true,
  46286. configurable: true
  46287. });
  46288. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  46289. var arrayOffset = index * 16;
  46290. if (offsetX === 0)
  46291. offsetX = this._epsilon;
  46292. else if (offsetX === 1)
  46293. offsetX = 1 - this._epsilon;
  46294. if (offsetY === 0)
  46295. offsetY = this._epsilon;
  46296. else if (offsetY === 1)
  46297. offsetY = 1 - this._epsilon;
  46298. this._vertexData[arrayOffset] = sprite.position.x;
  46299. this._vertexData[arrayOffset + 1] = sprite.position.y;
  46300. this._vertexData[arrayOffset + 2] = sprite.position.z;
  46301. this._vertexData[arrayOffset + 3] = sprite.angle;
  46302. this._vertexData[arrayOffset + 4] = sprite.width;
  46303. this._vertexData[arrayOffset + 5] = sprite.height;
  46304. this._vertexData[arrayOffset + 6] = offsetX;
  46305. this._vertexData[arrayOffset + 7] = offsetY;
  46306. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  46307. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  46308. var offset = (sprite.cellIndex / rowSize) >> 0;
  46309. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  46310. this._vertexData[arrayOffset + 11] = offset;
  46311. // Color
  46312. this._vertexData[arrayOffset + 12] = sprite.color.r;
  46313. this._vertexData[arrayOffset + 13] = sprite.color.g;
  46314. this._vertexData[arrayOffset + 14] = sprite.color.b;
  46315. this._vertexData[arrayOffset + 15] = sprite.color.a;
  46316. };
  46317. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  46318. var count = Math.min(this._capacity, this.sprites.length);
  46319. var min = BABYLON.Vector3.Zero();
  46320. var max = BABYLON.Vector3.Zero();
  46321. var distance = Number.MAX_VALUE;
  46322. var currentSprite = null;
  46323. var cameraSpacePosition = BABYLON.Vector3.Zero();
  46324. var cameraView = camera.getViewMatrix();
  46325. for (var index = 0; index < count; index++) {
  46326. var sprite = this.sprites[index];
  46327. if (!sprite) {
  46328. continue;
  46329. }
  46330. if (predicate) {
  46331. if (!predicate(sprite)) {
  46332. continue;
  46333. }
  46334. }
  46335. else if (!sprite.isPickable) {
  46336. continue;
  46337. }
  46338. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  46339. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  46340. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  46341. if (ray.intersectsBoxMinMax(min, max)) {
  46342. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  46343. if (distance > currentDistance) {
  46344. distance = currentDistance;
  46345. currentSprite = sprite;
  46346. if (fastCheck) {
  46347. break;
  46348. }
  46349. }
  46350. }
  46351. }
  46352. if (currentSprite) {
  46353. var result = new BABYLON.PickingInfo();
  46354. result.hit = true;
  46355. result.pickedSprite = currentSprite;
  46356. result.distance = distance;
  46357. return result;
  46358. }
  46359. return null;
  46360. };
  46361. SpriteManager.prototype.render = function () {
  46362. // Check
  46363. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  46364. return;
  46365. var engine = this._scene.getEngine();
  46366. var baseSize = this._spriteTexture.getBaseSize();
  46367. // Sprites
  46368. var deltaTime = engine.getDeltaTime();
  46369. var max = Math.min(this._capacity, this.sprites.length);
  46370. var rowSize = baseSize.width / this.cellWidth;
  46371. var offset = 0;
  46372. for (var index = 0; index < max; index++) {
  46373. var sprite = this.sprites[index];
  46374. if (!sprite) {
  46375. continue;
  46376. }
  46377. sprite._animate(deltaTime);
  46378. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  46379. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  46380. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  46381. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  46382. }
  46383. this._buffer.update(this._vertexData);
  46384. // Render
  46385. var effect = this._effectBase;
  46386. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46387. effect = this._effectFog;
  46388. }
  46389. engine.enableEffect(effect);
  46390. var viewMatrix = this._scene.getViewMatrix();
  46391. effect.setTexture("diffuseSampler", this._spriteTexture);
  46392. effect.setMatrix("view", viewMatrix);
  46393. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46394. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  46395. // Fog
  46396. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46397. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  46398. effect.setColor3("vFogColor", this._scene.fogColor);
  46399. }
  46400. // VBOs
  46401. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46402. // Draw order
  46403. engine.setDepthFunctionToLessOrEqual();
  46404. effect.setBool("alphaTest", true);
  46405. engine.setColorWrite(false);
  46406. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46407. engine.setColorWrite(true);
  46408. effect.setBool("alphaTest", false);
  46409. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46410. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46411. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46412. };
  46413. SpriteManager.prototype.dispose = function () {
  46414. if (this._buffer) {
  46415. this._buffer.dispose();
  46416. this._buffer = null;
  46417. }
  46418. if (this._indexBuffer) {
  46419. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46420. this._indexBuffer = null;
  46421. }
  46422. if (this._spriteTexture) {
  46423. this._spriteTexture.dispose();
  46424. this._spriteTexture = null;
  46425. }
  46426. // Remove from scene
  46427. var index = this._scene.spriteManagers.indexOf(this);
  46428. this._scene.spriteManagers.splice(index, 1);
  46429. // Callback
  46430. this.onDisposeObservable.notifyObservers(this);
  46431. this.onDisposeObservable.clear();
  46432. };
  46433. return SpriteManager;
  46434. }());
  46435. BABYLON.SpriteManager = SpriteManager;
  46436. })(BABYLON || (BABYLON = {}));
  46437. //# sourceMappingURL=babylon.spriteManager.js.map
  46438. var BABYLON;
  46439. (function (BABYLON) {
  46440. var Sprite = /** @class */ (function () {
  46441. function Sprite(name, manager) {
  46442. this.name = name;
  46443. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46444. this.width = 1.0;
  46445. this.height = 1.0;
  46446. this.angle = 0;
  46447. this.cellIndex = 0;
  46448. this.invertU = 0;
  46449. this.invertV = 0;
  46450. this.animations = new Array();
  46451. this.isPickable = false;
  46452. this._animationStarted = false;
  46453. this._loopAnimation = false;
  46454. this._fromIndex = 0;
  46455. this._toIndex = 0;
  46456. this._delay = 0;
  46457. this._direction = 1;
  46458. this._time = 0;
  46459. this._manager = manager;
  46460. this._manager.sprites.push(this);
  46461. this.position = BABYLON.Vector3.Zero();
  46462. }
  46463. Object.defineProperty(Sprite.prototype, "size", {
  46464. get: function () {
  46465. return this.width;
  46466. },
  46467. set: function (value) {
  46468. this.width = value;
  46469. this.height = value;
  46470. },
  46471. enumerable: true,
  46472. configurable: true
  46473. });
  46474. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  46475. this._fromIndex = from;
  46476. this._toIndex = to;
  46477. this._loopAnimation = loop;
  46478. this._delay = delay;
  46479. this._animationStarted = true;
  46480. this._direction = from < to ? 1 : -1;
  46481. this.cellIndex = from;
  46482. this._time = 0;
  46483. this._onAnimationEnd = onAnimationEnd;
  46484. };
  46485. Sprite.prototype.stopAnimation = function () {
  46486. this._animationStarted = false;
  46487. };
  46488. Sprite.prototype._animate = function (deltaTime) {
  46489. if (!this._animationStarted)
  46490. return;
  46491. this._time += deltaTime;
  46492. if (this._time > this._delay) {
  46493. this._time = this._time % this._delay;
  46494. this.cellIndex += this._direction;
  46495. if (this.cellIndex > this._toIndex) {
  46496. if (this._loopAnimation) {
  46497. this.cellIndex = this._fromIndex;
  46498. }
  46499. else {
  46500. this.cellIndex = this._toIndex;
  46501. this._animationStarted = false;
  46502. if (this._onAnimationEnd) {
  46503. this._onAnimationEnd();
  46504. }
  46505. if (this.disposeWhenFinishedAnimating) {
  46506. this.dispose();
  46507. }
  46508. }
  46509. }
  46510. }
  46511. };
  46512. Sprite.prototype.dispose = function () {
  46513. for (var i = 0; i < this._manager.sprites.length; i++) {
  46514. if (this._manager.sprites[i] == this) {
  46515. this._manager.sprites.splice(i, 1);
  46516. }
  46517. }
  46518. };
  46519. return Sprite;
  46520. }());
  46521. BABYLON.Sprite = Sprite;
  46522. })(BABYLON || (BABYLON = {}));
  46523. //# sourceMappingURL=babylon.sprite.js.map
  46524. var BABYLON;
  46525. (function (BABYLON) {
  46526. var IntersectionInfo = /** @class */ (function () {
  46527. function IntersectionInfo(bu, bv, distance) {
  46528. this.bu = bu;
  46529. this.bv = bv;
  46530. this.distance = distance;
  46531. this.faceId = 0;
  46532. this.subMeshId = 0;
  46533. }
  46534. return IntersectionInfo;
  46535. }());
  46536. BABYLON.IntersectionInfo = IntersectionInfo;
  46537. var PickingInfo = /** @class */ (function () {
  46538. function PickingInfo() {
  46539. this.hit = false;
  46540. this.distance = 0;
  46541. this.pickedPoint = null;
  46542. this.pickedMesh = null;
  46543. this.bu = 0;
  46544. this.bv = 0;
  46545. this.faceId = -1;
  46546. this.subMeshId = 0;
  46547. this.pickedSprite = null;
  46548. }
  46549. // Methods
  46550. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  46551. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  46552. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  46553. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  46554. return null;
  46555. }
  46556. var indices = this.pickedMesh.getIndices();
  46557. if (!indices) {
  46558. return null;
  46559. }
  46560. var result;
  46561. if (useVerticesNormals) {
  46562. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46563. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  46564. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  46565. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  46566. normal0 = normal0.scale(this.bu);
  46567. normal1 = normal1.scale(this.bv);
  46568. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  46569. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  46570. }
  46571. else {
  46572. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46573. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  46574. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  46575. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  46576. var p1p2 = vertex1.subtract(vertex2);
  46577. var p3p2 = vertex3.subtract(vertex2);
  46578. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  46579. }
  46580. if (useWorldCoordinates) {
  46581. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  46582. }
  46583. return BABYLON.Vector3.Normalize(result);
  46584. };
  46585. PickingInfo.prototype.getTextureCoordinates = function () {
  46586. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46587. return null;
  46588. }
  46589. var indices = this.pickedMesh.getIndices();
  46590. if (!indices) {
  46591. return null;
  46592. }
  46593. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46594. if (!uvs) {
  46595. return null;
  46596. }
  46597. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  46598. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  46599. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  46600. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  46601. uv1 = uv1.scale(this.bu);
  46602. uv2 = uv2.scale(this.bv);
  46603. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  46604. };
  46605. return PickingInfo;
  46606. }());
  46607. BABYLON.PickingInfo = PickingInfo;
  46608. })(BABYLON || (BABYLON = {}));
  46609. //# sourceMappingURL=babylon.pickingInfo.js.map
  46610. var BABYLON;
  46611. (function (BABYLON) {
  46612. var Ray = /** @class */ (function () {
  46613. function Ray(origin, direction, length) {
  46614. if (length === void 0) { length = Number.MAX_VALUE; }
  46615. this.origin = origin;
  46616. this.direction = direction;
  46617. this.length = length;
  46618. }
  46619. // Methods
  46620. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  46621. var d = 0.0;
  46622. var maxValue = Number.MAX_VALUE;
  46623. var inv;
  46624. var min;
  46625. var max;
  46626. var temp;
  46627. if (Math.abs(this.direction.x) < 0.0000001) {
  46628. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  46629. return false;
  46630. }
  46631. }
  46632. else {
  46633. inv = 1.0 / this.direction.x;
  46634. min = (minimum.x - this.origin.x) * inv;
  46635. max = (maximum.x - this.origin.x) * inv;
  46636. if (max === -Infinity) {
  46637. max = Infinity;
  46638. }
  46639. if (min > max) {
  46640. temp = min;
  46641. min = max;
  46642. max = temp;
  46643. }
  46644. d = Math.max(min, d);
  46645. maxValue = Math.min(max, maxValue);
  46646. if (d > maxValue) {
  46647. return false;
  46648. }
  46649. }
  46650. if (Math.abs(this.direction.y) < 0.0000001) {
  46651. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  46652. return false;
  46653. }
  46654. }
  46655. else {
  46656. inv = 1.0 / this.direction.y;
  46657. min = (minimum.y - this.origin.y) * inv;
  46658. max = (maximum.y - this.origin.y) * inv;
  46659. if (max === -Infinity) {
  46660. max = Infinity;
  46661. }
  46662. if (min > max) {
  46663. temp = min;
  46664. min = max;
  46665. max = temp;
  46666. }
  46667. d = Math.max(min, d);
  46668. maxValue = Math.min(max, maxValue);
  46669. if (d > maxValue) {
  46670. return false;
  46671. }
  46672. }
  46673. if (Math.abs(this.direction.z) < 0.0000001) {
  46674. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  46675. return false;
  46676. }
  46677. }
  46678. else {
  46679. inv = 1.0 / this.direction.z;
  46680. min = (minimum.z - this.origin.z) * inv;
  46681. max = (maximum.z - this.origin.z) * inv;
  46682. if (max === -Infinity) {
  46683. max = Infinity;
  46684. }
  46685. if (min > max) {
  46686. temp = min;
  46687. min = max;
  46688. max = temp;
  46689. }
  46690. d = Math.max(min, d);
  46691. maxValue = Math.min(max, maxValue);
  46692. if (d > maxValue) {
  46693. return false;
  46694. }
  46695. }
  46696. return true;
  46697. };
  46698. Ray.prototype.intersectsBox = function (box) {
  46699. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  46700. };
  46701. Ray.prototype.intersectsSphere = function (sphere) {
  46702. var x = sphere.center.x - this.origin.x;
  46703. var y = sphere.center.y - this.origin.y;
  46704. var z = sphere.center.z - this.origin.z;
  46705. var pyth = (x * x) + (y * y) + (z * z);
  46706. var rr = sphere.radius * sphere.radius;
  46707. if (pyth <= rr) {
  46708. return true;
  46709. }
  46710. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  46711. if (dot < 0.0) {
  46712. return false;
  46713. }
  46714. var temp = pyth - (dot * dot);
  46715. return temp <= rr;
  46716. };
  46717. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  46718. if (!this._edge1) {
  46719. this._edge1 = BABYLON.Vector3.Zero();
  46720. this._edge2 = BABYLON.Vector3.Zero();
  46721. this._pvec = BABYLON.Vector3.Zero();
  46722. this._tvec = BABYLON.Vector3.Zero();
  46723. this._qvec = BABYLON.Vector3.Zero();
  46724. }
  46725. vertex1.subtractToRef(vertex0, this._edge1);
  46726. vertex2.subtractToRef(vertex0, this._edge2);
  46727. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  46728. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  46729. if (det === 0) {
  46730. return null;
  46731. }
  46732. var invdet = 1 / det;
  46733. this.origin.subtractToRef(vertex0, this._tvec);
  46734. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  46735. if (bu < 0 || bu > 1.0) {
  46736. return null;
  46737. }
  46738. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  46739. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  46740. if (bv < 0 || bu + bv > 1.0) {
  46741. return null;
  46742. }
  46743. //check if the distance is longer than the predefined length.
  46744. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  46745. if (distance > this.length) {
  46746. return null;
  46747. }
  46748. return new BABYLON.IntersectionInfo(bu, bv, distance);
  46749. };
  46750. Ray.prototype.intersectsPlane = function (plane) {
  46751. var distance;
  46752. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  46753. if (Math.abs(result1) < 9.99999997475243E-07) {
  46754. return null;
  46755. }
  46756. else {
  46757. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  46758. distance = (-plane.d - result2) / result1;
  46759. if (distance < 0.0) {
  46760. if (distance < -9.99999997475243E-07) {
  46761. return null;
  46762. }
  46763. else {
  46764. return 0;
  46765. }
  46766. }
  46767. return distance;
  46768. }
  46769. };
  46770. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  46771. var tm = BABYLON.Tmp.Matrix[0];
  46772. mesh.getWorldMatrix().invertToRef(tm);
  46773. if (this._tmpRay) {
  46774. Ray.TransformToRef(this, tm, this._tmpRay);
  46775. }
  46776. else {
  46777. this._tmpRay = Ray.Transform(this, tm);
  46778. }
  46779. return mesh.intersects(this._tmpRay, fastCheck);
  46780. };
  46781. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  46782. if (results) {
  46783. results.length = 0;
  46784. }
  46785. else {
  46786. results = [];
  46787. }
  46788. for (var i = 0; i < meshes.length; i++) {
  46789. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  46790. if (pickInfo.hit) {
  46791. results.push(pickInfo);
  46792. }
  46793. }
  46794. results.sort(this._comparePickingInfo);
  46795. return results;
  46796. };
  46797. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  46798. if (pickingInfoA.distance < pickingInfoB.distance) {
  46799. return -1;
  46800. }
  46801. else if (pickingInfoA.distance > pickingInfoB.distance) {
  46802. return 1;
  46803. }
  46804. else {
  46805. return 0;
  46806. }
  46807. };
  46808. /**
  46809. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  46810. * @param sega the first point of the segment to test the intersection against
  46811. * @param segb the second point of the segment to test the intersection against
  46812. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  46813. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  46814. */
  46815. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  46816. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  46817. var u = segb.subtract(sega);
  46818. var v = rsegb.subtract(this.origin);
  46819. var w = sega.subtract(this.origin);
  46820. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  46821. var b = BABYLON.Vector3.Dot(u, v);
  46822. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  46823. var d = BABYLON.Vector3.Dot(u, w);
  46824. var e = BABYLON.Vector3.Dot(v, w);
  46825. var D = a * c - b * b; // always >= 0
  46826. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  46827. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  46828. // compute the line parameters of the two closest points
  46829. if (D < Ray.smallnum) {
  46830. sN = 0.0; // force using point P0 on segment S1
  46831. sD = 1.0; // to prevent possible division by 0.0 later
  46832. tN = e;
  46833. tD = c;
  46834. }
  46835. else {
  46836. sN = (b * e - c * d);
  46837. tN = (a * e - b * d);
  46838. if (sN < 0.0) {
  46839. sN = 0.0;
  46840. tN = e;
  46841. tD = c;
  46842. }
  46843. else if (sN > sD) {
  46844. sN = sD;
  46845. tN = e + b;
  46846. tD = c;
  46847. }
  46848. }
  46849. if (tN < 0.0) {
  46850. tN = 0.0;
  46851. // recompute sc for this edge
  46852. if (-d < 0.0) {
  46853. sN = 0.0;
  46854. }
  46855. else if (-d > a)
  46856. sN = sD;
  46857. else {
  46858. sN = -d;
  46859. sD = a;
  46860. }
  46861. }
  46862. else if (tN > tD) {
  46863. tN = tD;
  46864. // recompute sc for this edge
  46865. if ((-d + b) < 0.0) {
  46866. sN = 0;
  46867. }
  46868. else if ((-d + b) > a) {
  46869. sN = sD;
  46870. }
  46871. else {
  46872. sN = (-d + b);
  46873. sD = a;
  46874. }
  46875. }
  46876. // finally do the division to get sc and tc
  46877. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  46878. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  46879. // get the difference of the two closest points
  46880. var qtc = v.multiplyByFloats(tc, tc, tc);
  46881. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  46882. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  46883. if (isIntersected) {
  46884. return qtc.length();
  46885. }
  46886. return -1;
  46887. };
  46888. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46889. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  46890. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  46891. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  46892. this.direction.normalize();
  46893. return this;
  46894. };
  46895. // Statics
  46896. Ray.Zero = function () {
  46897. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  46898. };
  46899. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46900. var result = Ray.Zero();
  46901. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  46902. };
  46903. /**
  46904. * 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
  46905. * transformed to the given world matrix.
  46906. * @param origin The origin point
  46907. * @param end The end point
  46908. * @param world a matrix to transform the ray to. Default is the identity matrix.
  46909. */
  46910. Ray.CreateNewFromTo = function (origin, end, world) {
  46911. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  46912. var direction = end.subtract(origin);
  46913. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  46914. direction.normalize();
  46915. return Ray.Transform(new Ray(origin, direction, length), world);
  46916. };
  46917. Ray.Transform = function (ray, matrix) {
  46918. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  46919. Ray.TransformToRef(ray, matrix, result);
  46920. return result;
  46921. };
  46922. Ray.TransformToRef = function (ray, matrix, result) {
  46923. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  46924. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  46925. result.length = ray.length;
  46926. var dir = result.direction;
  46927. var len = dir.length();
  46928. if (!(len === 0 || len === 1)) {
  46929. var num = 1.0 / len;
  46930. dir.x *= num;
  46931. dir.y *= num;
  46932. dir.z *= num;
  46933. result.length *= len;
  46934. }
  46935. };
  46936. Ray.smallnum = 0.00000001;
  46937. Ray.rayl = 10e8;
  46938. return Ray;
  46939. }());
  46940. BABYLON.Ray = Ray;
  46941. })(BABYLON || (BABYLON = {}));
  46942. //# sourceMappingURL=babylon.ray.js.map
  46943. var BABYLON;
  46944. (function (BABYLON) {
  46945. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  46946. if (boxMin.x > sphereCenter.x + sphereRadius)
  46947. return false;
  46948. if (sphereCenter.x - sphereRadius > boxMax.x)
  46949. return false;
  46950. if (boxMin.y > sphereCenter.y + sphereRadius)
  46951. return false;
  46952. if (sphereCenter.y - sphereRadius > boxMax.y)
  46953. return false;
  46954. if (boxMin.z > sphereCenter.z + sphereRadius)
  46955. return false;
  46956. if (sphereCenter.z - sphereRadius > boxMax.z)
  46957. return false;
  46958. return true;
  46959. };
  46960. var getLowestRoot = (function () {
  46961. var result = { root: 0, found: false };
  46962. return function (a, b, c, maxR) {
  46963. result.root = 0;
  46964. result.found = false;
  46965. var determinant = b * b - 4.0 * a * c;
  46966. if (determinant < 0)
  46967. return result;
  46968. var sqrtD = Math.sqrt(determinant);
  46969. var r1 = (-b - sqrtD) / (2.0 * a);
  46970. var r2 = (-b + sqrtD) / (2.0 * a);
  46971. if (r1 > r2) {
  46972. var temp = r2;
  46973. r2 = r1;
  46974. r1 = temp;
  46975. }
  46976. if (r1 > 0 && r1 < maxR) {
  46977. result.root = r1;
  46978. result.found = true;
  46979. return result;
  46980. }
  46981. if (r2 > 0 && r2 < maxR) {
  46982. result.root = r2;
  46983. result.found = true;
  46984. return result;
  46985. }
  46986. return result;
  46987. };
  46988. })();
  46989. var Collider = /** @class */ (function () {
  46990. function Collider() {
  46991. this._collisionPoint = BABYLON.Vector3.Zero();
  46992. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  46993. this._tempVector = BABYLON.Vector3.Zero();
  46994. this._tempVector2 = BABYLON.Vector3.Zero();
  46995. this._tempVector3 = BABYLON.Vector3.Zero();
  46996. this._tempVector4 = BABYLON.Vector3.Zero();
  46997. this._edge = BABYLON.Vector3.Zero();
  46998. this._baseToVertex = BABYLON.Vector3.Zero();
  46999. this._destinationPoint = BABYLON.Vector3.Zero();
  47000. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  47001. this._displacementVector = BABYLON.Vector3.Zero();
  47002. this._radius = BABYLON.Vector3.One();
  47003. this._retry = 0;
  47004. this._basePointWorld = BABYLON.Vector3.Zero();
  47005. this._velocityWorld = BABYLON.Vector3.Zero();
  47006. this._normalizedVelocity = BABYLON.Vector3.Zero();
  47007. this._collisionMask = -1;
  47008. }
  47009. Object.defineProperty(Collider.prototype, "collisionMask", {
  47010. get: function () {
  47011. return this._collisionMask;
  47012. },
  47013. set: function (mask) {
  47014. this._collisionMask = !isNaN(mask) ? mask : -1;
  47015. },
  47016. enumerable: true,
  47017. configurable: true
  47018. });
  47019. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  47020. /**
  47021. * Gets the plane normal used to compute the sliding response (in local space)
  47022. */
  47023. get: function () {
  47024. return this._slidePlaneNormal;
  47025. },
  47026. enumerable: true,
  47027. configurable: true
  47028. });
  47029. // Methods
  47030. Collider.prototype._initialize = function (source, dir, e) {
  47031. this._velocity = dir;
  47032. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  47033. this._basePoint = source;
  47034. source.multiplyToRef(this._radius, this._basePointWorld);
  47035. dir.multiplyToRef(this._radius, this._velocityWorld);
  47036. this._velocityWorldLength = this._velocityWorld.length();
  47037. this._epsilon = e;
  47038. this.collisionFound = false;
  47039. };
  47040. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  47041. pa.subtractToRef(point, this._tempVector);
  47042. pb.subtractToRef(point, this._tempVector2);
  47043. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  47044. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47045. if (d < 0)
  47046. return false;
  47047. pc.subtractToRef(point, this._tempVector3);
  47048. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  47049. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47050. if (d < 0)
  47051. return false;
  47052. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  47053. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  47054. return d >= 0;
  47055. };
  47056. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  47057. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  47058. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  47059. if (distance > this._velocityWorldLength + max + sphereRadius) {
  47060. return false;
  47061. }
  47062. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  47063. return false;
  47064. return true;
  47065. };
  47066. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  47067. var t0;
  47068. var embeddedInPlane = false;
  47069. //defensive programming, actually not needed.
  47070. if (!trianglePlaneArray) {
  47071. trianglePlaneArray = [];
  47072. }
  47073. if (!trianglePlaneArray[faceIndex]) {
  47074. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  47075. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  47076. }
  47077. var trianglePlane = trianglePlaneArray[faceIndex];
  47078. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  47079. return;
  47080. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  47081. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  47082. if (normalDotVelocity == 0) {
  47083. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  47084. return;
  47085. embeddedInPlane = true;
  47086. t0 = 0;
  47087. }
  47088. else {
  47089. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47090. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  47091. if (t0 > t1) {
  47092. var temp = t1;
  47093. t1 = t0;
  47094. t0 = temp;
  47095. }
  47096. if (t0 > 1.0 || t1 < 0.0)
  47097. return;
  47098. if (t0 < 0)
  47099. t0 = 0;
  47100. if (t0 > 1.0)
  47101. t0 = 1.0;
  47102. }
  47103. this._collisionPoint.copyFromFloats(0, 0, 0);
  47104. var found = false;
  47105. var t = 1.0;
  47106. if (!embeddedInPlane) {
  47107. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  47108. this._velocity.scaleToRef(t0, this._tempVector);
  47109. this._planeIntersectionPoint.addInPlace(this._tempVector);
  47110. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  47111. found = true;
  47112. t = t0;
  47113. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  47114. }
  47115. }
  47116. if (!found) {
  47117. var velocitySquaredLength = this._velocity.lengthSquared();
  47118. var a = velocitySquaredLength;
  47119. this._basePoint.subtractToRef(p1, this._tempVector);
  47120. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47121. var c = this._tempVector.lengthSquared() - 1.0;
  47122. var lowestRoot = getLowestRoot(a, b, c, t);
  47123. if (lowestRoot.found) {
  47124. t = lowestRoot.root;
  47125. found = true;
  47126. this._collisionPoint.copyFrom(p1);
  47127. }
  47128. this._basePoint.subtractToRef(p2, this._tempVector);
  47129. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47130. c = this._tempVector.lengthSquared() - 1.0;
  47131. lowestRoot = getLowestRoot(a, b, c, t);
  47132. if (lowestRoot.found) {
  47133. t = lowestRoot.root;
  47134. found = true;
  47135. this._collisionPoint.copyFrom(p2);
  47136. }
  47137. this._basePoint.subtractToRef(p3, this._tempVector);
  47138. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  47139. c = this._tempVector.lengthSquared() - 1.0;
  47140. lowestRoot = getLowestRoot(a, b, c, t);
  47141. if (lowestRoot.found) {
  47142. t = lowestRoot.root;
  47143. found = true;
  47144. this._collisionPoint.copyFrom(p3);
  47145. }
  47146. p2.subtractToRef(p1, this._edge);
  47147. p1.subtractToRef(this._basePoint, this._baseToVertex);
  47148. var edgeSquaredLength = this._edge.lengthSquared();
  47149. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47150. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47151. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47152. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47153. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47154. lowestRoot = getLowestRoot(a, b, c, t);
  47155. if (lowestRoot.found) {
  47156. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47157. if (f >= 0.0 && f <= 1.0) {
  47158. t = lowestRoot.root;
  47159. found = true;
  47160. this._edge.scaleInPlace(f);
  47161. p1.addToRef(this._edge, this._collisionPoint);
  47162. }
  47163. }
  47164. p3.subtractToRef(p2, this._edge);
  47165. p2.subtractToRef(this._basePoint, this._baseToVertex);
  47166. edgeSquaredLength = this._edge.lengthSquared();
  47167. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47168. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47169. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47170. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47171. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47172. lowestRoot = getLowestRoot(a, b, c, t);
  47173. if (lowestRoot.found) {
  47174. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47175. if (f >= 0.0 && f <= 1.0) {
  47176. t = lowestRoot.root;
  47177. found = true;
  47178. this._edge.scaleInPlace(f);
  47179. p2.addToRef(this._edge, this._collisionPoint);
  47180. }
  47181. }
  47182. p1.subtractToRef(p3, this._edge);
  47183. p3.subtractToRef(this._basePoint, this._baseToVertex);
  47184. edgeSquaredLength = this._edge.lengthSquared();
  47185. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  47186. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  47187. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  47188. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  47189. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  47190. lowestRoot = getLowestRoot(a, b, c, t);
  47191. if (lowestRoot.found) {
  47192. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  47193. if (f >= 0.0 && f <= 1.0) {
  47194. t = lowestRoot.root;
  47195. found = true;
  47196. this._edge.scaleInPlace(f);
  47197. p3.addToRef(this._edge, this._collisionPoint);
  47198. }
  47199. }
  47200. }
  47201. if (found) {
  47202. var distToCollision = t * this._velocity.length();
  47203. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  47204. if (!this.intersectionPoint) {
  47205. this.intersectionPoint = this._collisionPoint.clone();
  47206. }
  47207. else {
  47208. this.intersectionPoint.copyFrom(this._collisionPoint);
  47209. }
  47210. this._nearestDistance = distToCollision;
  47211. this.collisionFound = true;
  47212. }
  47213. }
  47214. };
  47215. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  47216. for (var i = indexStart; i < indexEnd; i += 3) {
  47217. var p1 = pts[indices[i] - decal];
  47218. var p2 = pts[indices[i + 1] - decal];
  47219. var p3 = pts[indices[i + 2] - decal];
  47220. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  47221. }
  47222. };
  47223. Collider.prototype._getResponse = function (pos, vel) {
  47224. pos.addToRef(vel, this._destinationPoint);
  47225. vel.scaleInPlace((this._nearestDistance / vel.length()));
  47226. this._basePoint.addToRef(vel, pos);
  47227. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  47228. this._slidePlaneNormal.normalize();
  47229. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  47230. pos.addInPlace(this._displacementVector);
  47231. this.intersectionPoint.addInPlace(this._displacementVector);
  47232. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  47233. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  47234. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  47235. };
  47236. return Collider;
  47237. }());
  47238. BABYLON.Collider = Collider;
  47239. })(BABYLON || (BABYLON = {}));
  47240. //# sourceMappingURL=babylon.collider.js.map
  47241. var BABYLON;
  47242. (function (BABYLON) {
  47243. //WebWorker code will be inserted to this variable.
  47244. BABYLON.CollisionWorker = "";
  47245. var WorkerTaskType;
  47246. (function (WorkerTaskType) {
  47247. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  47248. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  47249. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  47250. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  47251. var WorkerReplyType;
  47252. (function (WorkerReplyType) {
  47253. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  47254. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  47255. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  47256. var CollisionCoordinatorWorker = /** @class */ (function () {
  47257. function CollisionCoordinatorWorker() {
  47258. var _this = this;
  47259. this._scaledPosition = BABYLON.Vector3.Zero();
  47260. this._scaledVelocity = BABYLON.Vector3.Zero();
  47261. this.onMeshUpdated = function (transformNode) {
  47262. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  47263. };
  47264. this.onGeometryUpdated = function (geometry) {
  47265. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  47266. };
  47267. this._afterRender = function () {
  47268. if (!_this._init)
  47269. return;
  47270. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  47271. return;
  47272. }
  47273. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  47274. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  47275. if (_this._runningUpdated > 4) {
  47276. return;
  47277. }
  47278. ++_this._runningUpdated;
  47279. var payload = {
  47280. updatedMeshes: _this._addUpdateMeshesList,
  47281. updatedGeometries: _this._addUpdateGeometriesList,
  47282. removedGeometries: _this._toRemoveGeometryArray,
  47283. removedMeshes: _this._toRemoveMeshesArray
  47284. };
  47285. var message = {
  47286. payload: payload,
  47287. taskType: WorkerTaskType.UPDATE
  47288. };
  47289. var serializable = [];
  47290. for (var id in payload.updatedGeometries) {
  47291. if (payload.updatedGeometries.hasOwnProperty(id)) {
  47292. //prepare transferables
  47293. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  47294. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  47295. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  47296. }
  47297. }
  47298. _this._worker.postMessage(message, serializable);
  47299. _this._addUpdateMeshesList = {};
  47300. _this._addUpdateGeometriesList = {};
  47301. _this._toRemoveGeometryArray = [];
  47302. _this._toRemoveMeshesArray = [];
  47303. };
  47304. this._onMessageFromWorker = function (e) {
  47305. var returnData = e.data;
  47306. if (returnData.error != WorkerReplyType.SUCCESS) {
  47307. //TODO what errors can be returned from the worker?
  47308. BABYLON.Tools.Warn("error returned from worker!");
  47309. return;
  47310. }
  47311. switch (returnData.taskType) {
  47312. case WorkerTaskType.INIT:
  47313. _this._init = true;
  47314. //Update the worked with ALL of the scene's current state
  47315. _this._scene.meshes.forEach(function (mesh) {
  47316. _this.onMeshAdded(mesh);
  47317. });
  47318. _this._scene.getGeometries().forEach(function (geometry) {
  47319. _this.onGeometryAdded(geometry);
  47320. });
  47321. break;
  47322. case WorkerTaskType.UPDATE:
  47323. _this._runningUpdated--;
  47324. break;
  47325. case WorkerTaskType.COLLIDE:
  47326. var returnPayload = returnData.payload;
  47327. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  47328. return;
  47329. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  47330. if (callback) {
  47331. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  47332. if (mesh) {
  47333. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  47334. }
  47335. }
  47336. //cleanup
  47337. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  47338. break;
  47339. }
  47340. };
  47341. this._collisionsCallbackArray = [];
  47342. this._init = false;
  47343. this._runningUpdated = 0;
  47344. this._addUpdateMeshesList = {};
  47345. this._addUpdateGeometriesList = {};
  47346. this._toRemoveGeometryArray = [];
  47347. this._toRemoveMeshesArray = [];
  47348. }
  47349. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47350. if (!this._init)
  47351. return;
  47352. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  47353. return;
  47354. position.divideToRef(collider._radius, this._scaledPosition);
  47355. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47356. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  47357. var payload = {
  47358. collider: {
  47359. position: this._scaledPosition.asArray(),
  47360. velocity: this._scaledVelocity.asArray(),
  47361. radius: collider._radius.asArray()
  47362. },
  47363. collisionId: collisionIndex,
  47364. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  47365. maximumRetry: maximumRetry
  47366. };
  47367. var message = {
  47368. payload: payload,
  47369. taskType: WorkerTaskType.COLLIDE
  47370. };
  47371. this._worker.postMessage(message);
  47372. };
  47373. CollisionCoordinatorWorker.prototype.init = function (scene) {
  47374. this._scene = scene;
  47375. this._scene.registerAfterRender(this._afterRender);
  47376. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  47377. this._worker = new Worker(workerUrl);
  47378. this._worker.onmessage = this._onMessageFromWorker;
  47379. var message = {
  47380. payload: {},
  47381. taskType: WorkerTaskType.INIT
  47382. };
  47383. this._worker.postMessage(message);
  47384. };
  47385. CollisionCoordinatorWorker.prototype.destroy = function () {
  47386. this._scene.unregisterAfterRender(this._afterRender);
  47387. this._worker.terminate();
  47388. };
  47389. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  47390. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  47391. this.onMeshUpdated(mesh);
  47392. };
  47393. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  47394. this._toRemoveMeshesArray.push(mesh.uniqueId);
  47395. };
  47396. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  47397. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  47398. geometry.onGeometryUpdated = this.onGeometryUpdated;
  47399. this.onGeometryUpdated(geometry);
  47400. };
  47401. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  47402. this._toRemoveGeometryArray.push(geometry.id);
  47403. };
  47404. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  47405. var submeshes = [];
  47406. if (mesh.subMeshes) {
  47407. submeshes = mesh.subMeshes.map(function (sm, idx) {
  47408. var boundingInfo = sm.getBoundingInfo();
  47409. return {
  47410. position: idx,
  47411. verticesStart: sm.verticesStart,
  47412. verticesCount: sm.verticesCount,
  47413. indexStart: sm.indexStart,
  47414. indexCount: sm.indexCount,
  47415. hasMaterial: !!sm.getMaterial(),
  47416. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47417. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47418. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47419. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  47420. };
  47421. });
  47422. }
  47423. var geometryId = null;
  47424. if (mesh instanceof BABYLON.Mesh) {
  47425. var geometry = mesh.geometry;
  47426. geometryId = geometry ? geometry.id : null;
  47427. }
  47428. else if (mesh instanceof BABYLON.InstancedMesh) {
  47429. var geometry = mesh.sourceMesh.geometry;
  47430. geometryId = geometry ? geometry.id : null;
  47431. }
  47432. var boundingInfo = mesh.getBoundingInfo();
  47433. return {
  47434. uniqueId: mesh.uniqueId,
  47435. id: mesh.id,
  47436. name: mesh.name,
  47437. geometryId: geometryId,
  47438. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47439. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47440. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47441. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  47442. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  47443. subMeshes: submeshes,
  47444. checkCollisions: mesh.checkCollisions
  47445. };
  47446. };
  47447. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  47448. return {
  47449. id: geometry.id,
  47450. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  47451. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  47452. indices: new Uint32Array(geometry.getIndices() || []),
  47453. };
  47454. };
  47455. return CollisionCoordinatorWorker;
  47456. }());
  47457. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  47458. var CollisionCoordinatorLegacy = /** @class */ (function () {
  47459. function CollisionCoordinatorLegacy() {
  47460. this._scaledPosition = BABYLON.Vector3.Zero();
  47461. this._scaledVelocity = BABYLON.Vector3.Zero();
  47462. this._finalPosition = BABYLON.Vector3.Zero();
  47463. }
  47464. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47465. position.divideToRef(collider._radius, this._scaledPosition);
  47466. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47467. collider.collidedMesh = null;
  47468. collider._retry = 0;
  47469. collider._initialVelocity = this._scaledVelocity;
  47470. collider._initialPosition = this._scaledPosition;
  47471. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  47472. this._finalPosition.multiplyInPlace(collider._radius);
  47473. //run the callback
  47474. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  47475. };
  47476. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  47477. this._scene = scene;
  47478. };
  47479. CollisionCoordinatorLegacy.prototype.destroy = function () {
  47480. //Legacy need no destruction method.
  47481. };
  47482. //No update in legacy mode
  47483. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  47484. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  47485. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  47486. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  47487. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  47488. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  47489. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  47490. if (excludedMesh === void 0) { excludedMesh = null; }
  47491. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  47492. if (collider._retry >= maximumRetry) {
  47493. finalPosition.copyFrom(position);
  47494. return;
  47495. }
  47496. // Check if this is a mesh else camera or -1
  47497. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  47498. collider._initialize(position, velocity, closeDistance);
  47499. // Check all meshes
  47500. for (var index = 0; index < this._scene.meshes.length; index++) {
  47501. var mesh = this._scene.meshes[index];
  47502. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  47503. mesh._checkCollision(collider);
  47504. }
  47505. }
  47506. if (!collider.collisionFound) {
  47507. position.addToRef(velocity, finalPosition);
  47508. return;
  47509. }
  47510. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  47511. collider._getResponse(position, velocity);
  47512. }
  47513. if (velocity.length() <= closeDistance) {
  47514. finalPosition.copyFrom(position);
  47515. return;
  47516. }
  47517. collider._retry++;
  47518. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  47519. };
  47520. return CollisionCoordinatorLegacy;
  47521. }());
  47522. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  47523. })(BABYLON || (BABYLON = {}));
  47524. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  47525. var BABYLON;
  47526. (function (BABYLON) {
  47527. /**
  47528. * A particle represents one of the element emitted by a particle system.
  47529. * This is mainly define by its coordinates, direction, velocity and age.
  47530. */
  47531. var Particle = /** @class */ (function () {
  47532. /**
  47533. * Creates a new instance of @see Particle
  47534. * @param particleSystem the particle system the particle belongs to
  47535. */
  47536. function Particle(particleSystem) {
  47537. this.particleSystem = particleSystem;
  47538. /**
  47539. * The world position of the particle in the scene.
  47540. */
  47541. this.position = BABYLON.Vector3.Zero();
  47542. /**
  47543. * The world direction of the particle in the scene.
  47544. */
  47545. this.direction = BABYLON.Vector3.Zero();
  47546. /**
  47547. * The color of the particle.
  47548. */
  47549. this.color = new BABYLON.Color4(0, 0, 0, 0);
  47550. /**
  47551. * The color change of the particle per step.
  47552. */
  47553. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  47554. /**
  47555. * Defines how long will the life of the particle be.
  47556. */
  47557. this.lifeTime = 1.0;
  47558. /**
  47559. * The current age of the particle.
  47560. */
  47561. this.age = 0;
  47562. /**
  47563. * The current size of the particle.
  47564. */
  47565. this.size = 0;
  47566. /**
  47567. * The current angle of the particle.
  47568. */
  47569. this.angle = 0;
  47570. /**
  47571. * Defines how fast is the angle changing.
  47572. */
  47573. this.angularSpeed = 0;
  47574. /**
  47575. * Defines the cell index used by the particle to be rendered from a sprite.
  47576. */
  47577. this.cellIndex = 0;
  47578. this._currentFrameCounter = 0;
  47579. if (!this.particleSystem.isAnimationSheetEnabled) {
  47580. return;
  47581. }
  47582. this.cellIndex = this.particleSystem.startSpriteCellID;
  47583. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  47584. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  47585. }
  47586. else {
  47587. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  47588. }
  47589. }
  47590. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  47591. // (ageOffset / scaledUpdateSpeed) / available cells
  47592. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  47593. this._currentFrameCounter += scaledUpdateSpeed;
  47594. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  47595. this._currentFrameCounter = 0;
  47596. this.cellIndex++;
  47597. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  47598. this.cellIndex = this.particleSystem.endSpriteCellID;
  47599. }
  47600. }
  47601. };
  47602. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  47603. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  47604. this.cellIndex++;
  47605. this._currentFrameCounter = 0;
  47606. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  47607. if (this.particleSystem.spriteCellLoop) {
  47608. this.cellIndex = this.particleSystem.startSpriteCellID;
  47609. }
  47610. else {
  47611. this.cellIndex = this.particleSystem.endSpriteCellID;
  47612. }
  47613. }
  47614. }
  47615. else {
  47616. this._currentFrameCounter++;
  47617. }
  47618. };
  47619. /**
  47620. * Copy the properties of particle to another one.
  47621. * @param other the particle to copy the information to.
  47622. */
  47623. Particle.prototype.copyTo = function (other) {
  47624. other.position.copyFrom(this.position);
  47625. other.direction.copyFrom(this.direction);
  47626. other.color.copyFrom(this.color);
  47627. other.colorStep.copyFrom(this.colorStep);
  47628. other.lifeTime = this.lifeTime;
  47629. other.age = this.age;
  47630. other.size = this.size;
  47631. other.angle = this.angle;
  47632. other.angularSpeed = this.angularSpeed;
  47633. other.particleSystem = this.particleSystem;
  47634. other.cellIndex = this.cellIndex;
  47635. };
  47636. return Particle;
  47637. }());
  47638. BABYLON.Particle = Particle;
  47639. })(BABYLON || (BABYLON = {}));
  47640. //# sourceMappingURL=babylon.particle.js.map
  47641. var BABYLON;
  47642. (function (BABYLON) {
  47643. /**
  47644. * This represents a particle system in Babylon.
  47645. * 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.
  47646. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  47647. * @example https://doc.babylonjs.com/babylon101/particles
  47648. */
  47649. var ParticleSystem = /** @class */ (function () {
  47650. /**
  47651. * Instantiates a particle system.
  47652. * 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.
  47653. * @param name The name of the particle system
  47654. * @param capacity The max number of particles alive at the same time
  47655. * @param scene The scene the particle system belongs to
  47656. * @param customEffect a custom effect used to change the way particles are rendered by default
  47657. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  47658. * @param epsilon Offset used to render the particles
  47659. */
  47660. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  47661. if (customEffect === void 0) { customEffect = null; }
  47662. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  47663. if (epsilon === void 0) { epsilon = 0.01; }
  47664. var _this = this;
  47665. /**
  47666. * List of animations used by the particle system.
  47667. */
  47668. this.animations = [];
  47669. /**
  47670. * The rendering group used by the Particle system to chose when to render.
  47671. */
  47672. this.renderingGroupId = 0;
  47673. /**
  47674. * The emitter represents the Mesh or position we are attaching the particle system to.
  47675. */
  47676. this.emitter = null;
  47677. /**
  47678. * The density of particles, the rate of particle flow
  47679. */
  47680. this.emitRate = 10;
  47681. /**
  47682. * If you want to launch only a few particles at once, that can be done, as well.
  47683. */
  47684. this.manualEmitCount = -1;
  47685. /**
  47686. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  47687. */
  47688. this.updateSpeed = 0.01;
  47689. /**
  47690. * The amount of time the particle system is running (depends of the overall speed above).
  47691. */
  47692. this.targetStopDuration = 0;
  47693. /**
  47694. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  47695. */
  47696. this.disposeOnStop = false;
  47697. /**
  47698. * Minimum power of emitting particles.
  47699. */
  47700. this.minEmitPower = 1;
  47701. /**
  47702. * Maximum power of emitting particles.
  47703. */
  47704. this.maxEmitPower = 1;
  47705. /**
  47706. * Minimum life time of emitting particles.
  47707. */
  47708. this.minLifeTime = 1;
  47709. /**
  47710. * Maximum life time of emitting particles.
  47711. */
  47712. this.maxLifeTime = 1;
  47713. /**
  47714. * Minimum Size of emitting particles.
  47715. */
  47716. this.minSize = 1;
  47717. /**
  47718. * Maximum Size of emitting particles.
  47719. */
  47720. this.maxSize = 1;
  47721. /**
  47722. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  47723. */
  47724. this.minAngularSpeed = 0;
  47725. /**
  47726. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  47727. */
  47728. this.maxAngularSpeed = 0;
  47729. /**
  47730. * The layer mask we are rendering the particles through.
  47731. */
  47732. this.layerMask = 0x0FFFFFFF;
  47733. /**
  47734. * This can help using your own shader to render the particle system.
  47735. * The according effect will be created
  47736. */
  47737. this.customShader = null;
  47738. /**
  47739. * By default particle system starts as soon as they are created. This prevents the
  47740. * automatic start to happen and let you decide when to start emitting particles.
  47741. */
  47742. this.preventAutoStart = false;
  47743. /**
  47744. * Callback triggered when the particle animation is ending.
  47745. */
  47746. this.onAnimationEnd = null;
  47747. /**
  47748. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  47749. */
  47750. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  47751. /**
  47752. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  47753. * to override the particles.
  47754. */
  47755. this.forceDepthWrite = false;
  47756. /**
  47757. * You can use gravity if you want to give an orientation to your particles.
  47758. */
  47759. this.gravity = BABYLON.Vector3.Zero();
  47760. /**
  47761. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47762. */
  47763. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  47764. /**
  47765. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47766. */
  47767. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  47768. /**
  47769. * 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.
  47770. */
  47771. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  47772. /**
  47773. * 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.
  47774. */
  47775. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47776. /**
  47777. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47778. */
  47779. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47780. /**
  47781. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47782. */
  47783. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47784. /**
  47785. * Color the particle will have at the end of its lifetime.
  47786. */
  47787. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  47788. /**
  47789. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  47790. */
  47791. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47792. /**
  47793. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  47794. */
  47795. this.spriteCellLoop = true;
  47796. /**
  47797. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  47798. */
  47799. this.spriteCellChangeSpeed = 0;
  47800. /**
  47801. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  47802. */
  47803. this.startSpriteCellID = 0;
  47804. /**
  47805. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  47806. */
  47807. this.endSpriteCellID = 0;
  47808. /**
  47809. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  47810. */
  47811. this.spriteCellWidth = 0;
  47812. /**
  47813. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  47814. */
  47815. this.spriteCellHeight = 0;
  47816. /**
  47817. * An event triggered when the system is disposed.
  47818. */
  47819. this.onDisposeObservable = new BABYLON.Observable();
  47820. this._particles = new Array();
  47821. this._stockParticles = new Array();
  47822. this._newPartsExcess = 0;
  47823. this._vertexBuffers = {};
  47824. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  47825. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  47826. this._scaledDirection = BABYLON.Vector3.Zero();
  47827. this._scaledGravity = BABYLON.Vector3.Zero();
  47828. this._currentRenderId = -1;
  47829. this._started = false;
  47830. this._stopped = false;
  47831. this._actualFrame = 0;
  47832. this._vertexBufferSize = 11;
  47833. this._appendParticleVertexes = null;
  47834. this.id = name;
  47835. this.name = name;
  47836. this._capacity = capacity;
  47837. this._epsilon = epsilon;
  47838. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  47839. if (isAnimationSheetEnabled) {
  47840. this._vertexBufferSize = 12;
  47841. }
  47842. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47843. this._customEffect = customEffect;
  47844. scene.particleSystems.push(this);
  47845. this._createIndexBuffer();
  47846. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  47847. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  47848. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  47849. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  47850. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  47851. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  47852. if (this._isAnimationSheetEnabled) {
  47853. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  47854. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  47855. }
  47856. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  47857. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  47858. this._vertexBuffers["options"] = options;
  47859. // Default behaviors
  47860. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  47861. this.updateFunction = function (particles) {
  47862. for (var index = 0; index < particles.length; index++) {
  47863. var particle = particles[index];
  47864. particle.age += _this._scaledUpdateSpeed;
  47865. if (particle.age >= particle.lifeTime) {
  47866. _this.recycleParticle(particle);
  47867. index--;
  47868. continue;
  47869. }
  47870. else {
  47871. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  47872. particle.color.addInPlace(_this._scaledColorStep);
  47873. if (particle.color.a < 0)
  47874. particle.color.a = 0;
  47875. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  47876. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  47877. particle.position.addInPlace(_this._scaledDirection);
  47878. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  47879. particle.direction.addInPlace(_this._scaledGravity);
  47880. if (_this._isAnimationSheetEnabled) {
  47881. particle.updateCellIndex(_this._scaledUpdateSpeed);
  47882. }
  47883. }
  47884. }
  47885. };
  47886. }
  47887. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  47888. /**
  47889. * Sets a callback that will be triggered when the system is disposed.
  47890. */
  47891. set: function (callback) {
  47892. if (this._onDisposeObserver) {
  47893. this.onDisposeObservable.remove(this._onDisposeObserver);
  47894. }
  47895. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  47896. },
  47897. enumerable: true,
  47898. configurable: true
  47899. });
  47900. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  47901. /**
  47902. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  47903. */
  47904. get: function () {
  47905. return this._isAnimationSheetEnabled;
  47906. },
  47907. enumerable: true,
  47908. configurable: true
  47909. });
  47910. ParticleSystem.prototype._createIndexBuffer = function () {
  47911. var indices = [];
  47912. var index = 0;
  47913. for (var count = 0; count < this._capacity; count++) {
  47914. indices.push(index);
  47915. indices.push(index + 1);
  47916. indices.push(index + 2);
  47917. indices.push(index);
  47918. indices.push(index + 2);
  47919. indices.push(index + 3);
  47920. index += 4;
  47921. }
  47922. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  47923. };
  47924. /**
  47925. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  47926. * Its lifetime will start back at 0.
  47927. * @param particle The particle to recycle
  47928. */
  47929. ParticleSystem.prototype.recycleParticle = function (particle) {
  47930. var lastParticle = this._particles.pop();
  47931. if (lastParticle !== particle) {
  47932. lastParticle.copyTo(particle);
  47933. this._stockParticles.push(lastParticle);
  47934. }
  47935. };
  47936. /**
  47937. * Gets the maximum number of particles active at the same time.
  47938. * @returns The max number of active particles.
  47939. */
  47940. ParticleSystem.prototype.getCapacity = function () {
  47941. return this._capacity;
  47942. };
  47943. /**
  47944. * Gets Wether there are still active particles in the system.
  47945. * @returns True if it is alive, otherwise false.
  47946. */
  47947. ParticleSystem.prototype.isAlive = function () {
  47948. return this._alive;
  47949. };
  47950. /**
  47951. * Gets Wether the system has been started.
  47952. * @returns True if it has been started, otherwise false.
  47953. */
  47954. ParticleSystem.prototype.isStarted = function () {
  47955. return this._started;
  47956. };
  47957. /**
  47958. * Starts the particle system and begins to emit.
  47959. */
  47960. ParticleSystem.prototype.start = function () {
  47961. this._started = true;
  47962. this._stopped = false;
  47963. this._actualFrame = 0;
  47964. };
  47965. /**
  47966. * Stops the particle system.
  47967. */
  47968. ParticleSystem.prototype.stop = function () {
  47969. this._stopped = true;
  47970. };
  47971. /**
  47972. * @ignore (for internal use only)
  47973. */
  47974. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  47975. var offset = index * this._vertexBufferSize;
  47976. this._vertexData[offset] = particle.position.x;
  47977. this._vertexData[offset + 1] = particle.position.y;
  47978. this._vertexData[offset + 2] = particle.position.z;
  47979. this._vertexData[offset + 3] = particle.color.r;
  47980. this._vertexData[offset + 4] = particle.color.g;
  47981. this._vertexData[offset + 5] = particle.color.b;
  47982. this._vertexData[offset + 6] = particle.color.a;
  47983. this._vertexData[offset + 7] = particle.angle;
  47984. this._vertexData[offset + 8] = particle.size;
  47985. this._vertexData[offset + 9] = offsetX;
  47986. this._vertexData[offset + 10] = offsetY;
  47987. };
  47988. /**
  47989. * @ignore (for internal use only)
  47990. */
  47991. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  47992. if (offsetX === 0)
  47993. offsetX = this._epsilon;
  47994. else if (offsetX === 1)
  47995. offsetX = 1 - this._epsilon;
  47996. if (offsetY === 0)
  47997. offsetY = this._epsilon;
  47998. else if (offsetY === 1)
  47999. offsetY = 1 - this._epsilon;
  48000. var offset = index * this._vertexBufferSize;
  48001. this._vertexData[offset] = particle.position.x;
  48002. this._vertexData[offset + 1] = particle.position.y;
  48003. this._vertexData[offset + 2] = particle.position.z;
  48004. this._vertexData[offset + 3] = particle.color.r;
  48005. this._vertexData[offset + 4] = particle.color.g;
  48006. this._vertexData[offset + 5] = particle.color.b;
  48007. this._vertexData[offset + 6] = particle.color.a;
  48008. this._vertexData[offset + 7] = particle.angle;
  48009. this._vertexData[offset + 8] = particle.size;
  48010. this._vertexData[offset + 9] = offsetX;
  48011. this._vertexData[offset + 10] = offsetY;
  48012. this._vertexData[offset + 11] = particle.cellIndex;
  48013. };
  48014. ParticleSystem.prototype._update = function (newParticles) {
  48015. // Update current
  48016. this._alive = this._particles.length > 0;
  48017. this.updateFunction(this._particles);
  48018. // Add new ones
  48019. var worldMatrix;
  48020. if (this.emitter.position) {
  48021. var emitterMesh = this.emitter;
  48022. worldMatrix = emitterMesh.getWorldMatrix();
  48023. }
  48024. else {
  48025. var emitterPosition = this.emitter;
  48026. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  48027. }
  48028. var particle;
  48029. for (var index = 0; index < newParticles; index++) {
  48030. if (this._particles.length === this._capacity) {
  48031. break;
  48032. }
  48033. if (this._stockParticles.length !== 0) {
  48034. particle = this._stockParticles.pop();
  48035. particle.age = 0;
  48036. particle.cellIndex = this.startSpriteCellID;
  48037. }
  48038. else {
  48039. particle = new BABYLON.Particle(this);
  48040. }
  48041. this._particles.push(particle);
  48042. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  48043. if (this.startPositionFunction) {
  48044. this.startPositionFunction(worldMatrix, particle.position, particle);
  48045. }
  48046. else {
  48047. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  48048. }
  48049. if (this.startDirectionFunction) {
  48050. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48051. }
  48052. else {
  48053. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  48054. }
  48055. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  48056. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  48057. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  48058. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  48059. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  48060. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  48061. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  48062. }
  48063. };
  48064. ParticleSystem.prototype._getEffect = function () {
  48065. if (this._customEffect) {
  48066. return this._customEffect;
  48067. }
  48068. ;
  48069. var defines = [];
  48070. if (this._scene.clipPlane) {
  48071. defines.push("#define CLIPPLANE");
  48072. }
  48073. if (this._isAnimationSheetEnabled) {
  48074. defines.push("#define ANIMATESHEET");
  48075. }
  48076. // Effect
  48077. var join = defines.join("\n");
  48078. if (this._cachedDefines !== join) {
  48079. this._cachedDefines = join;
  48080. var attributesNamesOrOptions;
  48081. var effectCreationOption;
  48082. if (this._isAnimationSheetEnabled) {
  48083. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  48084. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  48085. }
  48086. else {
  48087. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  48088. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  48089. }
  48090. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  48091. }
  48092. return this._effect;
  48093. };
  48094. /**
  48095. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  48096. */
  48097. ParticleSystem.prototype.animate = function () {
  48098. if (!this._started)
  48099. return;
  48100. var effect = this._getEffect();
  48101. // Check
  48102. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  48103. return;
  48104. if (this._currentRenderId === this._scene.getRenderId()) {
  48105. return;
  48106. }
  48107. this._currentRenderId = this._scene.getRenderId();
  48108. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  48109. // determine the number of particles we need to create
  48110. var newParticles;
  48111. if (this.manualEmitCount > -1) {
  48112. newParticles = this.manualEmitCount;
  48113. this._newPartsExcess = 0;
  48114. this.manualEmitCount = 0;
  48115. }
  48116. else {
  48117. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  48118. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  48119. }
  48120. if (this._newPartsExcess > 1.0) {
  48121. newParticles += this._newPartsExcess >> 0;
  48122. this._newPartsExcess -= this._newPartsExcess >> 0;
  48123. }
  48124. this._alive = false;
  48125. if (!this._stopped) {
  48126. this._actualFrame += this._scaledUpdateSpeed;
  48127. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  48128. this.stop();
  48129. }
  48130. else {
  48131. newParticles = 0;
  48132. }
  48133. this._update(newParticles);
  48134. // Stopped?
  48135. if (this._stopped) {
  48136. if (!this._alive) {
  48137. this._started = false;
  48138. if (this.onAnimationEnd) {
  48139. this.onAnimationEnd();
  48140. }
  48141. if (this.disposeOnStop) {
  48142. this._scene._toBeDisposed.push(this);
  48143. }
  48144. }
  48145. }
  48146. // Animation sheet
  48147. if (this._isAnimationSheetEnabled) {
  48148. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  48149. }
  48150. else {
  48151. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  48152. }
  48153. // Update VBO
  48154. var offset = 0;
  48155. for (var index = 0; index < this._particles.length; index++) {
  48156. var particle = this._particles[index];
  48157. this._appendParticleVertexes(offset, particle);
  48158. offset += 4;
  48159. }
  48160. if (this._vertexBuffer) {
  48161. this._vertexBuffer.update(this._vertexData);
  48162. }
  48163. };
  48164. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  48165. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  48166. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  48167. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  48168. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  48169. };
  48170. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  48171. this._appendParticleVertex(offset++, particle, 0, 0);
  48172. this._appendParticleVertex(offset++, particle, 1, 0);
  48173. this._appendParticleVertex(offset++, particle, 1, 1);
  48174. this._appendParticleVertex(offset++, particle, 0, 1);
  48175. };
  48176. /**
  48177. * Rebuilds the particle system.
  48178. */
  48179. ParticleSystem.prototype.rebuild = function () {
  48180. this._createIndexBuffer();
  48181. if (this._vertexBuffer) {
  48182. this._vertexBuffer._rebuild();
  48183. }
  48184. };
  48185. /**
  48186. * Renders the particle system in its current state.
  48187. * @returns the current number of particles.
  48188. */
  48189. ParticleSystem.prototype.render = function () {
  48190. var effect = this._getEffect();
  48191. // Check
  48192. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  48193. return 0;
  48194. var engine = this._scene.getEngine();
  48195. // Render
  48196. engine.enableEffect(effect);
  48197. engine.setState(false);
  48198. var viewMatrix = this._scene.getViewMatrix();
  48199. effect.setTexture("diffuseSampler", this.particleTexture);
  48200. effect.setMatrix("view", viewMatrix);
  48201. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48202. if (this._isAnimationSheetEnabled) {
  48203. var baseSize = this.particleTexture.getBaseSize();
  48204. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  48205. }
  48206. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  48207. if (this._scene.clipPlane) {
  48208. var clipPlane = this._scene.clipPlane;
  48209. var invView = viewMatrix.clone();
  48210. invView.invert();
  48211. effect.setMatrix("invView", invView);
  48212. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  48213. }
  48214. // VBOs
  48215. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48216. // Draw order
  48217. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  48218. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  48219. }
  48220. else {
  48221. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48222. }
  48223. if (this.forceDepthWrite) {
  48224. engine.setDepthWrite(true);
  48225. }
  48226. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  48227. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48228. return this._particles.length;
  48229. };
  48230. /**
  48231. * Disposes the particle system and free the associated resources.
  48232. */
  48233. ParticleSystem.prototype.dispose = function () {
  48234. if (this._vertexBuffer) {
  48235. this._vertexBuffer.dispose();
  48236. this._vertexBuffer = null;
  48237. }
  48238. if (this._indexBuffer) {
  48239. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48240. this._indexBuffer = null;
  48241. }
  48242. if (this.particleTexture) {
  48243. this.particleTexture.dispose();
  48244. this.particleTexture = null;
  48245. }
  48246. // Remove from scene
  48247. var index = this._scene.particleSystems.indexOf(this);
  48248. if (index > -1) {
  48249. this._scene.particleSystems.splice(index, 1);
  48250. }
  48251. // Callback
  48252. this.onDisposeObservable.notifyObservers(this);
  48253. this.onDisposeObservable.clear();
  48254. };
  48255. /**
  48256. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  48257. * @param radius The radius of the sphere to emit from
  48258. * @returns the emitter
  48259. */
  48260. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  48261. if (radius === void 0) { radius = 1; }
  48262. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  48263. this.particleEmitterType = particleEmitter;
  48264. return particleEmitter;
  48265. };
  48266. /**
  48267. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  48268. * @param radius The radius of the sphere to emit from
  48269. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  48270. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  48271. * @returns the emitter
  48272. */
  48273. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  48274. if (radius === void 0) { radius = 1; }
  48275. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  48276. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  48277. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  48278. this.particleEmitterType = particleEmitter;
  48279. return particleEmitter;
  48280. };
  48281. /**
  48282. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  48283. * @param radius The radius of the cone to emit from
  48284. * @param angle The base angle of the cone
  48285. * @returns the emitter
  48286. */
  48287. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  48288. if (radius === void 0) { radius = 1; }
  48289. if (angle === void 0) { angle = Math.PI / 4; }
  48290. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  48291. this.particleEmitterType = particleEmitter;
  48292. return particleEmitter;
  48293. };
  48294. // 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.
  48295. /**
  48296. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  48297. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  48298. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  48299. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48300. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48301. * @returns the emitter
  48302. */
  48303. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  48304. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  48305. this.direction1 = direction1;
  48306. this.direction2 = direction2;
  48307. this.minEmitBox = minEmitBox;
  48308. this.maxEmitBox = maxEmitBox;
  48309. this.particleEmitterType = particleEmitter;
  48310. return particleEmitter;
  48311. };
  48312. /**
  48313. * Clones the particle system.
  48314. * @param name The name of the cloned object
  48315. * @param newEmitter The new emitter to use
  48316. * @returns the cloned particle system
  48317. */
  48318. ParticleSystem.prototype.clone = function (name, newEmitter) {
  48319. var custom = null;
  48320. var program = null;
  48321. if (this.customShader != null) {
  48322. program = this.customShader;
  48323. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48324. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48325. }
  48326. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  48327. result.customShader = program;
  48328. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  48329. if (newEmitter === undefined) {
  48330. newEmitter = this.emitter;
  48331. }
  48332. result.emitter = newEmitter;
  48333. if (this.particleTexture) {
  48334. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  48335. }
  48336. if (!this.preventAutoStart) {
  48337. result.start();
  48338. }
  48339. return result;
  48340. };
  48341. /**
  48342. * Serializes the particle system to a JSON object.
  48343. * @returns the JSON object
  48344. */
  48345. ParticleSystem.prototype.serialize = function () {
  48346. var serializationObject = {};
  48347. serializationObject.name = this.name;
  48348. serializationObject.id = this.id;
  48349. // Emitter
  48350. if (this.emitter.position) {
  48351. var emitterMesh = this.emitter;
  48352. serializationObject.emitterId = emitterMesh.id;
  48353. }
  48354. else {
  48355. var emitterPosition = this.emitter;
  48356. serializationObject.emitter = emitterPosition.asArray();
  48357. }
  48358. serializationObject.capacity = this.getCapacity();
  48359. if (this.particleTexture) {
  48360. serializationObject.textureName = this.particleTexture.name;
  48361. }
  48362. // Animations
  48363. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  48364. // Particle system
  48365. serializationObject.minAngularSpeed = this.minAngularSpeed;
  48366. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  48367. serializationObject.minSize = this.minSize;
  48368. serializationObject.maxSize = this.maxSize;
  48369. serializationObject.minEmitPower = this.minEmitPower;
  48370. serializationObject.maxEmitPower = this.maxEmitPower;
  48371. serializationObject.minLifeTime = this.minLifeTime;
  48372. serializationObject.maxLifeTime = this.maxLifeTime;
  48373. serializationObject.emitRate = this.emitRate;
  48374. serializationObject.minEmitBox = this.minEmitBox.asArray();
  48375. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  48376. serializationObject.gravity = this.gravity.asArray();
  48377. serializationObject.direction1 = this.direction1.asArray();
  48378. serializationObject.direction2 = this.direction2.asArray();
  48379. serializationObject.color1 = this.color1.asArray();
  48380. serializationObject.color2 = this.color2.asArray();
  48381. serializationObject.colorDead = this.colorDead.asArray();
  48382. serializationObject.updateSpeed = this.updateSpeed;
  48383. serializationObject.targetStopDuration = this.targetStopDuration;
  48384. serializationObject.textureMask = this.textureMask.asArray();
  48385. serializationObject.blendMode = this.blendMode;
  48386. serializationObject.customShader = this.customShader;
  48387. serializationObject.preventAutoStart = this.preventAutoStart;
  48388. serializationObject.startSpriteCellID = this.startSpriteCellID;
  48389. serializationObject.endSpriteCellID = this.endSpriteCellID;
  48390. serializationObject.spriteCellLoop = this.spriteCellLoop;
  48391. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  48392. serializationObject.spriteCellWidth = this.spriteCellWidth;
  48393. serializationObject.spriteCellHeight = this.spriteCellHeight;
  48394. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  48395. return serializationObject;
  48396. };
  48397. /**
  48398. * Parses a JSON object to create a particle system.
  48399. * @param parsedParticleSystem The JSON object to parse
  48400. * @param scene The scene to create the particle system in
  48401. * @param rootUrl The root url to use to load external dependencies like texture
  48402. * @returns the Parsed particle system
  48403. */
  48404. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  48405. var name = parsedParticleSystem.name;
  48406. var custom = null;
  48407. var program = null;
  48408. if (parsedParticleSystem.customShader) {
  48409. program = parsedParticleSystem.customShader;
  48410. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48411. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48412. }
  48413. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  48414. particleSystem.customShader = program;
  48415. if (parsedParticleSystem.id) {
  48416. particleSystem.id = parsedParticleSystem.id;
  48417. }
  48418. // Auto start
  48419. if (parsedParticleSystem.preventAutoStart) {
  48420. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  48421. }
  48422. // Texture
  48423. if (parsedParticleSystem.textureName) {
  48424. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  48425. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  48426. }
  48427. // Emitter
  48428. if (parsedParticleSystem.emitterId) {
  48429. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  48430. }
  48431. else {
  48432. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  48433. }
  48434. // Animations
  48435. if (parsedParticleSystem.animations) {
  48436. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  48437. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  48438. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  48439. }
  48440. }
  48441. if (parsedParticleSystem.autoAnimate) {
  48442. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  48443. }
  48444. // Particle system
  48445. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  48446. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  48447. particleSystem.minSize = parsedParticleSystem.minSize;
  48448. particleSystem.maxSize = parsedParticleSystem.maxSize;
  48449. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  48450. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  48451. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  48452. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  48453. particleSystem.emitRate = parsedParticleSystem.emitRate;
  48454. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  48455. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  48456. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  48457. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  48458. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  48459. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  48460. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  48461. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  48462. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  48463. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  48464. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  48465. particleSystem.blendMode = parsedParticleSystem.blendMode;
  48466. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  48467. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  48468. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  48469. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  48470. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  48471. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  48472. if (!particleSystem.preventAutoStart) {
  48473. particleSystem.start();
  48474. }
  48475. return particleSystem;
  48476. };
  48477. /**
  48478. * Source color is added to the destination color without alpha affecting the result.
  48479. */
  48480. ParticleSystem.BLENDMODE_ONEONE = 0;
  48481. /**
  48482. * Blend current color and particle color using particle’s alpha.
  48483. */
  48484. ParticleSystem.BLENDMODE_STANDARD = 1;
  48485. return ParticleSystem;
  48486. }());
  48487. BABYLON.ParticleSystem = ParticleSystem;
  48488. })(BABYLON || (BABYLON = {}));
  48489. //# sourceMappingURL=babylon.particleSystem.js.map
  48490. var BABYLON;
  48491. (function (BABYLON) {
  48492. /**
  48493. * Particle emitter emitting particles from the inside of a box.
  48494. * It emits the particles randomly between 2 given directions.
  48495. */
  48496. var BoxParticleEmitter = /** @class */ (function () {
  48497. // to be updated like the rest of emitters when breaking changes.
  48498. // all property should be come public variables and passed through constructor.
  48499. /**
  48500. * Creates a new instance of @see BoxParticleEmitter
  48501. * @param _particleSystem the particle system associated with the emitter
  48502. */
  48503. function BoxParticleEmitter(_particleSystem) {
  48504. this._particleSystem = _particleSystem;
  48505. }
  48506. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  48507. /**
  48508. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48509. */
  48510. get: function () {
  48511. return this._particleSystem.direction1;
  48512. },
  48513. /**
  48514. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48515. */
  48516. set: function (value) {
  48517. this._particleSystem.direction1 = value;
  48518. },
  48519. enumerable: true,
  48520. configurable: true
  48521. });
  48522. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  48523. /**
  48524. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48525. */
  48526. get: function () {
  48527. return this._particleSystem.direction2;
  48528. },
  48529. /**
  48530. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48531. */
  48532. set: function (value) {
  48533. this._particleSystem.direction2 = value;
  48534. },
  48535. enumerable: true,
  48536. configurable: true
  48537. });
  48538. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  48539. /**
  48540. * 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.
  48541. */
  48542. get: function () {
  48543. return this._particleSystem.minEmitBox;
  48544. },
  48545. /**
  48546. * 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.
  48547. */
  48548. set: function (value) {
  48549. this._particleSystem.minEmitBox = value;
  48550. },
  48551. enumerable: true,
  48552. configurable: true
  48553. });
  48554. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  48555. /**
  48556. * 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.
  48557. */
  48558. get: function () {
  48559. return this._particleSystem.maxEmitBox;
  48560. },
  48561. /**
  48562. * 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.
  48563. */
  48564. set: function (value) {
  48565. this._particleSystem.maxEmitBox = value;
  48566. },
  48567. enumerable: true,
  48568. configurable: true
  48569. });
  48570. /**
  48571. * Called by the particle System when the direction is computed for the created particle.
  48572. * @param emitPower is the power of the particle (speed)
  48573. * @param worldMatrix is the world matrix of the particle system
  48574. * @param directionToUpdate is the direction vector to update with the result
  48575. * @param particle is the particle we are computed the direction for
  48576. */
  48577. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48578. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48579. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48580. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48581. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48582. };
  48583. /**
  48584. * Called by the particle System when the position is computed for the created particle.
  48585. * @param worldMatrix is the world matrix of the particle system
  48586. * @param positionToUpdate is the position vector to update with the result
  48587. * @param particle is the particle we are computed the position for
  48588. */
  48589. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48590. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  48591. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  48592. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  48593. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48594. };
  48595. /**
  48596. * Clones the current emitter and returns a copy of it
  48597. * @returns the new emitter
  48598. */
  48599. BoxParticleEmitter.prototype.clone = function () {
  48600. var newOne = new BoxParticleEmitter(this._particleSystem);
  48601. BABYLON.Tools.DeepCopy(this, newOne);
  48602. return newOne;
  48603. };
  48604. return BoxParticleEmitter;
  48605. }());
  48606. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  48607. })(BABYLON || (BABYLON = {}));
  48608. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  48609. var BABYLON;
  48610. (function (BABYLON) {
  48611. /**
  48612. * Particle emitter emitting particles from the inside of a cone.
  48613. * It emits the particles alongside the cone volume from the base to the particle.
  48614. * The emission direction might be randomized.
  48615. */
  48616. var ConeParticleEmitter = /** @class */ (function () {
  48617. /**
  48618. * Creates a new instance of @see ConeParticleEmitter
  48619. * @param radius the radius of the emission cone
  48620. * @param angles the cone base angle
  48621. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  48622. */
  48623. function ConeParticleEmitter(radius,
  48624. /**
  48625. * The radius of the emission cone.
  48626. */
  48627. angle,
  48628. /**
  48629. * The cone base angle.
  48630. */
  48631. directionRandomizer) {
  48632. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  48633. this.angle = angle;
  48634. this.directionRandomizer = directionRandomizer;
  48635. this.radius = radius;
  48636. }
  48637. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  48638. /**
  48639. * Gets the radius of the emission cone.
  48640. */
  48641. get: function () {
  48642. return this._radius;
  48643. },
  48644. /**
  48645. * Sets the radius of the emission cone.
  48646. */
  48647. set: function (value) {
  48648. this._radius = value;
  48649. if (this.angle !== 0) {
  48650. this._height = value / Math.tan(this.angle / 2);
  48651. }
  48652. else {
  48653. this._height = 1;
  48654. }
  48655. },
  48656. enumerable: true,
  48657. configurable: true
  48658. });
  48659. /**
  48660. * Called by the particle System when the direction is computed for the created particle.
  48661. * @param emitPower is the power of the particle (speed)
  48662. * @param worldMatrix is the world matrix of the particle system
  48663. * @param directionToUpdate is the direction vector to update with the result
  48664. * @param particle is the particle we are computed the direction for
  48665. */
  48666. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48667. if (this.angle === 0) {
  48668. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  48669. }
  48670. else {
  48671. // measure the direction Vector from the emitter to the particle.
  48672. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48673. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48674. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48675. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48676. direction.x += randX;
  48677. direction.y += randY;
  48678. direction.z += randZ;
  48679. direction.normalize();
  48680. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48681. }
  48682. };
  48683. /**
  48684. * Called by the particle System when the position is computed for the created particle.
  48685. * @param worldMatrix is the world matrix of the particle system
  48686. * @param positionToUpdate is the position vector to update with the result
  48687. * @param particle is the particle we are computed the position for
  48688. */
  48689. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48690. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  48691. var h = BABYLON.Scalar.RandomRange(0, 1);
  48692. // Better distribution in a cone at normal angles.
  48693. h = 1 - h * h;
  48694. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  48695. radius = radius * h / this._height;
  48696. var randX = radius * Math.sin(s);
  48697. var randZ = radius * Math.cos(s);
  48698. var randY = h;
  48699. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48700. };
  48701. /**
  48702. * Clones the current emitter and returns a copy of it
  48703. * @returns the new emitter
  48704. */
  48705. ConeParticleEmitter.prototype.clone = function () {
  48706. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  48707. BABYLON.Tools.DeepCopy(this, newOne);
  48708. return newOne;
  48709. };
  48710. return ConeParticleEmitter;
  48711. }());
  48712. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  48713. })(BABYLON || (BABYLON = {}));
  48714. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  48715. var BABYLON;
  48716. (function (BABYLON) {
  48717. /**
  48718. * Particle emitter emitting particles from the inside of a sphere.
  48719. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  48720. */
  48721. var SphereParticleEmitter = /** @class */ (function () {
  48722. /**
  48723. * Creates a new instance of @see SphereParticleEmitter
  48724. * @param radius the radius of the emission sphere
  48725. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  48726. */
  48727. function SphereParticleEmitter(
  48728. /**
  48729. * The radius of the emission sphere.
  48730. */
  48731. radius,
  48732. /**
  48733. * How much to randomize the particle direction [0-1].
  48734. */
  48735. directionRandomizer) {
  48736. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  48737. this.radius = radius;
  48738. this.directionRandomizer = directionRandomizer;
  48739. }
  48740. /**
  48741. * Called by the particle System when the direction is computed for the created particle.
  48742. * @param emitPower is the power of the particle (speed)
  48743. * @param worldMatrix is the world matrix of the particle system
  48744. * @param directionToUpdate is the direction vector to update with the result
  48745. * @param particle is the particle we are computed the direction for
  48746. */
  48747. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48748. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48749. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48750. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48751. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48752. direction.x += randX;
  48753. direction.y += randY;
  48754. direction.z += randZ;
  48755. direction.normalize();
  48756. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48757. };
  48758. /**
  48759. * Called by the particle System when the position is computed for the created particle.
  48760. * @param worldMatrix is the world matrix of the particle system
  48761. * @param positionToUpdate is the position vector to update with the result
  48762. * @param particle is the particle we are computed the position for
  48763. */
  48764. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48765. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  48766. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  48767. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  48768. var randY = this.radius * Math.cos(theta);
  48769. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  48770. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48771. };
  48772. /**
  48773. * Clones the current emitter and returns a copy of it
  48774. * @returns the new emitter
  48775. */
  48776. SphereParticleEmitter.prototype.clone = function () {
  48777. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  48778. BABYLON.Tools.DeepCopy(this, newOne);
  48779. return newOne;
  48780. };
  48781. return SphereParticleEmitter;
  48782. }());
  48783. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  48784. /**
  48785. * Particle emitter emitting particles from the inside of a sphere.
  48786. * It emits the particles randomly between two vectors.
  48787. */
  48788. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  48789. __extends(SphereDirectedParticleEmitter, _super);
  48790. /**
  48791. * Creates a new instance of @see SphereDirectedParticleEmitter
  48792. * @param radius the radius of the emission sphere
  48793. * @param direction1 the min limit of the emission direction
  48794. * @param direction2 the max limit of the emission direction
  48795. */
  48796. function SphereDirectedParticleEmitter(radius,
  48797. /**
  48798. * The min limit of the emission direction.
  48799. */
  48800. direction1,
  48801. /**
  48802. * The max limit of the emission direction.
  48803. */
  48804. direction2) {
  48805. var _this = _super.call(this, radius) || this;
  48806. _this.direction1 = direction1;
  48807. _this.direction2 = direction2;
  48808. return _this;
  48809. }
  48810. /**
  48811. * Called by the particle System when the direction is computed for the created particle.
  48812. * @param emitPower is the power of the particle (speed)
  48813. * @param worldMatrix is the world matrix of the particle system
  48814. * @param directionToUpdate is the direction vector to update with the result
  48815. * @param particle is the particle we are computed the direction for
  48816. */
  48817. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48818. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48819. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48820. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48821. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48822. };
  48823. /**
  48824. * Clones the current emitter and returns a copy of it
  48825. * @returns the new emitter
  48826. */
  48827. SphereDirectedParticleEmitter.prototype.clone = function () {
  48828. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  48829. BABYLON.Tools.DeepCopy(this, newOne);
  48830. return newOne;
  48831. };
  48832. return SphereDirectedParticleEmitter;
  48833. }(SphereParticleEmitter));
  48834. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  48835. })(BABYLON || (BABYLON = {}));
  48836. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  48837. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  48838. var BABYLON;
  48839. (function (BABYLON) {
  48840. /**
  48841. * This represents a GPU particle system in Babylon.
  48842. * This os the fastest particle system in Babylon as it uses the GPU to update the individual particle data.
  48843. */
  48844. var GPUParticleSystem = /** @class */ (function () {
  48845. /**
  48846. * Instantiates a GPU particle system.
  48847. * 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.
  48848. * @param name The name of the particle system
  48849. * @param capacity The max number of particles alive at the same time
  48850. * @param scene The scene the particle system belongs to
  48851. */
  48852. function GPUParticleSystem(name, capacity, scene) {
  48853. /**
  48854. * The emitter represents the Mesh or position we are attaching the particle system to.
  48855. */
  48856. this.emitter = null;
  48857. /**
  48858. * The rendering group used by the Particle system to chose when to render.
  48859. */
  48860. this.renderingGroupId = 0;
  48861. /**
  48862. * The layer mask we are rendering the particles through.
  48863. */
  48864. this.layerMask = 0x0FFFFFFF; // TODO
  48865. this._updateVertexBuffers = {};
  48866. this._renderVertexBuffers = {};
  48867. this._currentRenderId = -1;
  48868. this._started = true;
  48869. /**
  48870. * An event triggered when the system is disposed.
  48871. */
  48872. this.onDisposeObservable = new BABYLON.Observable();
  48873. this.id = name;
  48874. this.name = name;
  48875. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48876. this._capacity = capacity;
  48877. this._engine = this._scene.getEngine();
  48878. this._scene.particleSystems.push(this);
  48879. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  48880. var updateEffectOptions = {
  48881. attributes: ["position", "age", "life", "velocity"],
  48882. uniformsNames: [],
  48883. uniformBuffersNames: [],
  48884. samplers: [],
  48885. defines: "",
  48886. fallbacks: null,
  48887. onCompiled: null,
  48888. onError: null,
  48889. indexParameters: null,
  48890. maxSimultaneousLights: 0,
  48891. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  48892. };
  48893. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  48894. }
  48895. /**
  48896. * Gets Wether the system has been started.
  48897. * @returns True if it has been started, otherwise false.
  48898. */
  48899. GPUParticleSystem.prototype.isStarted = function () {
  48900. return this._started;
  48901. };
  48902. /**
  48903. * Starts the particle system and begins to emit.
  48904. */
  48905. GPUParticleSystem.prototype.start = function () {
  48906. this._started = true;
  48907. };
  48908. /**
  48909. * Stops the particle system.
  48910. */
  48911. GPUParticleSystem.prototype.stop = function () {
  48912. this._started = false;
  48913. };
  48914. /**
  48915. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  48916. */
  48917. GPUParticleSystem.prototype.animate = function () {
  48918. // Do nothing
  48919. };
  48920. GPUParticleSystem.prototype._initialize = function () {
  48921. if (this._renderVAO) {
  48922. return;
  48923. }
  48924. var data = new Array();
  48925. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  48926. // position
  48927. data.push(0.0);
  48928. data.push(0.0);
  48929. data.push(0.0);
  48930. var life = 1 + Math.random() * 10; // TODO: var
  48931. data.push(life + 1); // create the particle as a dead one to create a new one at start
  48932. data.push(life);
  48933. // velocity
  48934. data.push(0.0);
  48935. data.push(0.0);
  48936. data.push(0.0);
  48937. }
  48938. // Update VAO
  48939. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  48940. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  48941. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  48942. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  48943. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  48944. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  48945. this._engine.bindArrayBuffer(null);
  48946. // Render VAO
  48947. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  48948. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  48949. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  48950. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  48951. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  48952. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  48953. this._engine.bindArrayBuffer(null);
  48954. // Links
  48955. this._sourceVAO = this._updateVAO;
  48956. this._targetVAO = this._renderVAO;
  48957. this._sourceBuffer = this._updateBuffer;
  48958. this._targetBuffer = this._renderBuffer;
  48959. };
  48960. /**
  48961. * Renders the particle system in its current state.
  48962. * @returns the current number of particles.
  48963. */
  48964. GPUParticleSystem.prototype.render = function () {
  48965. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  48966. return 0;
  48967. }
  48968. // Get everything ready to render
  48969. this._initialize();
  48970. if (this._currentRenderId === this._scene.getRenderId()) {
  48971. return 0;
  48972. }
  48973. this._currentRenderId = this._scene.getRenderId();
  48974. // Enable update effect
  48975. this._engine.enableEffect(this._updateEffect);
  48976. this._engine.setState(false);
  48977. // Bind source VAO
  48978. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  48979. // Update
  48980. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  48981. this._engine.setRasterizerState(false);
  48982. this._engine.beginTransformFeedback();
  48983. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  48984. this._engine.endTransformFeedback();
  48985. this._engine.setRasterizerState(true);
  48986. this._engine.bindTransformFeedbackBuffer(null);
  48987. // Enable render effect
  48988. this._engine.enableEffect(this._renderEffect);
  48989. // Bind source VAO
  48990. this._engine.bindVertexArrayObject(this._targetVAO, null);
  48991. // Render
  48992. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  48993. // Switch VAOs
  48994. var tmpVAO = this._sourceVAO;
  48995. this._sourceVAO = this._targetVAO;
  48996. this._targetVAO = tmpVAO;
  48997. // Switch buffers
  48998. var tmpBuffer = this._sourceBuffer;
  48999. this._sourceBuffer = this._targetBuffer;
  49000. this._targetBuffer = tmpBuffer;
  49001. return 0;
  49002. };
  49003. /**
  49004. * Rebuilds the particle system
  49005. */
  49006. GPUParticleSystem.prototype.rebuild = function () {
  49007. };
  49008. /**
  49009. * Disposes the particle system and free the associated resources.
  49010. */
  49011. GPUParticleSystem.prototype.dispose = function () {
  49012. var index = this._scene.particleSystems.indexOf(this);
  49013. if (index > -1) {
  49014. this._scene.particleSystems.splice(index, 1);
  49015. }
  49016. //TODO: this._dataBuffer.dispose();
  49017. // Callback
  49018. this.onDisposeObservable.notifyObservers(this);
  49019. this.onDisposeObservable.clear();
  49020. };
  49021. //TODO: Clone / Parse / serialize
  49022. /**
  49023. * Clones the particle system.
  49024. * @param name The name of the cloned object
  49025. * @param newEmitter The new emitter to use
  49026. * @returns the cloned particle system
  49027. */
  49028. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  49029. return null;
  49030. };
  49031. /**
  49032. * Serializes the particle system to a JSON object.
  49033. * @returns the JSON object
  49034. */
  49035. GPUParticleSystem.prototype.serialize = function () {
  49036. };
  49037. return GPUParticleSystem;
  49038. }());
  49039. BABYLON.GPUParticleSystem = GPUParticleSystem;
  49040. })(BABYLON || (BABYLON = {}));
  49041. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  49042. var BABYLON;
  49043. (function (BABYLON) {
  49044. /**
  49045. * Represents one particle of a solid particle system.
  49046. * @see SolidParticleSystem
  49047. */
  49048. var SolidParticle = /** @class */ (function () {
  49049. /**
  49050. * Creates a Solid Particle object.
  49051. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49052. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49053. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49054. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  49055. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  49056. * @param shapeId (integer) is the model shape identifier in the SPS.
  49057. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49058. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  49059. */
  49060. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49061. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  49062. /**
  49063. * particle global index
  49064. */
  49065. this.idx = 0;
  49066. /**
  49067. * The color of the particle
  49068. */
  49069. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49070. /**
  49071. * The world space position of the particle.
  49072. */
  49073. this.position = BABYLON.Vector3.Zero();
  49074. /**
  49075. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  49076. */
  49077. this.rotation = BABYLON.Vector3.Zero();
  49078. /**
  49079. * The scaling of the particle.
  49080. */
  49081. this.scaling = BABYLON.Vector3.One();
  49082. /**
  49083. * The uvs of the particle.
  49084. */
  49085. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  49086. /**
  49087. * The current speed of the particle.
  49088. */
  49089. this.velocity = BABYLON.Vector3.Zero();
  49090. /**
  49091. * The pivot point in the particle local space.
  49092. */
  49093. this.pivot = BABYLON.Vector3.Zero();
  49094. /**
  49095. * Is the particle active or not ?
  49096. */
  49097. this.alive = true;
  49098. /**
  49099. * Is the particle visible or not ?
  49100. */
  49101. this.isVisible = true;
  49102. /**
  49103. * Index of this particle in the global "positions" array (Internal use)
  49104. */
  49105. this._pos = 0;
  49106. /**
  49107. * Index of this particle in the global "indices" array (Internal use)
  49108. */
  49109. this._ind = 0;
  49110. /**
  49111. * ModelShape id of this particle
  49112. */
  49113. this.shapeId = 0;
  49114. /**
  49115. * Index of the particle in its shape id (Internal use)
  49116. */
  49117. this.idxInShape = 0;
  49118. /**
  49119. * Still set as invisible in order to skip useless computations (Internal use)
  49120. */
  49121. this._stillInvisible = false;
  49122. this.idx = particleIndex;
  49123. this._pos = positionIndex;
  49124. this._ind = indiceIndex;
  49125. this._model = model;
  49126. this.shapeId = shapeId;
  49127. this.idxInShape = idxInShape;
  49128. this._sps = sps;
  49129. if (modelBoundingInfo) {
  49130. this._modelBoundingInfo = modelBoundingInfo;
  49131. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49132. }
  49133. }
  49134. Object.defineProperty(SolidParticle.prototype, "scale", {
  49135. /**
  49136. * Legacy support, changed scale to scaling
  49137. */
  49138. get: function () {
  49139. return this.scaling;
  49140. },
  49141. /**
  49142. * Legacy support, changed scale to scaling
  49143. */
  49144. set: function (scale) {
  49145. this.scaling = scale;
  49146. },
  49147. enumerable: true,
  49148. configurable: true
  49149. });
  49150. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49151. /**
  49152. * Legacy support, changed quaternion to rotationQuaternion
  49153. */
  49154. get: function () {
  49155. return this.rotationQuaternion;
  49156. },
  49157. /**
  49158. * Legacy support, changed quaternion to rotationQuaternion
  49159. */
  49160. set: function (q) {
  49161. this.rotationQuaternion = q;
  49162. },
  49163. enumerable: true,
  49164. configurable: true
  49165. });
  49166. /**
  49167. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49168. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49169. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  49170. * @returns true if it intersects
  49171. */
  49172. SolidParticle.prototype.intersectsMesh = function (target) {
  49173. if (!this._boundingInfo || !target._boundingInfo) {
  49174. return false;
  49175. }
  49176. if (this._sps._bSphereOnly) {
  49177. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49178. }
  49179. return this._boundingInfo.intersects(target._boundingInfo, false);
  49180. };
  49181. return SolidParticle;
  49182. }());
  49183. BABYLON.SolidParticle = SolidParticle;
  49184. /**
  49185. * Represents the shape of the model used by one particle of a solid particle system.
  49186. * SPS internal tool, don't use it manually.
  49187. * @see SolidParticleSystem
  49188. */
  49189. var ModelShape = /** @class */ (function () {
  49190. /**
  49191. * 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.
  49192. * SPS internal tool, don't use it manually.
  49193. * @ignore
  49194. */
  49195. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  49196. /**
  49197. * length of the shape in the model indices array (internal use)
  49198. */
  49199. this._indicesLength = 0;
  49200. this.shapeID = id;
  49201. this._shape = shape;
  49202. this._indicesLength = indicesLength;
  49203. this._shapeUV = shapeUV;
  49204. this._positionFunction = posFunction;
  49205. this._vertexFunction = vtxFunction;
  49206. }
  49207. return ModelShape;
  49208. }());
  49209. BABYLON.ModelShape = ModelShape;
  49210. /**
  49211. * Represents a Depth Sorted Particle in the solid particle system.
  49212. * @see SolidParticleSystem
  49213. */
  49214. var DepthSortedParticle = /** @class */ (function () {
  49215. function DepthSortedParticle() {
  49216. /**
  49217. * Index of the particle in the "indices" array
  49218. */
  49219. this.ind = 0;
  49220. /**
  49221. * Length of the particle shape in the "indices" array
  49222. */
  49223. this.indicesLength = 0;
  49224. /**
  49225. * Squared distance from the particle to the camera
  49226. */
  49227. this.sqDistance = 0.0;
  49228. }
  49229. return DepthSortedParticle;
  49230. }());
  49231. BABYLON.DepthSortedParticle = DepthSortedParticle;
  49232. })(BABYLON || (BABYLON = {}));
  49233. //# sourceMappingURL=babylon.solidParticle.js.map
  49234. var BABYLON;
  49235. (function (BABYLON) {
  49236. /**
  49237. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  49238. *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.
  49239. * The SPS is also a particle system. It provides some methods to manage the particles.
  49240. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  49241. *
  49242. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49243. */
  49244. var SolidParticleSystem = /** @class */ (function () {
  49245. /**
  49246. * Creates a SPS (Solid Particle System) object.
  49247. * @param name (String) is the SPS name, this will be the underlying mesh name.
  49248. * @param scene (Scene) is the scene in which the SPS is added.
  49249. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  49250. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  49251. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  49252. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  49253. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49254. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49255. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49256. */
  49257. function SolidParticleSystem(name, scene, options) {
  49258. /**
  49259. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49260. * Example : var p = SPS.particles[i];
  49261. */
  49262. this.particles = new Array();
  49263. /**
  49264. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49265. */
  49266. this.nbParticles = 0;
  49267. /**
  49268. * If the particles must ever face the camera (default false). Useful for planar particles.
  49269. */
  49270. this.billboard = false;
  49271. /**
  49272. * Recompute normals when adding a shape
  49273. */
  49274. this.recomputeNormals = true;
  49275. /**
  49276. * This a counter ofr your own usage. It's not set by any SPS functions.
  49277. */
  49278. this.counter = 0;
  49279. /**
  49280. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49281. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49282. */
  49283. this.vars = {};
  49284. /**
  49285. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  49286. */
  49287. this._bSphereOnly = false;
  49288. /**
  49289. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  49290. */
  49291. this._bSphereRadiusFactor = 1.0;
  49292. this._positions = new Array();
  49293. this._indices = new Array();
  49294. this._normals = new Array();
  49295. this._colors = new Array();
  49296. this._uvs = new Array();
  49297. this._index = 0; // indices index
  49298. this._updatable = true;
  49299. this._pickable = false;
  49300. this._isVisibilityBoxLocked = false;
  49301. this._alwaysVisible = false;
  49302. this._depthSort = false;
  49303. this._shapeCounter = 0;
  49304. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  49305. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49306. this._computeParticleColor = true;
  49307. this._computeParticleTexture = true;
  49308. this._computeParticleRotation = true;
  49309. this._computeParticleVertex = false;
  49310. this._computeBoundingBox = false;
  49311. this._depthSortParticles = true;
  49312. this._cam_axisZ = BABYLON.Vector3.Zero();
  49313. this._cam_axisY = BABYLON.Vector3.Zero();
  49314. this._cam_axisX = BABYLON.Vector3.Zero();
  49315. this._axisZ = BABYLON.Axis.Z;
  49316. this._camDir = BABYLON.Vector3.Zero();
  49317. this._camInvertedPosition = BABYLON.Vector3.Zero();
  49318. this._rotMatrix = new BABYLON.Matrix();
  49319. this._invertMatrix = new BABYLON.Matrix();
  49320. this._rotated = BABYLON.Vector3.Zero();
  49321. this._quaternion = new BABYLON.Quaternion();
  49322. this._vertex = BABYLON.Vector3.Zero();
  49323. this._normal = BABYLON.Vector3.Zero();
  49324. this._yaw = 0.0;
  49325. this._pitch = 0.0;
  49326. this._roll = 0.0;
  49327. this._halfroll = 0.0;
  49328. this._halfpitch = 0.0;
  49329. this._halfyaw = 0.0;
  49330. this._sinRoll = 0.0;
  49331. this._cosRoll = 0.0;
  49332. this._sinPitch = 0.0;
  49333. this._cosPitch = 0.0;
  49334. this._sinYaw = 0.0;
  49335. this._cosYaw = 0.0;
  49336. this._mustUnrotateFixedNormals = false;
  49337. this._minimum = BABYLON.Tmp.Vector3[0];
  49338. this._maximum = BABYLON.Tmp.Vector3[1];
  49339. this._minBbox = BABYLON.Tmp.Vector3[4];
  49340. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49341. this._particlesIntersect = false;
  49342. this._depthSortFunction = function (p1, p2) {
  49343. return (p2.sqDistance - p1.sqDistance);
  49344. };
  49345. this._needs32Bits = false;
  49346. this.name = name;
  49347. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49348. this._camera = scene.activeCamera;
  49349. this._pickable = options ? options.isPickable : false;
  49350. this._depthSort = options ? options.enableDepthSort : false;
  49351. this._particlesIntersect = options ? options.particleIntersection : false;
  49352. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49353. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49354. if (options && options.updatable) {
  49355. this._updatable = options.updatable;
  49356. }
  49357. else {
  49358. this._updatable = true;
  49359. }
  49360. if (this._pickable) {
  49361. this.pickedParticles = [];
  49362. }
  49363. if (this._depthSort) {
  49364. this.depthSortedParticles = [];
  49365. }
  49366. }
  49367. /**
  49368. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49369. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49370. * @returns the created mesh
  49371. */
  49372. SolidParticleSystem.prototype.buildMesh = function () {
  49373. if (this.nbParticles === 0) {
  49374. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49375. this.addShape(triangle, 1);
  49376. triangle.dispose();
  49377. }
  49378. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  49379. this._positions32 = new Float32Array(this._positions);
  49380. this._uvs32 = new Float32Array(this._uvs);
  49381. this._colors32 = new Float32Array(this._colors);
  49382. if (this.recomputeNormals) {
  49383. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  49384. }
  49385. this._normals32 = new Float32Array(this._normals);
  49386. this._fixedNormal32 = new Float32Array(this._normals);
  49387. if (this._mustUnrotateFixedNormals) {
  49388. this._unrotateFixedNormals();
  49389. }
  49390. var vertexData = new BABYLON.VertexData();
  49391. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  49392. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49393. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49394. if (this._uvs32) {
  49395. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49396. ;
  49397. }
  49398. if (this._colors32) {
  49399. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49400. }
  49401. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49402. vertexData.applyToMesh(mesh, this._updatable);
  49403. this.mesh = mesh;
  49404. this.mesh.isPickable = this._pickable;
  49405. // free memory
  49406. if (!this._depthSort) {
  49407. this._indices = null;
  49408. }
  49409. this._positions = null;
  49410. this._normals = null;
  49411. this._uvs = null;
  49412. this._colors = null;
  49413. if (!this._updatable) {
  49414. this.particles.length = 0;
  49415. }
  49416. return mesh;
  49417. };
  49418. /**
  49419. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49420. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49421. * Thus the particles generated from `digest()` have their property `position` set yet.
  49422. * @param mesh ( Mesh ) is the mesh to be digested
  49423. * @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
  49424. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49425. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49426. * @returns the current SPS
  49427. */
  49428. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49429. var size = (options && options.facetNb) || 1;
  49430. var number = (options && options.number) || 0;
  49431. var delta = (options && options.delta) || 0;
  49432. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49433. var meshInd = mesh.getIndices();
  49434. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49435. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49436. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49437. var f = 0; // facet counter
  49438. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49439. // compute size from number
  49440. if (number) {
  49441. number = (number > totalFacets) ? totalFacets : number;
  49442. size = Math.round(totalFacets / number);
  49443. delta = 0;
  49444. }
  49445. else {
  49446. size = (size > totalFacets) ? totalFacets : size;
  49447. }
  49448. var facetPos = []; // submesh positions
  49449. var facetInd = []; // submesh indices
  49450. var facetUV = []; // submesh UV
  49451. var facetCol = []; // submesh colors
  49452. var barycenter = BABYLON.Tmp.Vector3[0];
  49453. var sizeO = size;
  49454. while (f < totalFacets) {
  49455. size = sizeO + Math.floor((1 + delta) * Math.random());
  49456. if (f > totalFacets - size) {
  49457. size = totalFacets - f;
  49458. }
  49459. // reset temp arrays
  49460. facetPos.length = 0;
  49461. facetInd.length = 0;
  49462. facetUV.length = 0;
  49463. facetCol.length = 0;
  49464. // iterate over "size" facets
  49465. var fi = 0;
  49466. for (var j = f * 3; j < (f + size) * 3; j++) {
  49467. facetInd.push(fi);
  49468. var i = meshInd[j];
  49469. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49470. if (meshUV) {
  49471. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49472. }
  49473. if (meshCol) {
  49474. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49475. }
  49476. fi++;
  49477. }
  49478. // create a model shape for each single particle
  49479. var idx = this.nbParticles;
  49480. var shape = this._posToShape(facetPos);
  49481. var shapeUV = this._uvsToShapeUV(facetUV);
  49482. // compute the barycenter of the shape
  49483. var v;
  49484. for (v = 0; v < shape.length; v++) {
  49485. barycenter.addInPlace(shape[v]);
  49486. }
  49487. barycenter.scaleInPlace(1 / shape.length);
  49488. // shift the shape from its barycenter to the origin
  49489. for (v = 0; v < shape.length; v++) {
  49490. shape[v].subtractInPlace(barycenter);
  49491. }
  49492. var bInfo;
  49493. if (this._particlesIntersect) {
  49494. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49495. }
  49496. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  49497. // add the particle in the SPS
  49498. var currentPos = this._positions.length;
  49499. var currentInd = this._indices.length;
  49500. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49501. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  49502. // initialize the particle position
  49503. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49504. this._index += shape.length;
  49505. idx++;
  49506. this.nbParticles++;
  49507. this._shapeCounter++;
  49508. f += size;
  49509. }
  49510. return this;
  49511. };
  49512. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  49513. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  49514. var index = 0;
  49515. var idx = 0;
  49516. for (var p = 0; p < this.particles.length; p++) {
  49517. this._particle = this.particles[p];
  49518. this._shape = this._particle._model._shape;
  49519. if (this._particle.rotationQuaternion) {
  49520. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49521. }
  49522. else {
  49523. this._yaw = this._particle.rotation.y;
  49524. this._pitch = this._particle.rotation.x;
  49525. this._roll = this._particle.rotation.z;
  49526. this._quaternionRotationYPR();
  49527. }
  49528. this._quaternionToRotationMatrix();
  49529. this._rotMatrix.invertToRef(this._invertMatrix);
  49530. for (var pt = 0; pt < this._shape.length; pt++) {
  49531. idx = index + pt * 3;
  49532. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  49533. this._fixedNormal32[idx] = this._normal.x;
  49534. this._fixedNormal32[idx + 1] = this._normal.y;
  49535. this._fixedNormal32[idx + 2] = this._normal.z;
  49536. }
  49537. index = idx + 3;
  49538. }
  49539. };
  49540. //reset copy
  49541. SolidParticleSystem.prototype._resetCopy = function () {
  49542. this._copy.position.x = 0;
  49543. this._copy.position.y = 0;
  49544. this._copy.position.z = 0;
  49545. this._copy.rotation.x = 0;
  49546. this._copy.rotation.y = 0;
  49547. this._copy.rotation.z = 0;
  49548. this._copy.rotationQuaternion = null;
  49549. this._copy.scaling.x = 1.0;
  49550. this._copy.scaling.y = 1.0;
  49551. this._copy.scaling.z = 1.0;
  49552. this._copy.uvs.x = 0;
  49553. this._copy.uvs.y = 0;
  49554. this._copy.uvs.z = 1.0;
  49555. this._copy.uvs.w = 1.0;
  49556. this._copy.color = null;
  49557. };
  49558. // _meshBuilder : inserts the shape model in the global SPS mesh
  49559. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49560. var i;
  49561. var u = 0;
  49562. var c = 0;
  49563. var n = 0;
  49564. this._resetCopy();
  49565. if (options && options.positionFunction) {
  49566. options.positionFunction(this._copy, idx, idxInShape);
  49567. this._mustUnrotateFixedNormals = true;
  49568. }
  49569. if (this._copy.rotationQuaternion) {
  49570. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49571. }
  49572. else {
  49573. this._yaw = this._copy.rotation.y;
  49574. this._pitch = this._copy.rotation.x;
  49575. this._roll = this._copy.rotation.z;
  49576. this._quaternionRotationYPR();
  49577. }
  49578. this._quaternionToRotationMatrix();
  49579. for (i = 0; i < shape.length; i++) {
  49580. this._vertex.x = shape[i].x;
  49581. this._vertex.y = shape[i].y;
  49582. this._vertex.z = shape[i].z;
  49583. if (options && options.vertexFunction) {
  49584. options.vertexFunction(this._copy, this._vertex, i);
  49585. }
  49586. this._vertex.x *= this._copy.scaling.x;
  49587. this._vertex.y *= this._copy.scaling.y;
  49588. this._vertex.z *= this._copy.scaling.z;
  49589. this._vertex.x += this._copy.pivot.x;
  49590. this._vertex.y += this._copy.pivot.y;
  49591. this._vertex.z += this._copy.pivot.z;
  49592. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49593. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49594. if (meshUV) {
  49595. 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);
  49596. u += 2;
  49597. }
  49598. if (this._copy.color) {
  49599. this._color = this._copy.color;
  49600. }
  49601. else if (meshCol && meshCol[c] !== undefined) {
  49602. this._color.r = meshCol[c];
  49603. this._color.g = meshCol[c + 1];
  49604. this._color.b = meshCol[c + 2];
  49605. this._color.a = meshCol[c + 3];
  49606. }
  49607. else {
  49608. this._color.r = 1.0;
  49609. this._color.g = 1.0;
  49610. this._color.b = 1.0;
  49611. this._color.a = 1.0;
  49612. }
  49613. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49614. c += 4;
  49615. if (!this.recomputeNormals && meshNor) {
  49616. this._normal.x = meshNor[n];
  49617. this._normal.y = meshNor[n + 1];
  49618. this._normal.z = meshNor[n + 2];
  49619. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  49620. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49621. n += 3;
  49622. }
  49623. }
  49624. for (i = 0; i < meshInd.length; i++) {
  49625. var current_ind = p + meshInd[i];
  49626. indices.push(current_ind);
  49627. if (current_ind > 65535) {
  49628. this._needs32Bits = true;
  49629. }
  49630. }
  49631. if (this._pickable) {
  49632. var nbfaces = meshInd.length / 3;
  49633. for (i = 0; i < nbfaces; i++) {
  49634. this.pickedParticles.push({ idx: idx, faceId: i });
  49635. }
  49636. }
  49637. if (this._depthSort) {
  49638. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  49639. }
  49640. return this._copy;
  49641. };
  49642. // returns a shape array from positions array
  49643. SolidParticleSystem.prototype._posToShape = function (positions) {
  49644. var shape = [];
  49645. for (var i = 0; i < positions.length; i += 3) {
  49646. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49647. }
  49648. return shape;
  49649. };
  49650. // returns a shapeUV array from a Vector4 uvs
  49651. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49652. var shapeUV = [];
  49653. if (uvs) {
  49654. for (var i = 0; i < uvs.length; i++)
  49655. shapeUV.push(uvs[i]);
  49656. }
  49657. return shapeUV;
  49658. };
  49659. // adds a new particle object in the particles array
  49660. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  49661. if (bInfo === void 0) { bInfo = null; }
  49662. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  49663. this.particles.push(sp);
  49664. return sp;
  49665. };
  49666. /**
  49667. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49668. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49669. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  49670. * @param nb (positive integer) the number of particles to be created from this model
  49671. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  49672. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  49673. * @returns the number of shapes in the system
  49674. */
  49675. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49676. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49677. var meshInd = mesh.getIndices();
  49678. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49679. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49680. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49681. var bbInfo;
  49682. if (this._particlesIntersect) {
  49683. bbInfo = mesh.getBoundingInfo();
  49684. }
  49685. var shape = this._posToShape(meshPos);
  49686. var shapeUV = this._uvsToShapeUV(meshUV);
  49687. var posfunc = options ? options.positionFunction : null;
  49688. var vtxfunc = options ? options.vertexFunction : null;
  49689. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  49690. // particles
  49691. var sp;
  49692. var currentCopy;
  49693. var idx = this.nbParticles;
  49694. for (var i = 0; i < nb; i++) {
  49695. var currentPos = this._positions.length;
  49696. var currentInd = this._indices.length;
  49697. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  49698. if (this._updatable) {
  49699. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  49700. sp.position.copyFrom(currentCopy.position);
  49701. sp.rotation.copyFrom(currentCopy.rotation);
  49702. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  49703. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  49704. }
  49705. if (currentCopy.color && sp.color) {
  49706. sp.color.copyFrom(currentCopy.color);
  49707. }
  49708. sp.scaling.copyFrom(currentCopy.scaling);
  49709. sp.uvs.copyFrom(currentCopy.uvs);
  49710. }
  49711. this._index += shape.length;
  49712. idx++;
  49713. }
  49714. this.nbParticles += nb;
  49715. this._shapeCounter++;
  49716. return this._shapeCounter - 1;
  49717. };
  49718. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49719. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49720. this._resetCopy();
  49721. if (particle._model._positionFunction) {
  49722. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49723. }
  49724. if (this._copy.rotationQuaternion) {
  49725. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49726. }
  49727. else {
  49728. this._yaw = this._copy.rotation.y;
  49729. this._pitch = this._copy.rotation.x;
  49730. this._roll = this._copy.rotation.z;
  49731. this._quaternionRotationYPR();
  49732. }
  49733. this._quaternionToRotationMatrix();
  49734. this._shape = particle._model._shape;
  49735. for (var pt = 0; pt < this._shape.length; pt++) {
  49736. this._vertex.x = this._shape[pt].x;
  49737. this._vertex.y = this._shape[pt].y;
  49738. this._vertex.z = this._shape[pt].z;
  49739. if (particle._model._vertexFunction) {
  49740. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49741. }
  49742. this._vertex.x *= this._copy.scaling.x;
  49743. this._vertex.y *= this._copy.scaling.y;
  49744. this._vertex.z *= this._copy.scaling.z;
  49745. this._vertex.x += this._copy.pivot.x;
  49746. this._vertex.y += this._copy.pivot.y;
  49747. this._vertex.z += this._copy.pivot.z;
  49748. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49749. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49750. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49751. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49752. }
  49753. particle.position.x = 0.0;
  49754. particle.position.y = 0.0;
  49755. particle.position.z = 0.0;
  49756. particle.rotation.x = 0.0;
  49757. particle.rotation.y = 0.0;
  49758. particle.rotation.z = 0.0;
  49759. particle.rotationQuaternion = null;
  49760. particle.scaling.x = 1.0;
  49761. particle.scaling.y = 1.0;
  49762. particle.scaling.z = 1.0;
  49763. };
  49764. /**
  49765. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49766. * @returns the SPS.
  49767. */
  49768. SolidParticleSystem.prototype.rebuildMesh = function () {
  49769. for (var p = 0; p < this.particles.length; p++) {
  49770. this._rebuildParticle(this.particles[p]);
  49771. }
  49772. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49773. return this;
  49774. };
  49775. /**
  49776. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49777. * This method calls `updateParticle()` for each particle of the SPS.
  49778. * For an animated SPS, it is usually called within the render loop.
  49779. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49780. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49781. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49782. * @returns the SPS.
  49783. */
  49784. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49785. if (start === void 0) { start = 0; }
  49786. if (end === void 0) { end = this.nbParticles - 1; }
  49787. if (update === void 0) { update = true; }
  49788. if (!this._updatable) {
  49789. return this;
  49790. }
  49791. // custom beforeUpdate
  49792. this.beforeUpdateParticles(start, end, update);
  49793. this._cam_axisX.x = 1.0;
  49794. this._cam_axisX.y = 0.0;
  49795. this._cam_axisX.z = 0.0;
  49796. this._cam_axisY.x = 0.0;
  49797. this._cam_axisY.y = 1.0;
  49798. this._cam_axisY.z = 0.0;
  49799. this._cam_axisZ.x = 0.0;
  49800. this._cam_axisZ.y = 0.0;
  49801. this._cam_axisZ.z = 1.0;
  49802. // cases when the World Matrix is to be computed first
  49803. if (this.billboard || this._depthSort) {
  49804. this.mesh.computeWorldMatrix(true);
  49805. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  49806. }
  49807. // if the particles will always face the camera
  49808. if (this.billboard) {
  49809. // compute the camera position and un-rotate it by the current mesh rotation
  49810. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  49811. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49812. this._cam_axisZ.normalize();
  49813. // same for camera up vector extracted from the cam view matrix
  49814. var view = this._camera.getViewMatrix(true);
  49815. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  49816. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49817. this._cam_axisY.normalize();
  49818. this._cam_axisX.normalize();
  49819. }
  49820. // if depthSort, compute the camera global position in the mesh local system
  49821. if (this._depthSort) {
  49822. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  49823. }
  49824. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49825. var idx = 0; // current position index in the global array positions32
  49826. var index = 0; // position start index in the global array positions32 of the current particle
  49827. var colidx = 0; // current color index in the global array colors32
  49828. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  49829. var uvidx = 0; // current uv index in the global array uvs32
  49830. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  49831. var pt = 0; // current index in the particle model shape
  49832. if (this.mesh.isFacetDataEnabled) {
  49833. this._computeBoundingBox = true;
  49834. }
  49835. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  49836. if (this._computeBoundingBox) {
  49837. if (start == 0 && end == this.nbParticles - 1) {
  49838. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49839. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49840. }
  49841. else {
  49842. if (this.mesh._boundingInfo) {
  49843. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  49844. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  49845. }
  49846. }
  49847. }
  49848. // particle loop
  49849. index = this.particles[start]._pos;
  49850. var vpos = (index / 3) | 0;
  49851. colorIndex = vpos * 4;
  49852. uvIndex = vpos * 2;
  49853. for (var p = start; p <= end; p++) {
  49854. this._particle = this.particles[p];
  49855. this._shape = this._particle._model._shape;
  49856. this._shapeUV = this._particle._model._shapeUV;
  49857. // call to custom user function to update the particle properties
  49858. this.updateParticle(this._particle);
  49859. // camera-particle distance for depth sorting
  49860. if (this._depthSort && this._depthSortParticles) {
  49861. var dsp = this.depthSortedParticles[p];
  49862. dsp.ind = this._particle._ind;
  49863. dsp.indicesLength = this._particle._model._indicesLength;
  49864. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  49865. }
  49866. // skip the computations for inactive or already invisible particles
  49867. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  49868. // increment indexes for the next particle
  49869. pt = this._shape.length;
  49870. index += pt * 3;
  49871. colorIndex += pt * 4;
  49872. uvIndex += pt * 2;
  49873. continue;
  49874. }
  49875. if (this._particle.isVisible) {
  49876. this._particle._stillInvisible = false; // un-mark permanent invisibility
  49877. // particle rotation matrix
  49878. if (this.billboard) {
  49879. this._particle.rotation.x = 0.0;
  49880. this._particle.rotation.y = 0.0;
  49881. }
  49882. if (this._computeParticleRotation || this.billboard) {
  49883. if (this._particle.rotationQuaternion) {
  49884. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49885. }
  49886. else {
  49887. this._yaw = this._particle.rotation.y;
  49888. this._pitch = this._particle.rotation.x;
  49889. this._roll = this._particle.rotation.z;
  49890. this._quaternionRotationYPR();
  49891. }
  49892. this._quaternionToRotationMatrix();
  49893. }
  49894. // particle vertex loop
  49895. for (pt = 0; pt < this._shape.length; pt++) {
  49896. idx = index + pt * 3;
  49897. colidx = colorIndex + pt * 4;
  49898. uvidx = uvIndex + pt * 2;
  49899. this._vertex.x = this._shape[pt].x;
  49900. this._vertex.y = this._shape[pt].y;
  49901. this._vertex.z = this._shape[pt].z;
  49902. if (this._computeParticleVertex) {
  49903. this.updateParticleVertex(this._particle, this._vertex, pt);
  49904. }
  49905. // positions
  49906. this._vertex.x *= this._particle.scaling.x;
  49907. this._vertex.y *= this._particle.scaling.y;
  49908. this._vertex.z *= this._particle.scaling.z;
  49909. this._vertex.x += this._particle.pivot.x;
  49910. this._vertex.y += this._particle.pivot.y;
  49911. this._vertex.z += this._particle.pivot.z;
  49912. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49913. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49914. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49915. 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;
  49916. 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;
  49917. 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;
  49918. if (this._computeBoundingBox) {
  49919. if (this._positions32[idx] < this._minimum.x) {
  49920. this._minimum.x = this._positions32[idx];
  49921. }
  49922. if (this._positions32[idx] > this._maximum.x) {
  49923. this._maximum.x = this._positions32[idx];
  49924. }
  49925. if (this._positions32[idx + 1] < this._minimum.y) {
  49926. this._minimum.y = this._positions32[idx + 1];
  49927. }
  49928. if (this._positions32[idx + 1] > this._maximum.y) {
  49929. this._maximum.y = this._positions32[idx + 1];
  49930. }
  49931. if (this._positions32[idx + 2] < this._minimum.z) {
  49932. this._minimum.z = this._positions32[idx + 2];
  49933. }
  49934. if (this._positions32[idx + 2] > this._maximum.z) {
  49935. this._maximum.z = this._positions32[idx + 2];
  49936. }
  49937. }
  49938. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  49939. if (!this._computeParticleVertex) {
  49940. this._normal.x = this._fixedNormal32[idx];
  49941. this._normal.y = this._fixedNormal32[idx + 1];
  49942. this._normal.z = this._fixedNormal32[idx + 2];
  49943. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  49944. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  49945. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  49946. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49947. 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;
  49948. 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;
  49949. }
  49950. if (this._computeParticleColor && this._particle.color) {
  49951. this._colors32[colidx] = this._particle.color.r;
  49952. this._colors32[colidx + 1] = this._particle.color.g;
  49953. this._colors32[colidx + 2] = this._particle.color.b;
  49954. this._colors32[colidx + 3] = this._particle.color.a;
  49955. }
  49956. if (this._computeParticleTexture) {
  49957. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49958. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49959. }
  49960. }
  49961. }
  49962. else {
  49963. this._particle._stillInvisible = true; // mark the particle as invisible
  49964. for (pt = 0; pt < this._shape.length; pt++) {
  49965. idx = index + pt * 3;
  49966. colidx = colorIndex + pt * 4;
  49967. uvidx = uvIndex + pt * 2;
  49968. this._positions32[idx] = 0.0;
  49969. this._positions32[idx + 1] = 0.0;
  49970. this._positions32[idx + 2] = 0.0;
  49971. this._normals32[idx] = 0.0;
  49972. this._normals32[idx + 1] = 0.0;
  49973. this._normals32[idx + 2] = 0.0;
  49974. if (this._computeParticleColor && this._particle.color) {
  49975. this._colors32[colidx] = this._particle.color.r;
  49976. this._colors32[colidx + 1] = this._particle.color.g;
  49977. this._colors32[colidx + 2] = this._particle.color.b;
  49978. this._colors32[colidx + 3] = this._particle.color.a;
  49979. }
  49980. if (this._computeParticleTexture) {
  49981. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49982. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49983. }
  49984. }
  49985. }
  49986. // if the particle intersections must be computed : update the bbInfo
  49987. if (this._particlesIntersect) {
  49988. var bInfo = this._particle._boundingInfo;
  49989. var bBox = bInfo.boundingBox;
  49990. var bSphere = bInfo.boundingSphere;
  49991. if (!this._bSphereOnly) {
  49992. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49993. for (var b = 0; b < bBox.vectors.length; b++) {
  49994. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49995. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49996. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49997. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49998. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49999. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  50000. 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;
  50001. 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;
  50002. 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;
  50003. }
  50004. bBox._update(this.mesh._worldMatrix);
  50005. }
  50006. // place and scale the particle bouding sphere in the SPS local system, then update it
  50007. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  50008. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  50009. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  50010. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  50011. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  50012. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  50013. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  50014. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  50015. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  50016. 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));
  50017. bSphere._update(this.mesh._worldMatrix);
  50018. }
  50019. // increment indexes for the next particle
  50020. index = idx + 3;
  50021. colorIndex = colidx + 4;
  50022. uvIndex = uvidx + 2;
  50023. }
  50024. // if the VBO must be updated
  50025. if (update) {
  50026. if (this._computeParticleColor) {
  50027. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  50028. }
  50029. if (this._computeParticleTexture) {
  50030. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  50031. }
  50032. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50033. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  50034. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  50035. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  50036. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  50037. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  50038. for (var i = 0; i < this._normals32.length; i++) {
  50039. this._fixedNormal32[i] = this._normals32[i];
  50040. }
  50041. }
  50042. if (!this.mesh.areNormalsFrozen) {
  50043. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  50044. }
  50045. }
  50046. if (this._depthSort && this._depthSortParticles) {
  50047. this.depthSortedParticles.sort(this._depthSortFunction);
  50048. var dspl = this.depthSortedParticles.length;
  50049. var sorted = 0;
  50050. var lind = 0;
  50051. var sind = 0;
  50052. var sid = 0;
  50053. for (sorted = 0; sorted < dspl; sorted++) {
  50054. lind = this.depthSortedParticles[sorted].indicesLength;
  50055. sind = this.depthSortedParticles[sorted].ind;
  50056. for (var i = 0; i < lind; i++) {
  50057. this._indices32[sid] = this._indices[sind + i];
  50058. sid++;
  50059. }
  50060. }
  50061. this.mesh.updateIndices(this._indices32);
  50062. }
  50063. }
  50064. if (this._computeBoundingBox) {
  50065. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  50066. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  50067. }
  50068. this.afterUpdateParticles(start, end, update);
  50069. return this;
  50070. };
  50071. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  50072. this._halfroll = this._roll * 0.5;
  50073. this._halfpitch = this._pitch * 0.5;
  50074. this._halfyaw = this._yaw * 0.5;
  50075. this._sinRoll = Math.sin(this._halfroll);
  50076. this._cosRoll = Math.cos(this._halfroll);
  50077. this._sinPitch = Math.sin(this._halfpitch);
  50078. this._cosPitch = Math.cos(this._halfpitch);
  50079. this._sinYaw = Math.sin(this._halfyaw);
  50080. this._cosYaw = Math.cos(this._halfyaw);
  50081. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  50082. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  50083. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  50084. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  50085. };
  50086. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  50087. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  50088. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  50089. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  50090. this._rotMatrix.m[3] = 0;
  50091. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  50092. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  50093. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  50094. this._rotMatrix.m[7] = 0;
  50095. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  50096. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  50097. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  50098. this._rotMatrix.m[11] = 0;
  50099. this._rotMatrix.m[12] = 0;
  50100. this._rotMatrix.m[13] = 0;
  50101. this._rotMatrix.m[14] = 0;
  50102. this._rotMatrix.m[15] = 1.0;
  50103. };
  50104. /**
  50105. * Disposes the SPS.
  50106. */
  50107. SolidParticleSystem.prototype.dispose = function () {
  50108. this.mesh.dispose();
  50109. this.vars = null;
  50110. // drop references to internal big arrays for the GC
  50111. this._positions = null;
  50112. this._indices = null;
  50113. this._normals = null;
  50114. this._uvs = null;
  50115. this._colors = null;
  50116. this._indices32 = null;
  50117. this._positions32 = null;
  50118. this._normals32 = null;
  50119. this._fixedNormal32 = null;
  50120. this._uvs32 = null;
  50121. this._colors32 = null;
  50122. this.pickedParticles = null;
  50123. };
  50124. /**
  50125. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  50126. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50127. * @returns the SPS.
  50128. */
  50129. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  50130. if (!this._isVisibilityBoxLocked) {
  50131. this.mesh.refreshBoundingInfo();
  50132. }
  50133. return this;
  50134. };
  50135. /**
  50136. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  50137. * @param size the size (float) of the visibility box
  50138. * note : this doesn't lock the SPS mesh bounding box.
  50139. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50140. */
  50141. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  50142. var vis = size / 2;
  50143. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  50144. };
  50145. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  50146. /**
  50147. * Gets whether the SPS as always visible or not
  50148. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50149. */
  50150. get: function () {
  50151. return this._alwaysVisible;
  50152. },
  50153. /**
  50154. * Sets the SPS as always visible or not
  50155. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50156. */
  50157. set: function (val) {
  50158. this._alwaysVisible = val;
  50159. this.mesh.alwaysSelectAsActiveMesh = val;
  50160. },
  50161. enumerable: true,
  50162. configurable: true
  50163. });
  50164. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  50165. /**
  50166. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50167. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50168. */
  50169. get: function () {
  50170. return this._isVisibilityBoxLocked;
  50171. },
  50172. /**
  50173. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50174. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50175. */
  50176. set: function (val) {
  50177. this._isVisibilityBoxLocked = val;
  50178. var boundingInfo = this.mesh.getBoundingInfo();
  50179. boundingInfo.isLocked = val;
  50180. },
  50181. enumerable: true,
  50182. configurable: true
  50183. });
  50184. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  50185. /**
  50186. * Gets if `setParticles()` computes the particle rotations or not.
  50187. * Default value : true. The SPS is faster when it's set to false.
  50188. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50189. */
  50190. get: function () {
  50191. return this._computeParticleRotation;
  50192. },
  50193. /**
  50194. * Tells to `setParticles()` to compute the particle rotations or not.
  50195. * Default value : true. The SPS is faster when it's set to false.
  50196. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50197. */
  50198. set: function (val) {
  50199. this._computeParticleRotation = val;
  50200. },
  50201. enumerable: true,
  50202. configurable: true
  50203. });
  50204. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50205. /**
  50206. * Gets if `setParticles()` computes the particle colors or not.
  50207. * Default value : true. The SPS is faster when it's set to false.
  50208. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50209. */
  50210. get: function () {
  50211. return this._computeParticleColor;
  50212. },
  50213. /**
  50214. * Tells to `setParticles()` to compute the particle colors or not.
  50215. * Default value : true. The SPS is faster when it's set to false.
  50216. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50217. */
  50218. set: function (val) {
  50219. this._computeParticleColor = val;
  50220. },
  50221. enumerable: true,
  50222. configurable: true
  50223. });
  50224. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50225. /**
  50226. * Gets if `setParticles()` computes the particle textures or not.
  50227. * Default value : true. The SPS is faster when it's set to false.
  50228. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50229. */
  50230. get: function () {
  50231. return this._computeParticleTexture;
  50232. },
  50233. set: function (val) {
  50234. this._computeParticleTexture = val;
  50235. },
  50236. enumerable: true,
  50237. configurable: true
  50238. });
  50239. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50240. /**
  50241. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  50242. * Default value : false. The SPS is faster when it's set to false.
  50243. * Note : the particle custom vertex positions aren't stored values.
  50244. */
  50245. get: function () {
  50246. return this._computeParticleVertex;
  50247. },
  50248. /**
  50249. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50250. * Default value : false. The SPS is faster when it's set to false.
  50251. * Note : the particle custom vertex positions aren't stored values.
  50252. */
  50253. set: function (val) {
  50254. this._computeParticleVertex = val;
  50255. },
  50256. enumerable: true,
  50257. configurable: true
  50258. });
  50259. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50260. /**
  50261. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  50262. */
  50263. get: function () {
  50264. return this._computeBoundingBox;
  50265. },
  50266. /**
  50267. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50268. */
  50269. set: function (val) {
  50270. this._computeBoundingBox = val;
  50271. },
  50272. enumerable: true,
  50273. configurable: true
  50274. });
  50275. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  50276. /**
  50277. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  50278. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50279. * Default : `true`
  50280. */
  50281. get: function () {
  50282. return this._depthSortParticles;
  50283. },
  50284. /**
  50285. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  50286. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50287. * Default : `true`
  50288. */
  50289. set: function (val) {
  50290. this._depthSortParticles = val;
  50291. },
  50292. enumerable: true,
  50293. configurable: true
  50294. });
  50295. // =======================================================================
  50296. // Particle behavior logic
  50297. // these following methods may be overwritten by the user to fit his needs
  50298. /**
  50299. * This function does nothing. It may be overwritten to set all the particle first values.
  50300. * The SPS doesn't call this function, you may have to call it by your own.
  50301. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50302. */
  50303. SolidParticleSystem.prototype.initParticles = function () {
  50304. };
  50305. /**
  50306. * This function does nothing. It may be overwritten to recycle a particle.
  50307. * The SPS doesn't call this function, you may have to call it by your own.
  50308. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50309. * @param particle The particle to recycle
  50310. * @returns the recycled particle
  50311. */
  50312. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50313. return particle;
  50314. };
  50315. /**
  50316. * Updates a particle : this function should be overwritten by the user.
  50317. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50318. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50319. * @example : just set a particle position or velocity and recycle conditions
  50320. * @param particle The particle to update
  50321. * @returns the updated particle
  50322. */
  50323. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50324. return particle;
  50325. };
  50326. /**
  50327. * Updates a vertex of a particle : it can be overwritten by the user.
  50328. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50329. * @param particle the current particle
  50330. * @param vertex the current index of the current particle
  50331. * @param pt the index of the current vertex in the particle shape
  50332. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50333. * @example : just set a vertex particle position
  50334. * @returns the updated vertex
  50335. */
  50336. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50337. return vertex;
  50338. };
  50339. /**
  50340. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50341. * This does nothing and may be overwritten by the user.
  50342. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50343. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50344. * @param update the boolean update value actually passed to setParticles()
  50345. */
  50346. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50347. };
  50348. /**
  50349. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50350. * This will be passed three parameters.
  50351. * This does nothing and may be overwritten by the user.
  50352. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50353. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50354. * @param update the boolean update value actually passed to setParticles()
  50355. */
  50356. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50357. };
  50358. return SolidParticleSystem;
  50359. }());
  50360. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50361. })(BABYLON || (BABYLON = {}));
  50362. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50363. var BABYLON;
  50364. (function (BABYLON) {
  50365. var ShaderMaterial = /** @class */ (function (_super) {
  50366. __extends(ShaderMaterial, _super);
  50367. function ShaderMaterial(name, scene, shaderPath, options) {
  50368. var _this = _super.call(this, name, scene) || this;
  50369. _this._textures = {};
  50370. _this._textureArrays = {};
  50371. _this._floats = {};
  50372. _this._ints = {};
  50373. _this._floatsArrays = {};
  50374. _this._colors3 = {};
  50375. _this._colors3Arrays = {};
  50376. _this._colors4 = {};
  50377. _this._vectors2 = {};
  50378. _this._vectors3 = {};
  50379. _this._vectors4 = {};
  50380. _this._matrices = {};
  50381. _this._matrices3x3 = {};
  50382. _this._matrices2x2 = {};
  50383. _this._vectors2Arrays = {};
  50384. _this._vectors3Arrays = {};
  50385. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  50386. _this._shaderPath = shaderPath;
  50387. options.needAlphaBlending = options.needAlphaBlending || false;
  50388. options.needAlphaTesting = options.needAlphaTesting || false;
  50389. options.attributes = options.attributes || ["position", "normal", "uv"];
  50390. options.uniforms = options.uniforms || ["worldViewProjection"];
  50391. options.uniformBuffers = options.uniformBuffers || [];
  50392. options.samplers = options.samplers || [];
  50393. options.defines = options.defines || [];
  50394. _this._options = options;
  50395. return _this;
  50396. }
  50397. ShaderMaterial.prototype.getClassName = function () {
  50398. return "ShaderMaterial";
  50399. };
  50400. ShaderMaterial.prototype.needAlphaBlending = function () {
  50401. return this._options.needAlphaBlending;
  50402. };
  50403. ShaderMaterial.prototype.needAlphaTesting = function () {
  50404. return this._options.needAlphaTesting;
  50405. };
  50406. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  50407. if (this._options.uniforms.indexOf(uniformName) === -1) {
  50408. this._options.uniforms.push(uniformName);
  50409. }
  50410. };
  50411. ShaderMaterial.prototype.setTexture = function (name, texture) {
  50412. if (this._options.samplers.indexOf(name) === -1) {
  50413. this._options.samplers.push(name);
  50414. }
  50415. this._textures[name] = texture;
  50416. return this;
  50417. };
  50418. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  50419. if (this._options.samplers.indexOf(name) === -1) {
  50420. this._options.samplers.push(name);
  50421. }
  50422. this._checkUniform(name);
  50423. this._textureArrays[name] = textures;
  50424. return this;
  50425. };
  50426. ShaderMaterial.prototype.setFloat = function (name, value) {
  50427. this._checkUniform(name);
  50428. this._floats[name] = value;
  50429. return this;
  50430. };
  50431. ShaderMaterial.prototype.setInt = function (name, value) {
  50432. this._checkUniform(name);
  50433. this._ints[name] = value;
  50434. return this;
  50435. };
  50436. ShaderMaterial.prototype.setFloats = function (name, value) {
  50437. this._checkUniform(name);
  50438. this._floatsArrays[name] = value;
  50439. return this;
  50440. };
  50441. ShaderMaterial.prototype.setColor3 = function (name, value) {
  50442. this._checkUniform(name);
  50443. this._colors3[name] = value;
  50444. return this;
  50445. };
  50446. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  50447. this._checkUniform(name);
  50448. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  50449. color.toArray(arr, arr.length);
  50450. return arr;
  50451. }, []);
  50452. return this;
  50453. };
  50454. ShaderMaterial.prototype.setColor4 = function (name, value) {
  50455. this._checkUniform(name);
  50456. this._colors4[name] = value;
  50457. return this;
  50458. };
  50459. ShaderMaterial.prototype.setVector2 = function (name, value) {
  50460. this._checkUniform(name);
  50461. this._vectors2[name] = value;
  50462. return this;
  50463. };
  50464. ShaderMaterial.prototype.setVector3 = function (name, value) {
  50465. this._checkUniform(name);
  50466. this._vectors3[name] = value;
  50467. return this;
  50468. };
  50469. ShaderMaterial.prototype.setVector4 = function (name, value) {
  50470. this._checkUniform(name);
  50471. this._vectors4[name] = value;
  50472. return this;
  50473. };
  50474. ShaderMaterial.prototype.setMatrix = function (name, value) {
  50475. this._checkUniform(name);
  50476. this._matrices[name] = value;
  50477. return this;
  50478. };
  50479. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  50480. this._checkUniform(name);
  50481. this._matrices3x3[name] = value;
  50482. return this;
  50483. };
  50484. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  50485. this._checkUniform(name);
  50486. this._matrices2x2[name] = value;
  50487. return this;
  50488. };
  50489. ShaderMaterial.prototype.setArray2 = function (name, value) {
  50490. this._checkUniform(name);
  50491. this._vectors2Arrays[name] = value;
  50492. return this;
  50493. };
  50494. ShaderMaterial.prototype.setArray3 = function (name, value) {
  50495. this._checkUniform(name);
  50496. this._vectors3Arrays[name] = value;
  50497. return this;
  50498. };
  50499. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  50500. if (!mesh) {
  50501. return true;
  50502. }
  50503. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  50504. return false;
  50505. }
  50506. return false;
  50507. };
  50508. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  50509. var scene = this.getScene();
  50510. var engine = scene.getEngine();
  50511. if (!this.checkReadyOnEveryCall) {
  50512. if (this._renderId === scene.getRenderId()) {
  50513. if (this._checkCache(scene, mesh, useInstances)) {
  50514. return true;
  50515. }
  50516. }
  50517. }
  50518. // Instances
  50519. var defines = [];
  50520. var attribs = [];
  50521. var fallbacks = new BABYLON.EffectFallbacks();
  50522. if (useInstances) {
  50523. defines.push("#define INSTANCES");
  50524. }
  50525. for (var index = 0; index < this._options.defines.length; index++) {
  50526. defines.push(this._options.defines[index]);
  50527. }
  50528. for (var index = 0; index < this._options.attributes.length; index++) {
  50529. attribs.push(this._options.attributes[index]);
  50530. }
  50531. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  50532. attribs.push(BABYLON.VertexBuffer.ColorKind);
  50533. defines.push("#define VERTEXCOLOR");
  50534. }
  50535. // Bones
  50536. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  50537. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50538. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50539. if (mesh.numBoneInfluencers > 4) {
  50540. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50541. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50542. }
  50543. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50544. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50545. fallbacks.addCPUSkinningFallback(0, mesh);
  50546. if (this._options.uniforms.indexOf("mBones") === -1) {
  50547. this._options.uniforms.push("mBones");
  50548. }
  50549. }
  50550. else {
  50551. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50552. }
  50553. // Textures
  50554. for (var name in this._textures) {
  50555. if (!this._textures[name].isReady()) {
  50556. return false;
  50557. }
  50558. }
  50559. // Alpha test
  50560. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  50561. defines.push("#define ALPHATEST");
  50562. }
  50563. var previousEffect = this._effect;
  50564. var join = defines.join("\n");
  50565. this._effect = engine.createEffect(this._shaderPath, {
  50566. attributes: attribs,
  50567. uniformsNames: this._options.uniforms,
  50568. uniformBuffersNames: this._options.uniformBuffers,
  50569. samplers: this._options.samplers,
  50570. defines: join,
  50571. fallbacks: fallbacks,
  50572. onCompiled: this.onCompiled,
  50573. onError: this.onError
  50574. }, engine);
  50575. if (!this._effect.isReady()) {
  50576. return false;
  50577. }
  50578. if (previousEffect !== this._effect) {
  50579. scene.resetCachedMaterial();
  50580. }
  50581. this._renderId = scene.getRenderId();
  50582. return true;
  50583. };
  50584. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  50585. var scene = this.getScene();
  50586. if (!this._effect) {
  50587. return;
  50588. }
  50589. if (this._options.uniforms.indexOf("world") !== -1) {
  50590. this._effect.setMatrix("world", world);
  50591. }
  50592. if (this._options.uniforms.indexOf("worldView") !== -1) {
  50593. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  50594. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  50595. }
  50596. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  50597. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  50598. }
  50599. };
  50600. ShaderMaterial.prototype.bind = function (world, mesh) {
  50601. // Std values
  50602. this.bindOnlyWorldMatrix(world);
  50603. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  50604. if (this._options.uniforms.indexOf("view") !== -1) {
  50605. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  50606. }
  50607. if (this._options.uniforms.indexOf("projection") !== -1) {
  50608. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  50609. }
  50610. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  50611. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  50612. }
  50613. // Bones
  50614. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  50615. var name;
  50616. // Texture
  50617. for (name in this._textures) {
  50618. this._effect.setTexture(name, this._textures[name]);
  50619. }
  50620. // Texture arrays
  50621. for (name in this._textureArrays) {
  50622. this._effect.setTextureArray(name, this._textureArrays[name]);
  50623. }
  50624. // Int
  50625. for (name in this._ints) {
  50626. this._effect.setInt(name, this._ints[name]);
  50627. }
  50628. // Float
  50629. for (name in this._floats) {
  50630. this._effect.setFloat(name, this._floats[name]);
  50631. }
  50632. // Floats
  50633. for (name in this._floatsArrays) {
  50634. this._effect.setArray(name, this._floatsArrays[name]);
  50635. }
  50636. // Color3
  50637. for (name in this._colors3) {
  50638. this._effect.setColor3(name, this._colors3[name]);
  50639. }
  50640. for (name in this._colors3Arrays) {
  50641. this._effect.setArray3(name, this._colors3Arrays[name]);
  50642. }
  50643. // Color4
  50644. for (name in this._colors4) {
  50645. var color = this._colors4[name];
  50646. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50647. }
  50648. // Vector2
  50649. for (name in this._vectors2) {
  50650. this._effect.setVector2(name, this._vectors2[name]);
  50651. }
  50652. // Vector3
  50653. for (name in this._vectors3) {
  50654. this._effect.setVector3(name, this._vectors3[name]);
  50655. }
  50656. // Vector4
  50657. for (name in this._vectors4) {
  50658. this._effect.setVector4(name, this._vectors4[name]);
  50659. }
  50660. // Matrix
  50661. for (name in this._matrices) {
  50662. this._effect.setMatrix(name, this._matrices[name]);
  50663. }
  50664. // Matrix 3x3
  50665. for (name in this._matrices3x3) {
  50666. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  50667. }
  50668. // Matrix 2x2
  50669. for (name in this._matrices2x2) {
  50670. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  50671. }
  50672. // Vector2Array
  50673. for (name in this._vectors2Arrays) {
  50674. this._effect.setArray2(name, this._vectors2Arrays[name]);
  50675. }
  50676. // Vector3Array
  50677. for (name in this._vectors3Arrays) {
  50678. this._effect.setArray3(name, this._vectors3Arrays[name]);
  50679. }
  50680. }
  50681. this._afterBind(mesh);
  50682. };
  50683. ShaderMaterial.prototype.getActiveTextures = function () {
  50684. var activeTextures = _super.prototype.getActiveTextures.call(this);
  50685. for (var name in this._textures) {
  50686. activeTextures.push(this._textures[name]);
  50687. }
  50688. for (var name in this._textureArrays) {
  50689. var array = this._textureArrays[name];
  50690. for (var index = 0; index < array.length; index++) {
  50691. activeTextures.push(array[index]);
  50692. }
  50693. }
  50694. return activeTextures;
  50695. };
  50696. ShaderMaterial.prototype.hasTexture = function (texture) {
  50697. if (_super.prototype.hasTexture.call(this, texture)) {
  50698. return true;
  50699. }
  50700. for (var name in this._textures) {
  50701. if (this._textures[name] === texture) {
  50702. return true;
  50703. }
  50704. }
  50705. for (var name in this._textureArrays) {
  50706. var array = this._textureArrays[name];
  50707. for (var index = 0; index < array.length; index++) {
  50708. if (array[index] === texture) {
  50709. return true;
  50710. }
  50711. }
  50712. }
  50713. return false;
  50714. };
  50715. ShaderMaterial.prototype.clone = function (name) {
  50716. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  50717. return newShaderMaterial;
  50718. };
  50719. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  50720. if (forceDisposeTextures) {
  50721. var name;
  50722. for (name in this._textures) {
  50723. this._textures[name].dispose();
  50724. }
  50725. for (name in this._textureArrays) {
  50726. var array = this._textureArrays[name];
  50727. for (var index = 0; index < array.length; index++) {
  50728. array[index].dispose();
  50729. }
  50730. }
  50731. }
  50732. this._textures = {};
  50733. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  50734. };
  50735. ShaderMaterial.prototype.serialize = function () {
  50736. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  50737. serializationObject.customType = "BABYLON.ShaderMaterial";
  50738. serializationObject.options = this._options;
  50739. serializationObject.shaderPath = this._shaderPath;
  50740. var name;
  50741. // Texture
  50742. serializationObject.textures = {};
  50743. for (name in this._textures) {
  50744. serializationObject.textures[name] = this._textures[name].serialize();
  50745. }
  50746. // Texture arrays
  50747. serializationObject.textureArrays = {};
  50748. for (name in this._textureArrays) {
  50749. serializationObject.textureArrays[name] = [];
  50750. var array = this._textureArrays[name];
  50751. for (var index = 0; index < array.length; index++) {
  50752. serializationObject.textureArrays[name].push(array[index].serialize());
  50753. }
  50754. }
  50755. // Float
  50756. serializationObject.floats = {};
  50757. for (name in this._floats) {
  50758. serializationObject.floats[name] = this._floats[name];
  50759. }
  50760. // Float s
  50761. serializationObject.FloatArrays = {};
  50762. for (name in this._floatsArrays) {
  50763. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  50764. }
  50765. // Color3
  50766. serializationObject.colors3 = {};
  50767. for (name in this._colors3) {
  50768. serializationObject.colors3[name] = this._colors3[name].asArray();
  50769. }
  50770. // Color3 array
  50771. serializationObject.colors3Arrays = {};
  50772. for (name in this._colors3Arrays) {
  50773. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  50774. }
  50775. // Color4
  50776. serializationObject.colors4 = {};
  50777. for (name in this._colors4) {
  50778. serializationObject.colors4[name] = this._colors4[name].asArray();
  50779. }
  50780. // Vector2
  50781. serializationObject.vectors2 = {};
  50782. for (name in this._vectors2) {
  50783. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  50784. }
  50785. // Vector3
  50786. serializationObject.vectors3 = {};
  50787. for (name in this._vectors3) {
  50788. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  50789. }
  50790. // Vector4
  50791. serializationObject.vectors4 = {};
  50792. for (name in this._vectors4) {
  50793. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  50794. }
  50795. // Matrix
  50796. serializationObject.matrices = {};
  50797. for (name in this._matrices) {
  50798. serializationObject.matrices[name] = this._matrices[name].asArray();
  50799. }
  50800. // Matrix 3x3
  50801. serializationObject.matrices3x3 = {};
  50802. for (name in this._matrices3x3) {
  50803. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  50804. }
  50805. // Matrix 2x2
  50806. serializationObject.matrices2x2 = {};
  50807. for (name in this._matrices2x2) {
  50808. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  50809. }
  50810. // Vector2Array
  50811. serializationObject.vectors2Arrays = {};
  50812. for (name in this._vectors2Arrays) {
  50813. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  50814. }
  50815. // Vector3Array
  50816. serializationObject.vectors3Arrays = {};
  50817. for (name in this._vectors3Arrays) {
  50818. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  50819. }
  50820. return serializationObject;
  50821. };
  50822. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  50823. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  50824. var name;
  50825. // Texture
  50826. for (name in source.textures) {
  50827. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  50828. }
  50829. // Texture arrays
  50830. for (name in source.textureArrays) {
  50831. var array = source.textureArrays[name];
  50832. var textureArray = new Array();
  50833. for (var index = 0; index < array.length; index++) {
  50834. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  50835. }
  50836. material.setTextureArray(name, textureArray);
  50837. }
  50838. // Float
  50839. for (name in source.floats) {
  50840. material.setFloat(name, source.floats[name]);
  50841. }
  50842. // Float s
  50843. for (name in source.floatsArrays) {
  50844. material.setFloats(name, source.floatsArrays[name]);
  50845. }
  50846. // Color3
  50847. for (name in source.colors3) {
  50848. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  50849. }
  50850. // Color3 arrays
  50851. for (name in source.colors3Arrays) {
  50852. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  50853. if (i % 3 === 0) {
  50854. arr.push([num]);
  50855. }
  50856. else {
  50857. arr[arr.length - 1].push(num);
  50858. }
  50859. return arr;
  50860. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  50861. material.setColor3Array(name, colors);
  50862. }
  50863. // Color4
  50864. for (name in source.colors4) {
  50865. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  50866. }
  50867. // Vector2
  50868. for (name in source.vectors2) {
  50869. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  50870. }
  50871. // Vector3
  50872. for (name in source.vectors3) {
  50873. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  50874. }
  50875. // Vector4
  50876. for (name in source.vectors4) {
  50877. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  50878. }
  50879. // Matrix
  50880. for (name in source.matrices) {
  50881. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  50882. }
  50883. // Matrix 3x3
  50884. for (name in source.matrices3x3) {
  50885. material.setMatrix3x3(name, source.matrices3x3[name]);
  50886. }
  50887. // Matrix 2x2
  50888. for (name in source.matrices2x2) {
  50889. material.setMatrix2x2(name, source.matrices2x2[name]);
  50890. }
  50891. // Vector2Array
  50892. for (name in source.vectors2Arrays) {
  50893. material.setArray2(name, source.vectors2Arrays[name]);
  50894. }
  50895. // Vector3Array
  50896. for (name in source.vectors3Arrays) {
  50897. material.setArray3(name, source.vectors3Arrays[name]);
  50898. }
  50899. return material;
  50900. };
  50901. return ShaderMaterial;
  50902. }(BABYLON.Material));
  50903. BABYLON.ShaderMaterial = ShaderMaterial;
  50904. })(BABYLON || (BABYLON = {}));
  50905. //# sourceMappingURL=babylon.shaderMaterial.js.map
  50906. var BABYLON;
  50907. (function (BABYLON) {
  50908. var GroundMesh = /** @class */ (function (_super) {
  50909. __extends(GroundMesh, _super);
  50910. function GroundMesh(name, scene) {
  50911. var _this = _super.call(this, name, scene) || this;
  50912. _this.generateOctree = false;
  50913. return _this;
  50914. }
  50915. GroundMesh.prototype.getClassName = function () {
  50916. return "GroundMesh";
  50917. };
  50918. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  50919. get: function () {
  50920. return Math.min(this._subdivisionsX, this._subdivisionsY);
  50921. },
  50922. enumerable: true,
  50923. configurable: true
  50924. });
  50925. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  50926. get: function () {
  50927. return this._subdivisionsX;
  50928. },
  50929. enumerable: true,
  50930. configurable: true
  50931. });
  50932. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  50933. get: function () {
  50934. return this._subdivisionsY;
  50935. },
  50936. enumerable: true,
  50937. configurable: true
  50938. });
  50939. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  50940. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  50941. this._subdivisionsX = chunksCount;
  50942. this._subdivisionsY = chunksCount;
  50943. this.subdivide(chunksCount);
  50944. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  50945. };
  50946. /**
  50947. * Returns a height (y) value in the Worl system :
  50948. * the ground altitude at the coordinates (x, z) expressed in the World system.
  50949. * Returns the ground y position if (x, z) are outside the ground surface.
  50950. */
  50951. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  50952. var world = this.getWorldMatrix();
  50953. var invMat = BABYLON.Tmp.Matrix[5];
  50954. world.invertToRef(invMat);
  50955. var tmpVect = BABYLON.Tmp.Vector3[8];
  50956. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  50957. x = tmpVect.x;
  50958. z = tmpVect.z;
  50959. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50960. return this.position.y;
  50961. }
  50962. if (!this._heightQuads || this._heightQuads.length == 0) {
  50963. this._initHeightQuads();
  50964. this._computeHeightQuads();
  50965. }
  50966. var facet = this._getFacetAt(x, z);
  50967. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  50968. // return y in the World system
  50969. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  50970. return tmpVect.y;
  50971. };
  50972. /**
  50973. * Returns a normalized vector (Vector3) orthogonal to the ground
  50974. * at the ground coordinates (x, z) expressed in the World system.
  50975. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  50976. */
  50977. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  50978. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  50979. this.getNormalAtCoordinatesToRef(x, z, normal);
  50980. return normal;
  50981. };
  50982. /**
  50983. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  50984. * at the ground coordinates (x, z) expressed in the World system.
  50985. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  50986. * Returns the GroundMesh.
  50987. */
  50988. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  50989. var world = this.getWorldMatrix();
  50990. var tmpMat = BABYLON.Tmp.Matrix[5];
  50991. world.invertToRef(tmpMat);
  50992. var tmpVect = BABYLON.Tmp.Vector3[8];
  50993. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  50994. x = tmpVect.x;
  50995. z = tmpVect.z;
  50996. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50997. return this;
  50998. }
  50999. if (!this._heightQuads || this._heightQuads.length == 0) {
  51000. this._initHeightQuads();
  51001. this._computeHeightQuads();
  51002. }
  51003. var facet = this._getFacetAt(x, z);
  51004. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  51005. return this;
  51006. };
  51007. /**
  51008. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  51009. * if the ground has been updated.
  51010. * This can be used in the render loop.
  51011. * Returns the GroundMesh.
  51012. */
  51013. GroundMesh.prototype.updateCoordinateHeights = function () {
  51014. if (!this._heightQuads || this._heightQuads.length == 0) {
  51015. this._initHeightQuads();
  51016. }
  51017. this._computeHeightQuads();
  51018. return this;
  51019. };
  51020. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  51021. GroundMesh.prototype._getFacetAt = function (x, z) {
  51022. // retrieve col and row from x, z coordinates in the ground local system
  51023. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  51024. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  51025. var quad = this._heightQuads[row * this._subdivisionsX + col];
  51026. var facet;
  51027. if (z < quad.slope.x * x + quad.slope.y) {
  51028. facet = quad.facet1;
  51029. }
  51030. else {
  51031. facet = quad.facet2;
  51032. }
  51033. return facet;
  51034. };
  51035. // Creates and populates the heightMap array with "facet" elements :
  51036. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  51037. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51038. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51039. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51040. // Returns the GroundMesh.
  51041. GroundMesh.prototype._initHeightQuads = function () {
  51042. var subdivisionsX = this._subdivisionsX;
  51043. var subdivisionsY = this._subdivisionsY;
  51044. this._heightQuads = new Array();
  51045. for (var row = 0; row < subdivisionsY; row++) {
  51046. for (var col = 0; col < subdivisionsX; col++) {
  51047. 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) };
  51048. this._heightQuads[row * subdivisionsX + col] = quad;
  51049. }
  51050. }
  51051. return this;
  51052. };
  51053. // Compute each quad element values and update the the heightMap array :
  51054. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  51055. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  51056. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  51057. // Returns the GroundMesh.
  51058. GroundMesh.prototype._computeHeightQuads = function () {
  51059. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51060. if (!positions) {
  51061. return this;
  51062. }
  51063. var v1 = BABYLON.Tmp.Vector3[3];
  51064. var v2 = BABYLON.Tmp.Vector3[2];
  51065. var v3 = BABYLON.Tmp.Vector3[1];
  51066. var v4 = BABYLON.Tmp.Vector3[0];
  51067. var v1v2 = BABYLON.Tmp.Vector3[4];
  51068. var v1v3 = BABYLON.Tmp.Vector3[5];
  51069. var v1v4 = BABYLON.Tmp.Vector3[6];
  51070. var norm1 = BABYLON.Tmp.Vector3[7];
  51071. var norm2 = BABYLON.Tmp.Vector3[8];
  51072. var i = 0;
  51073. var j = 0;
  51074. var k = 0;
  51075. var cd = 0; // 2D slope coefficient : z = cd * x + h
  51076. var h = 0;
  51077. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  51078. var d2 = 0;
  51079. var subdivisionsX = this._subdivisionsX;
  51080. var subdivisionsY = this._subdivisionsY;
  51081. for (var row = 0; row < subdivisionsY; row++) {
  51082. for (var col = 0; col < subdivisionsX; col++) {
  51083. i = col * 3;
  51084. j = row * (subdivisionsX + 1) * 3;
  51085. k = (row + 1) * (subdivisionsX + 1) * 3;
  51086. v1.x = positions[j + i];
  51087. v1.y = positions[j + i + 1];
  51088. v1.z = positions[j + i + 2];
  51089. v2.x = positions[j + i + 3];
  51090. v2.y = positions[j + i + 4];
  51091. v2.z = positions[j + i + 5];
  51092. v3.x = positions[k + i];
  51093. v3.y = positions[k + i + 1];
  51094. v3.z = positions[k + i + 2];
  51095. v4.x = positions[k + i + 3];
  51096. v4.y = positions[k + i + 4];
  51097. v4.z = positions[k + i + 5];
  51098. // 2D slope V1V4
  51099. cd = (v4.z - v1.z) / (v4.x - v1.x);
  51100. h = v1.z - cd * v1.x; // v1 belongs to the slope
  51101. // facet equations :
  51102. // we compute each facet normal vector
  51103. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  51104. // we compute the value d by applying the equation to v1 which belongs to the plane
  51105. // then we store the facet equation in a Vector4
  51106. v2.subtractToRef(v1, v1v2);
  51107. v3.subtractToRef(v1, v1v3);
  51108. v4.subtractToRef(v1, v1v4);
  51109. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  51110. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  51111. norm1.normalize();
  51112. norm2.normalize();
  51113. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  51114. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  51115. var quad = this._heightQuads[row * subdivisionsX + col];
  51116. quad.slope.copyFromFloats(cd, h);
  51117. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  51118. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  51119. }
  51120. }
  51121. return this;
  51122. };
  51123. GroundMesh.prototype.serialize = function (serializationObject) {
  51124. _super.prototype.serialize.call(this, serializationObject);
  51125. serializationObject.subdivisionsX = this._subdivisionsX;
  51126. serializationObject.subdivisionsY = this._subdivisionsY;
  51127. serializationObject.minX = this._minX;
  51128. serializationObject.maxX = this._maxX;
  51129. serializationObject.minZ = this._minZ;
  51130. serializationObject.maxZ = this._maxZ;
  51131. serializationObject.width = this._width;
  51132. serializationObject.height = this._height;
  51133. };
  51134. GroundMesh.Parse = function (parsedMesh, scene) {
  51135. var result = new GroundMesh(parsedMesh.name, scene);
  51136. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  51137. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  51138. result._minX = parsedMesh.minX;
  51139. result._maxX = parsedMesh.maxX;
  51140. result._minZ = parsedMesh.minZ;
  51141. result._maxZ = parsedMesh.maxZ;
  51142. result._width = parsedMesh.width;
  51143. result._height = parsedMesh.height;
  51144. return result;
  51145. };
  51146. return GroundMesh;
  51147. }(BABYLON.Mesh));
  51148. BABYLON.GroundMesh = GroundMesh;
  51149. })(BABYLON || (BABYLON = {}));
  51150. //# sourceMappingURL=babylon.groundMesh.js.map
  51151. var BABYLON;
  51152. (function (BABYLON) {
  51153. /**
  51154. * Creates an instance based on a source mesh.
  51155. */
  51156. var InstancedMesh = /** @class */ (function (_super) {
  51157. __extends(InstancedMesh, _super);
  51158. function InstancedMesh(name, source) {
  51159. var _this = _super.call(this, name, source.getScene()) || this;
  51160. source.instances.push(_this);
  51161. _this._sourceMesh = source;
  51162. _this.position.copyFrom(source.position);
  51163. _this.rotation.copyFrom(source.rotation);
  51164. _this.scaling.copyFrom(source.scaling);
  51165. if (source.rotationQuaternion) {
  51166. _this.rotationQuaternion = source.rotationQuaternion.clone();
  51167. }
  51168. _this.infiniteDistance = source.infiniteDistance;
  51169. _this.setPivotMatrix(source.getPivotMatrix());
  51170. _this.refreshBoundingInfo();
  51171. _this._syncSubMeshes();
  51172. return _this;
  51173. }
  51174. /**
  51175. * Returns the string "InstancedMesh".
  51176. */
  51177. InstancedMesh.prototype.getClassName = function () {
  51178. return "InstancedMesh";
  51179. };
  51180. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  51181. // Methods
  51182. get: function () {
  51183. return this._sourceMesh.receiveShadows;
  51184. },
  51185. enumerable: true,
  51186. configurable: true
  51187. });
  51188. Object.defineProperty(InstancedMesh.prototype, "material", {
  51189. get: function () {
  51190. return this._sourceMesh.material;
  51191. },
  51192. enumerable: true,
  51193. configurable: true
  51194. });
  51195. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  51196. get: function () {
  51197. return this._sourceMesh.visibility;
  51198. },
  51199. enumerable: true,
  51200. configurable: true
  51201. });
  51202. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  51203. get: function () {
  51204. return this._sourceMesh.skeleton;
  51205. },
  51206. enumerable: true,
  51207. configurable: true
  51208. });
  51209. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  51210. get: function () {
  51211. return this._sourceMesh.renderingGroupId;
  51212. },
  51213. enumerable: true,
  51214. configurable: true
  51215. });
  51216. /**
  51217. * Returns the total number of vertices (integer).
  51218. */
  51219. InstancedMesh.prototype.getTotalVertices = function () {
  51220. return this._sourceMesh.getTotalVertices();
  51221. };
  51222. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  51223. get: function () {
  51224. return this._sourceMesh;
  51225. },
  51226. enumerable: true,
  51227. configurable: true
  51228. });
  51229. /**
  51230. * Is this node ready to be used/rendered
  51231. * @return {boolean} is it ready
  51232. */
  51233. InstancedMesh.prototype.isReady = function () {
  51234. return this._sourceMesh.isReady(true);
  51235. };
  51236. /**
  51237. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  51238. */
  51239. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  51240. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  51241. };
  51242. /**
  51243. * Sets the vertex data of the mesh geometry for the requested `kind`.
  51244. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  51245. * The `data` are either a numeric array either a Float32Array.
  51246. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  51247. * 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).
  51248. * Note that a new underlying VertexBuffer object is created each call.
  51249. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  51250. *
  51251. * Possible `kind` values :
  51252. * - BABYLON.VertexBuffer.PositionKind
  51253. * - BABYLON.VertexBuffer.UVKind
  51254. * - BABYLON.VertexBuffer.UV2Kind
  51255. * - BABYLON.VertexBuffer.UV3Kind
  51256. * - BABYLON.VertexBuffer.UV4Kind
  51257. * - BABYLON.VertexBuffer.UV5Kind
  51258. * - BABYLON.VertexBuffer.UV6Kind
  51259. * - BABYLON.VertexBuffer.ColorKind
  51260. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51261. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51262. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51263. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51264. *
  51265. * Returns the Mesh.
  51266. */
  51267. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  51268. if (this.sourceMesh) {
  51269. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  51270. }
  51271. return this.sourceMesh;
  51272. };
  51273. /**
  51274. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  51275. * If the mesh has no geometry, it is simply returned as it is.
  51276. * The `data` are either a numeric array either a Float32Array.
  51277. * No new underlying VertexBuffer object is created.
  51278. * 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.
  51279. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  51280. *
  51281. * Possible `kind` values :
  51282. * - BABYLON.VertexBuffer.PositionKind
  51283. * - BABYLON.VertexBuffer.UVKind
  51284. * - BABYLON.VertexBuffer.UV2Kind
  51285. * - BABYLON.VertexBuffer.UV3Kind
  51286. * - BABYLON.VertexBuffer.UV4Kind
  51287. * - BABYLON.VertexBuffer.UV5Kind
  51288. * - BABYLON.VertexBuffer.UV6Kind
  51289. * - BABYLON.VertexBuffer.ColorKind
  51290. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51291. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51292. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51293. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51294. *
  51295. * Returns the Mesh.
  51296. */
  51297. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  51298. if (this.sourceMesh) {
  51299. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  51300. }
  51301. return this.sourceMesh;
  51302. };
  51303. /**
  51304. * Sets the mesh indices.
  51305. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  51306. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  51307. * This method creates a new index buffer each call.
  51308. * Returns the Mesh.
  51309. */
  51310. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  51311. if (totalVertices === void 0) { totalVertices = null; }
  51312. if (this.sourceMesh) {
  51313. this.sourceMesh.setIndices(indices, totalVertices);
  51314. }
  51315. return this.sourceMesh;
  51316. };
  51317. /**
  51318. * Boolean : True if the mesh owns the requested kind of data.
  51319. */
  51320. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  51321. return this._sourceMesh.isVerticesDataPresent(kind);
  51322. };
  51323. /**
  51324. * Returns an array of indices (IndicesArray).
  51325. */
  51326. InstancedMesh.prototype.getIndices = function () {
  51327. return this._sourceMesh.getIndices();
  51328. };
  51329. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  51330. get: function () {
  51331. return this._sourceMesh._positions;
  51332. },
  51333. enumerable: true,
  51334. configurable: true
  51335. });
  51336. /**
  51337. * Sets a new updated BoundingInfo to the mesh.
  51338. * Returns the mesh.
  51339. */
  51340. InstancedMesh.prototype.refreshBoundingInfo = function () {
  51341. var meshBB = this._sourceMesh.getBoundingInfo();
  51342. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  51343. this._updateBoundingInfo();
  51344. return this;
  51345. };
  51346. InstancedMesh.prototype._preActivate = function () {
  51347. if (this._currentLOD) {
  51348. this._currentLOD._preActivate();
  51349. }
  51350. return this;
  51351. };
  51352. InstancedMesh.prototype._activate = function (renderId) {
  51353. if (this._currentLOD) {
  51354. this._currentLOD._registerInstanceForRenderId(this, renderId);
  51355. }
  51356. return this;
  51357. };
  51358. /**
  51359. * Returns the current associated LOD AbstractMesh.
  51360. */
  51361. InstancedMesh.prototype.getLOD = function (camera) {
  51362. if (!camera) {
  51363. return this;
  51364. }
  51365. var boundingInfo = this.getBoundingInfo();
  51366. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  51367. if (this._currentLOD === this.sourceMesh) {
  51368. return this;
  51369. }
  51370. return this._currentLOD;
  51371. };
  51372. InstancedMesh.prototype._syncSubMeshes = function () {
  51373. this.releaseSubMeshes();
  51374. if (this._sourceMesh.subMeshes) {
  51375. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  51376. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  51377. }
  51378. }
  51379. return this;
  51380. };
  51381. InstancedMesh.prototype._generatePointsArray = function () {
  51382. return this._sourceMesh._generatePointsArray();
  51383. };
  51384. /**
  51385. * Creates a new InstancedMesh from the current mesh.
  51386. * - name (string) : the cloned mesh name
  51387. * - newParent (optional Node) : the optional Node to parent the clone to.
  51388. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  51389. *
  51390. * Returns the clone.
  51391. */
  51392. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51393. var result = this._sourceMesh.createInstance(name);
  51394. // Deep copy
  51395. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  51396. // Bounding info
  51397. this.refreshBoundingInfo();
  51398. // Parent
  51399. if (newParent) {
  51400. result.parent = newParent;
  51401. }
  51402. if (!doNotCloneChildren) {
  51403. // Children
  51404. for (var index = 0; index < this.getScene().meshes.length; index++) {
  51405. var mesh = this.getScene().meshes[index];
  51406. if (mesh.parent === this) {
  51407. mesh.clone(mesh.name, result);
  51408. }
  51409. }
  51410. }
  51411. result.computeWorldMatrix(true);
  51412. return result;
  51413. };
  51414. /**
  51415. * Disposes the InstancedMesh.
  51416. * Returns nothing.
  51417. */
  51418. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  51419. // Remove from mesh
  51420. var index = this._sourceMesh.instances.indexOf(this);
  51421. this._sourceMesh.instances.splice(index, 1);
  51422. _super.prototype.dispose.call(this, doNotRecurse);
  51423. };
  51424. return InstancedMesh;
  51425. }(BABYLON.AbstractMesh));
  51426. BABYLON.InstancedMesh = InstancedMesh;
  51427. })(BABYLON || (BABYLON = {}));
  51428. //# sourceMappingURL=babylon.instancedMesh.js.map
  51429. var BABYLON;
  51430. (function (BABYLON) {
  51431. var LinesMesh = /** @class */ (function (_super) {
  51432. __extends(LinesMesh, _super);
  51433. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  51434. if (scene === void 0) { scene = null; }
  51435. if (parent === void 0) { parent = null; }
  51436. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  51437. _this.useVertexColor = useVertexColor;
  51438. _this.useVertexAlpha = useVertexAlpha;
  51439. _this.color = new BABYLON.Color3(1, 1, 1);
  51440. _this.alpha = 1;
  51441. if (source) {
  51442. _this.color = source.color.clone();
  51443. _this.alpha = source.alpha;
  51444. _this.useVertexColor = source.useVertexColor;
  51445. _this.useVertexAlpha = source.useVertexAlpha;
  51446. }
  51447. _this._intersectionThreshold = 0.1;
  51448. var defines = [];
  51449. var options = {
  51450. attributes: [BABYLON.VertexBuffer.PositionKind],
  51451. uniforms: ["world", "viewProjection"],
  51452. needAlphaBlending: true,
  51453. defines: defines
  51454. };
  51455. if (useVertexAlpha === false) {
  51456. options.needAlphaBlending = false;
  51457. }
  51458. if (!useVertexColor) {
  51459. options.uniforms.push("color");
  51460. }
  51461. else {
  51462. options.defines.push("#define VERTEXCOLOR");
  51463. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  51464. }
  51465. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  51466. return _this;
  51467. }
  51468. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  51469. /**
  51470. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  51471. * This margin is expressed in world space coordinates, so its value may vary.
  51472. * Default value is 0.1
  51473. * @returns the intersection Threshold value.
  51474. */
  51475. get: function () {
  51476. return this._intersectionThreshold;
  51477. },
  51478. /**
  51479. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  51480. * This margin is expressed in world space coordinates, so its value may vary.
  51481. * @param value the new threshold to apply
  51482. */
  51483. set: function (value) {
  51484. if (this._intersectionThreshold === value) {
  51485. return;
  51486. }
  51487. this._intersectionThreshold = value;
  51488. if (this.geometry) {
  51489. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  51490. }
  51491. },
  51492. enumerable: true,
  51493. configurable: true
  51494. });
  51495. /**
  51496. * Returns the string "LineMesh"
  51497. */
  51498. LinesMesh.prototype.getClassName = function () {
  51499. return "LinesMesh";
  51500. };
  51501. Object.defineProperty(LinesMesh.prototype, "material", {
  51502. get: function () {
  51503. return this._colorShader;
  51504. },
  51505. set: function (value) {
  51506. // Do nothing
  51507. },
  51508. enumerable: true,
  51509. configurable: true
  51510. });
  51511. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  51512. get: function () {
  51513. return false;
  51514. },
  51515. enumerable: true,
  51516. configurable: true
  51517. });
  51518. LinesMesh.prototype.createInstance = function (name) {
  51519. throw new Error("LinesMeshes do not support createInstance.");
  51520. };
  51521. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  51522. if (!this._geometry) {
  51523. return this;
  51524. }
  51525. // VBOs
  51526. this._geometry._bind(this._colorShader.getEffect());
  51527. // Color
  51528. if (!this.useVertexColor) {
  51529. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  51530. }
  51531. return this;
  51532. };
  51533. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  51534. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  51535. return this;
  51536. }
  51537. var engine = this.getScene().getEngine();
  51538. // Draw order
  51539. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  51540. return this;
  51541. };
  51542. LinesMesh.prototype.dispose = function (doNotRecurse) {
  51543. this._colorShader.dispose();
  51544. _super.prototype.dispose.call(this, doNotRecurse);
  51545. };
  51546. /**
  51547. * Returns a new LineMesh object cloned from the current one.
  51548. */
  51549. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51550. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  51551. };
  51552. return LinesMesh;
  51553. }(BABYLON.Mesh));
  51554. BABYLON.LinesMesh = LinesMesh;
  51555. })(BABYLON || (BABYLON = {}));
  51556. //# sourceMappingURL=babylon.linesMesh.js.map
  51557. var BABYLON;
  51558. (function (BABYLON) {
  51559. var MeshBuilder = /** @class */ (function () {
  51560. function MeshBuilder() {
  51561. }
  51562. MeshBuilder.updateSideOrientation = function (orientation) {
  51563. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  51564. return BABYLON.Mesh.DOUBLESIDE;
  51565. }
  51566. if (orientation === undefined || orientation === null) {
  51567. return BABYLON.Mesh.FRONTSIDE;
  51568. }
  51569. return orientation;
  51570. };
  51571. /**
  51572. * Creates a box mesh.
  51573. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  51574. * The parameter `size` sets the size (float) of each box side (default 1).
  51575. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  51576. * 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).
  51577. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  51578. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51579. * 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).
  51580. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51581. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51582. */
  51583. MeshBuilder.CreateBox = function (name, options, scene) {
  51584. if (scene === void 0) { scene = null; }
  51585. var box = new BABYLON.Mesh(name, scene);
  51586. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51587. box._originalBuilderSideOrientation = options.sideOrientation;
  51588. var vertexData = BABYLON.VertexData.CreateBox(options);
  51589. vertexData.applyToMesh(box, options.updatable);
  51590. return box;
  51591. };
  51592. /**
  51593. * Creates a sphere mesh.
  51594. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  51595. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  51596. * 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`).
  51597. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  51598. * 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
  51599. * 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).
  51600. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51601. * 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).
  51602. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51603. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51604. */
  51605. MeshBuilder.CreateSphere = function (name, options, scene) {
  51606. var sphere = new BABYLON.Mesh(name, scene);
  51607. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51608. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51609. var vertexData = BABYLON.VertexData.CreateSphere(options);
  51610. vertexData.applyToMesh(sphere, options.updatable);
  51611. return sphere;
  51612. };
  51613. /**
  51614. * Creates a plane polygonal mesh. By default, this is a disc.
  51615. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  51616. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  51617. * 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.
  51618. * 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
  51619. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51620. * 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).
  51621. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51623. */
  51624. MeshBuilder.CreateDisc = function (name, options, scene) {
  51625. if (scene === void 0) { scene = null; }
  51626. var disc = new BABYLON.Mesh(name, scene);
  51627. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51628. disc._originalBuilderSideOrientation = options.sideOrientation;
  51629. var vertexData = BABYLON.VertexData.CreateDisc(options);
  51630. vertexData.applyToMesh(disc, options.updatable);
  51631. return disc;
  51632. };
  51633. /**
  51634. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  51635. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  51636. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  51637. * 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`).
  51638. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  51639. * 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.
  51640. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51641. * 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).
  51642. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51643. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51644. */
  51645. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  51646. var sphere = new BABYLON.Mesh(name, scene);
  51647. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51648. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51649. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  51650. vertexData.applyToMesh(sphere, options.updatable);
  51651. return sphere;
  51652. };
  51653. ;
  51654. /**
  51655. * Creates a ribbon mesh.
  51656. * 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.
  51657. *
  51658. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  51659. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  51660. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  51661. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  51662. * 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.
  51663. * 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.
  51664. * 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
  51665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51666. * 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).
  51667. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51668. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51669. * 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.
  51670. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  51671. * 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
  51672. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  51673. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  51674. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51675. */
  51676. MeshBuilder.CreateRibbon = function (name, options, scene) {
  51677. if (scene === void 0) { scene = null; }
  51678. var pathArray = options.pathArray;
  51679. var closeArray = options.closeArray;
  51680. var closePath = options.closePath;
  51681. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51682. var instance = options.instance;
  51683. var updatable = options.updatable;
  51684. if (instance) {
  51685. // positionFunction : ribbon case
  51686. // only pathArray and sideOrientation parameters are taken into account for positions update
  51687. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  51688. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  51689. var positionFunction = function (positions) {
  51690. var minlg = pathArray[0].length;
  51691. var i = 0;
  51692. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  51693. for (var si = 1; si <= ns; si++) {
  51694. for (var p = 0; p < pathArray.length; p++) {
  51695. var path = pathArray[p];
  51696. var l = path.length;
  51697. minlg = (minlg < l) ? minlg : l;
  51698. var j = 0;
  51699. while (j < minlg) {
  51700. positions[i] = path[j].x;
  51701. positions[i + 1] = path[j].y;
  51702. positions[i + 2] = path[j].z;
  51703. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  51704. BABYLON.Tmp.Vector3[0].x = path[j].x;
  51705. }
  51706. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  51707. BABYLON.Tmp.Vector3[1].x = path[j].x;
  51708. }
  51709. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  51710. BABYLON.Tmp.Vector3[0].y = path[j].y;
  51711. }
  51712. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  51713. BABYLON.Tmp.Vector3[1].y = path[j].y;
  51714. }
  51715. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  51716. BABYLON.Tmp.Vector3[0].z = path[j].z;
  51717. }
  51718. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  51719. BABYLON.Tmp.Vector3[1].z = path[j].z;
  51720. }
  51721. j++;
  51722. i += 3;
  51723. }
  51724. if (instance._closePath) {
  51725. positions[i] = path[0].x;
  51726. positions[i + 1] = path[0].y;
  51727. positions[i + 2] = path[0].z;
  51728. i += 3;
  51729. }
  51730. }
  51731. }
  51732. };
  51733. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51734. positionFunction(positions);
  51735. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  51736. instance._boundingInfo.update(instance._worldMatrix);
  51737. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  51738. if (options.colors) {
  51739. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51740. for (var c = 0; c < options.colors.length; c++) {
  51741. colors[c * 4] = options.colors[c].r;
  51742. colors[c * 4 + 1] = options.colors[c].g;
  51743. colors[c * 4 + 2] = options.colors[c].b;
  51744. colors[c * 4 + 3] = options.colors[c].a;
  51745. }
  51746. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  51747. }
  51748. if (options.uvs) {
  51749. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51750. for (var i = 0; i < options.uvs.length; i++) {
  51751. uvs[i * 2] = options.uvs[i].x;
  51752. uvs[i * 2 + 1] = options.uvs[i].y;
  51753. }
  51754. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  51755. }
  51756. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  51757. var indices = instance.getIndices();
  51758. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51759. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  51760. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  51761. if (instance._closePath) {
  51762. var indexFirst = 0;
  51763. var indexLast = 0;
  51764. for (var p = 0; p < pathArray.length; p++) {
  51765. indexFirst = instance._idx[p] * 3;
  51766. if (p + 1 < pathArray.length) {
  51767. indexLast = (instance._idx[p + 1] - 1) * 3;
  51768. }
  51769. else {
  51770. indexLast = normals.length - 3;
  51771. }
  51772. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  51773. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  51774. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  51775. normals[indexLast] = normals[indexFirst];
  51776. normals[indexLast + 1] = normals[indexFirst + 1];
  51777. normals[indexLast + 2] = normals[indexFirst + 2];
  51778. }
  51779. }
  51780. if (!(instance.areNormalsFrozen)) {
  51781. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  51782. }
  51783. }
  51784. return instance;
  51785. }
  51786. else {
  51787. var ribbon = new BABYLON.Mesh(name, scene);
  51788. ribbon._originalBuilderSideOrientation = sideOrientation;
  51789. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  51790. if (closePath) {
  51791. ribbon._idx = vertexData._idx;
  51792. }
  51793. ribbon._closePath = closePath;
  51794. ribbon._closeArray = closeArray;
  51795. vertexData.applyToMesh(ribbon, updatable);
  51796. return ribbon;
  51797. }
  51798. };
  51799. /**
  51800. * Creates a cylinder or a cone mesh.
  51801. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  51802. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  51803. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  51804. * 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.
  51805. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  51806. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  51807. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  51808. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  51809. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  51810. * 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).
  51811. * 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
  51812. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  51813. * 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
  51814. * 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.
  51815. * If `enclose` is false, a ring surface is one element.
  51816. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  51817. * 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
  51818. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51819. * 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).
  51820. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51821. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51822. */
  51823. MeshBuilder.CreateCylinder = function (name, options, scene) {
  51824. var cylinder = new BABYLON.Mesh(name, scene);
  51825. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51826. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  51827. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  51828. vertexData.applyToMesh(cylinder, options.updatable);
  51829. return cylinder;
  51830. };
  51831. /**
  51832. * Creates a torus mesh.
  51833. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  51834. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  51835. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  51836. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  51837. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51838. * 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).
  51839. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51841. */
  51842. MeshBuilder.CreateTorus = function (name, options, scene) {
  51843. var torus = new BABYLON.Mesh(name, scene);
  51844. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51845. torus._originalBuilderSideOrientation = options.sideOrientation;
  51846. var vertexData = BABYLON.VertexData.CreateTorus(options);
  51847. vertexData.applyToMesh(torus, options.updatable);
  51848. return torus;
  51849. };
  51850. /**
  51851. * Creates a torus knot mesh.
  51852. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  51853. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  51854. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  51855. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  51856. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  51857. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51858. * 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).
  51859. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51860. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51861. */
  51862. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  51863. var torusKnot = new BABYLON.Mesh(name, scene);
  51864. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51865. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  51866. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  51867. vertexData.applyToMesh(torusKnot, options.updatable);
  51868. return torusKnot;
  51869. };
  51870. /**
  51871. * Creates a line system mesh.
  51872. * A line system is a pool of many lines gathered in a single mesh.
  51873. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  51874. * 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.
  51875. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  51876. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  51877. * 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
  51878. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  51879. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  51880. * 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
  51881. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  51882. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51883. */
  51884. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  51885. var instance = options.instance;
  51886. var lines = options.lines;
  51887. var colors = options.colors;
  51888. if (instance) {
  51889. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51890. var vertexColor;
  51891. var lineColors;
  51892. if (colors) {
  51893. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51894. }
  51895. var i = 0;
  51896. var c = 0;
  51897. for (var l = 0; l < lines.length; l++) {
  51898. var points = lines[l];
  51899. for (var p = 0; p < points.length; p++) {
  51900. positions[i] = points[p].x;
  51901. positions[i + 1] = points[p].y;
  51902. positions[i + 2] = points[p].z;
  51903. if (colors && vertexColor) {
  51904. lineColors = colors[l];
  51905. vertexColor[c] = lineColors[p].r;
  51906. vertexColor[c + 1] = lineColors[p].g;
  51907. vertexColor[c + 2] = lineColors[p].b;
  51908. vertexColor[c + 3] = lineColors[p].a;
  51909. c += 4;
  51910. }
  51911. i += 3;
  51912. }
  51913. }
  51914. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  51915. if (colors && vertexColor) {
  51916. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  51917. }
  51918. return instance;
  51919. }
  51920. // line system creation
  51921. var useVertexColor = (colors) ? true : false;
  51922. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  51923. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  51924. vertexData.applyToMesh(lineSystem, options.updatable);
  51925. return lineSystem;
  51926. };
  51927. /**
  51928. * Creates a line mesh.
  51929. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  51930. * 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.
  51931. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51932. * The parameter `points` is an array successive Vector3.
  51933. * 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
  51934. * The optional parameter `colors` is an array of successive Color4, one per line point.
  51935. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  51936. * When updating an instance, remember that only point positions can change, not the number of points.
  51937. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51938. */
  51939. MeshBuilder.CreateLines = function (name, options, scene) {
  51940. if (scene === void 0) { scene = null; }
  51941. var colors = (options.colors) ? [options.colors] : null;
  51942. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  51943. return lines;
  51944. };
  51945. /**
  51946. * Creates a dashed line mesh.
  51947. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  51948. * 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.
  51949. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51950. * The parameter `points` is an array successive Vector3.
  51951. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  51952. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  51953. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  51954. * 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
  51955. * When updating an instance, remember that only point positions can change, not the number of points.
  51956. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51957. */
  51958. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  51959. if (scene === void 0) { scene = null; }
  51960. var points = options.points;
  51961. var instance = options.instance;
  51962. var gapSize = options.gapSize || 1;
  51963. var dashSize = options.dashSize || 3;
  51964. if (instance) {
  51965. var positionFunction = function (positions) {
  51966. var curvect = BABYLON.Vector3.Zero();
  51967. var nbSeg = positions.length / 6;
  51968. var lg = 0;
  51969. var nb = 0;
  51970. var shft = 0;
  51971. var dashshft = 0;
  51972. var curshft = 0;
  51973. var p = 0;
  51974. var i = 0;
  51975. var j = 0;
  51976. for (i = 0; i < points.length - 1; i++) {
  51977. points[i + 1].subtractToRef(points[i], curvect);
  51978. lg += curvect.length();
  51979. }
  51980. shft = lg / nbSeg;
  51981. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  51982. for (i = 0; i < points.length - 1; i++) {
  51983. points[i + 1].subtractToRef(points[i], curvect);
  51984. nb = Math.floor(curvect.length() / shft);
  51985. curvect.normalize();
  51986. j = 0;
  51987. while (j < nb && p < positions.length) {
  51988. curshft = shft * j;
  51989. positions[p] = points[i].x + curshft * curvect.x;
  51990. positions[p + 1] = points[i].y + curshft * curvect.y;
  51991. positions[p + 2] = points[i].z + curshft * curvect.z;
  51992. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  51993. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  51994. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  51995. p += 6;
  51996. j++;
  51997. }
  51998. }
  51999. while (p < positions.length) {
  52000. positions[p] = points[i].x;
  52001. positions[p + 1] = points[i].y;
  52002. positions[p + 2] = points[i].z;
  52003. p += 3;
  52004. }
  52005. };
  52006. instance.updateMeshPositions(positionFunction, false);
  52007. return instance;
  52008. }
  52009. // dashed lines creation
  52010. var dashedLines = new BABYLON.LinesMesh(name, scene);
  52011. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  52012. vertexData.applyToMesh(dashedLines, options.updatable);
  52013. dashedLines.dashSize = dashSize;
  52014. dashedLines.gapSize = gapSize;
  52015. return dashedLines;
  52016. };
  52017. /**
  52018. * Creates an extruded shape mesh.
  52019. * 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.
  52020. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  52021. *
  52022. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52023. * 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
  52024. * extruded along the Z axis.
  52025. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52026. * 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.
  52027. * The parameter `scale` (float, default 1) is the value to scale the shape.
  52028. * 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
  52029. * 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
  52030. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52031. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52032. * 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).
  52033. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52034. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52035. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52036. */
  52037. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  52038. if (scene === void 0) { scene = null; }
  52039. var path = options.path;
  52040. var shape = options.shape;
  52041. var scale = options.scale || 1;
  52042. var rotation = options.rotation || 0;
  52043. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52044. var updatable = options.updatable;
  52045. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52046. var instance = options.instance || null;
  52047. var invertUV = options.invertUV || false;
  52048. 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);
  52049. };
  52050. /**
  52051. * Creates an custom extruded shape mesh.
  52052. * 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.
  52053. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  52054. *
  52055. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  52056. * 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
  52057. * extruded along the Z axis.
  52058. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  52059. * 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
  52060. * and the distance of this point from the begining of the path :
  52061. * ```javascript
  52062. * var rotationFunction = function(i, distance) {
  52063. * // do things
  52064. * return rotationValue; }
  52065. * ```
  52066. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  52067. * 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
  52068. * and the distance of this point from the begining of the path :
  52069. * ```javascript
  52070. * var scaleFunction = function(i, distance) {
  52071. * // do things
  52072. * return scaleValue;}
  52073. * ```
  52074. * It must returns a float value that will be the scale value applied to the shape on each path point.
  52075. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  52076. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  52077. * 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
  52078. * 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
  52079. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  52080. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52081. * 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).
  52082. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52083. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52084. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52085. */
  52086. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  52087. var path = options.path;
  52088. var shape = options.shape;
  52089. var scaleFunction = options.scaleFunction || (function () { return 1; });
  52090. var rotationFunction = options.rotationFunction || (function () { return 0; });
  52091. var ribbonCloseArray = options.ribbonCloseArray || false;
  52092. var ribbonClosePath = options.ribbonClosePath || false;
  52093. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  52094. var updatable = options.updatable;
  52095. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52096. var instance = options.instance;
  52097. var invertUV = options.invertUV || false;
  52098. 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);
  52099. };
  52100. /**
  52101. * Creates lathe mesh.
  52102. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  52103. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  52104. *
  52105. * 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
  52106. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  52107. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  52108. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  52109. * 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.
  52110. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  52111. * 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
  52112. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52113. * 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).
  52114. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52115. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52116. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52117. */
  52118. MeshBuilder.CreateLathe = function (name, options, scene) {
  52119. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  52120. var closed = (options.closed === undefined) ? true : options.closed;
  52121. var shape = options.shape;
  52122. var radius = options.radius || 1;
  52123. var tessellation = options.tessellation || 64;
  52124. var updatable = options.updatable;
  52125. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52126. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52127. var pi2 = Math.PI * 2;
  52128. var paths = new Array();
  52129. var invertUV = options.invertUV || false;
  52130. var i = 0;
  52131. var p = 0;
  52132. var step = pi2 / tessellation * arc;
  52133. var rotated;
  52134. var path = new Array();
  52135. ;
  52136. for (i = 0; i <= tessellation; i++) {
  52137. var path = [];
  52138. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  52139. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  52140. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  52141. }
  52142. for (p = 0; p < shape.length; p++) {
  52143. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  52144. path.push(rotated);
  52145. }
  52146. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  52147. 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));
  52148. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  52149. }
  52150. paths.push(path);
  52151. }
  52152. // lathe ribbon
  52153. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52154. return lathe;
  52155. };
  52156. /**
  52157. * Creates a plane mesh.
  52158. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52159. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  52160. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  52161. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  52162. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52163. * 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).
  52164. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52165. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52166. */
  52167. MeshBuilder.CreatePlane = function (name, options, scene) {
  52168. var plane = new BABYLON.Mesh(name, scene);
  52169. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52170. plane._originalBuilderSideOrientation = options.sideOrientation;
  52171. var vertexData = BABYLON.VertexData.CreatePlane(options);
  52172. vertexData.applyToMesh(plane, options.updatable);
  52173. if (options.sourcePlane) {
  52174. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  52175. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  52176. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  52177. plane.rotate(vectorProduct, product);
  52178. }
  52179. return plane;
  52180. };
  52181. /**
  52182. * Creates a ground mesh.
  52183. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  52184. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  52185. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  52186. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52187. */
  52188. MeshBuilder.CreateGround = function (name, options, scene) {
  52189. var ground = new BABYLON.GroundMesh(name, scene);
  52190. ground._setReady(false);
  52191. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  52192. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  52193. ground._width = options.width || 1;
  52194. ground._height = options.height || 1;
  52195. ground._maxX = ground._width / 2;
  52196. ground._maxZ = ground._height / 2;
  52197. ground._minX = -ground._maxX;
  52198. ground._minZ = -ground._maxZ;
  52199. var vertexData = BABYLON.VertexData.CreateGround(options);
  52200. vertexData.applyToMesh(ground, options.updatable);
  52201. ground._setReady(true);
  52202. return ground;
  52203. };
  52204. /**
  52205. * Creates a tiled ground mesh.
  52206. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  52207. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  52208. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  52209. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  52210. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  52211. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  52212. * numbers of subdivisions on the ground width and height of each tile.
  52213. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52214. */
  52215. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  52216. var tiledGround = new BABYLON.Mesh(name, scene);
  52217. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  52218. vertexData.applyToMesh(tiledGround, options.updatable);
  52219. return tiledGround;
  52220. };
  52221. /**
  52222. * Creates a ground mesh from a height map.
  52223. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  52224. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  52225. * The parameter `url` sets the URL of the height map image resource.
  52226. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  52227. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  52228. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  52229. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  52230. * 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.
  52231. * 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).
  52232. * This function is passed the newly built mesh :
  52233. * ```javascript
  52234. * function(mesh) { // do things
  52235. * return; }
  52236. * ```
  52237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52238. */
  52239. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  52240. var width = options.width || 10.0;
  52241. var height = options.height || 10.0;
  52242. var subdivisions = options.subdivisions || 1 | 0;
  52243. var minHeight = options.minHeight || 0.0;
  52244. var maxHeight = options.maxHeight || 1.0;
  52245. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  52246. var updatable = options.updatable;
  52247. var onReady = options.onReady;
  52248. var ground = new BABYLON.GroundMesh(name, scene);
  52249. ground._subdivisionsX = subdivisions;
  52250. ground._subdivisionsY = subdivisions;
  52251. ground._width = width;
  52252. ground._height = height;
  52253. ground._maxX = ground._width / 2.0;
  52254. ground._maxZ = ground._height / 2.0;
  52255. ground._minX = -ground._maxX;
  52256. ground._minZ = -ground._maxZ;
  52257. ground._setReady(false);
  52258. var onload = function (img) {
  52259. // Getting height map data
  52260. var canvas = document.createElement("canvas");
  52261. var context = canvas.getContext("2d");
  52262. if (!context) {
  52263. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  52264. }
  52265. if (scene.isDisposed) {
  52266. return;
  52267. }
  52268. var bufferWidth = img.width;
  52269. var bufferHeight = img.height;
  52270. canvas.width = bufferWidth;
  52271. canvas.height = bufferHeight;
  52272. context.drawImage(img, 0, 0);
  52273. // Create VertexData from map data
  52274. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  52275. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  52276. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  52277. width: width, height: height,
  52278. subdivisions: subdivisions,
  52279. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  52280. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  52281. });
  52282. vertexData.applyToMesh(ground, updatable);
  52283. ground._setReady(true);
  52284. //execute ready callback, if set
  52285. if (onReady) {
  52286. onReady(ground);
  52287. }
  52288. };
  52289. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  52290. return ground;
  52291. };
  52292. /**
  52293. * Creates a polygon mesh.
  52294. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  52295. * 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.
  52296. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52297. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52298. * 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).
  52299. * Remember you can only change the shape positions, not their number when updating a polygon.
  52300. */
  52301. MeshBuilder.CreatePolygon = function (name, options, scene) {
  52302. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52303. var shape = options.shape;
  52304. var holes = options.holes || [];
  52305. var depth = options.depth || 0;
  52306. var contours = [];
  52307. var hole = [];
  52308. for (var i = 0; i < shape.length; i++) {
  52309. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  52310. }
  52311. var epsilon = 0.00000001;
  52312. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  52313. contours.pop();
  52314. }
  52315. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  52316. for (var hNb = 0; hNb < holes.length; hNb++) {
  52317. hole = [];
  52318. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  52319. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  52320. }
  52321. polygonTriangulation.addHole(hole);
  52322. }
  52323. var polygon = polygonTriangulation.build(options.updatable, depth);
  52324. polygon._originalBuilderSideOrientation = options.sideOrientation;
  52325. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  52326. vertexData.applyToMesh(polygon, options.updatable);
  52327. return polygon;
  52328. };
  52329. ;
  52330. /**
  52331. * Creates an extruded polygon mesh, with depth in the Y direction.
  52332. * 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).
  52333. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  52334. */
  52335. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  52336. return MeshBuilder.CreatePolygon(name, options, scene);
  52337. };
  52338. ;
  52339. /**
  52340. * Creates a tube mesh.
  52341. * 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.
  52342. *
  52343. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  52344. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  52345. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  52346. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  52347. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  52348. * 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.
  52349. * It must return a radius value (positive float) :
  52350. * ```javascript
  52351. * var radiusFunction = function(i, distance) {
  52352. * // do things
  52353. * return radius; }
  52354. * ```
  52355. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  52356. * 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
  52357. * 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
  52358. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52359. * 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).
  52360. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52361. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52362. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52363. */
  52364. MeshBuilder.CreateTube = function (name, options, scene) {
  52365. var path = options.path;
  52366. var instance = options.instance;
  52367. var radius = 1.0;
  52368. if (instance) {
  52369. radius = instance.radius;
  52370. }
  52371. if (options.radius !== undefined) {
  52372. radius = options.radius;
  52373. }
  52374. ;
  52375. var tessellation = options.tessellation || 64 | 0;
  52376. var radiusFunction = options.radiusFunction || null;
  52377. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52378. var invertUV = options.invertUV || false;
  52379. var updatable = options.updatable;
  52380. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52381. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  52382. // tube geometry
  52383. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  52384. var tangents = path3D.getTangents();
  52385. var normals = path3D.getNormals();
  52386. var distances = path3D.getDistances();
  52387. var pi2 = Math.PI * 2;
  52388. var step = pi2 / tessellation * arc;
  52389. var returnRadius = function () { return radius; };
  52390. var radiusFunctionFinal = radiusFunction || returnRadius;
  52391. var circlePath;
  52392. var rad;
  52393. var normal;
  52394. var rotated;
  52395. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52396. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52397. for (var i = 0; i < path.length; i++) {
  52398. rad = radiusFunctionFinal(i, distances[i]); // current radius
  52399. circlePath = Array(); // current circle array
  52400. normal = normals[i]; // current normal
  52401. for (var t = 0; t < tessellation; t++) {
  52402. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  52403. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  52404. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  52405. rotated.scaleInPlace(rad).addInPlace(path[i]);
  52406. circlePath[t] = rotated;
  52407. }
  52408. circlePaths[index] = circlePath;
  52409. index++;
  52410. }
  52411. // cap
  52412. var capPath = function (nbPoints, pathIndex) {
  52413. var pointCap = Array();
  52414. for (var i = 0; i < nbPoints; i++) {
  52415. pointCap.push(path[pathIndex]);
  52416. }
  52417. return pointCap;
  52418. };
  52419. switch (cap) {
  52420. case BABYLON.Mesh.NO_CAP:
  52421. break;
  52422. case BABYLON.Mesh.CAP_START:
  52423. circlePaths[0] = capPath(tessellation, 0);
  52424. circlePaths[1] = circlePaths[2].slice(0);
  52425. break;
  52426. case BABYLON.Mesh.CAP_END:
  52427. circlePaths[index] = circlePaths[index - 1].slice(0);
  52428. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52429. break;
  52430. case BABYLON.Mesh.CAP_ALL:
  52431. circlePaths[0] = capPath(tessellation, 0);
  52432. circlePaths[1] = circlePaths[2].slice(0);
  52433. circlePaths[index] = circlePaths[index - 1].slice(0);
  52434. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52435. break;
  52436. default:
  52437. break;
  52438. }
  52439. return circlePaths;
  52440. };
  52441. var path3D;
  52442. var pathArray;
  52443. if (instance) {
  52444. var arc = options.arc || instance.arc;
  52445. path3D = (instance.path3D).update(path);
  52446. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  52447. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  52448. instance.path3D = path3D;
  52449. instance.pathArray = pathArray;
  52450. instance.arc = arc;
  52451. instance.radius = radius;
  52452. return instance;
  52453. }
  52454. // tube creation
  52455. path3D = new BABYLON.Path3D(path);
  52456. var newPathArray = new Array();
  52457. cap = (cap < 0 || cap > 3) ? 0 : cap;
  52458. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  52459. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52460. tube.pathArray = pathArray;
  52461. tube.path3D = path3D;
  52462. tube.tessellation = tessellation;
  52463. tube.cap = cap;
  52464. tube.arc = options.arc;
  52465. tube.radius = radius;
  52466. return tube;
  52467. };
  52468. /**
  52469. * Creates a polyhedron mesh.
  52470. *
  52471. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  52472. * 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
  52473. * to choose the wanted type.
  52474. * The parameter `size` (positive float, default 1) sets the polygon size.
  52475. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  52476. * 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`.
  52477. * 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
  52478. * 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)`).
  52479. * 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
  52480. * 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.
  52481. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52482. * 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).
  52483. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52484. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52485. */
  52486. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  52487. var polyhedron = new BABYLON.Mesh(name, scene);
  52488. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52489. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  52490. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  52491. vertexData.applyToMesh(polyhedron, options.updatable);
  52492. return polyhedron;
  52493. };
  52494. /**
  52495. * Creates a decal mesh.
  52496. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  52497. * 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.
  52498. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  52499. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  52500. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  52501. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  52502. */
  52503. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  52504. var indices = sourceMesh.getIndices();
  52505. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52506. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52507. var position = options.position || BABYLON.Vector3.Zero();
  52508. var normal = options.normal || BABYLON.Vector3.Up();
  52509. var size = options.size || BABYLON.Vector3.One();
  52510. var angle = options.angle || 0;
  52511. // Getting correct rotation
  52512. if (!normal) {
  52513. var target = new BABYLON.Vector3(0, 0, 1);
  52514. var camera = sourceMesh.getScene().activeCamera;
  52515. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  52516. normal = camera.globalPosition.subtract(cameraWorldTarget);
  52517. }
  52518. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  52519. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  52520. var pitch = Math.atan2(normal.y, len);
  52521. // Matrix
  52522. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  52523. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  52524. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  52525. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  52526. var vertexData = new BABYLON.VertexData();
  52527. vertexData.indices = [];
  52528. vertexData.positions = [];
  52529. vertexData.normals = [];
  52530. vertexData.uvs = [];
  52531. var currentVertexDataIndex = 0;
  52532. var extractDecalVector3 = function (indexId) {
  52533. var result = new BABYLON.PositionNormalVertex();
  52534. if (!indices || !positions || !normals) {
  52535. return result;
  52536. }
  52537. var vertexId = indices[indexId];
  52538. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  52539. // Send vector to decal local world
  52540. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  52541. // Get normal
  52542. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  52543. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  52544. return result;
  52545. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  52546. var clip = function (vertices, axis) {
  52547. if (vertices.length === 0) {
  52548. return vertices;
  52549. }
  52550. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  52551. var clipVertices = function (v0, v1) {
  52552. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  52553. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  52554. };
  52555. var result = new Array();
  52556. for (var index = 0; index < vertices.length; index += 3) {
  52557. var v1Out;
  52558. var v2Out;
  52559. var v3Out;
  52560. var total = 0;
  52561. var nV1 = null;
  52562. var nV2 = null;
  52563. var nV3 = null;
  52564. var nV4 = null;
  52565. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  52566. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  52567. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  52568. v1Out = d1 > 0;
  52569. v2Out = d2 > 0;
  52570. v3Out = d3 > 0;
  52571. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  52572. switch (total) {
  52573. case 0:
  52574. result.push(vertices[index]);
  52575. result.push(vertices[index + 1]);
  52576. result.push(vertices[index + 2]);
  52577. break;
  52578. case 1:
  52579. if (v1Out) {
  52580. nV1 = vertices[index + 1];
  52581. nV2 = vertices[index + 2];
  52582. nV3 = clipVertices(vertices[index], nV1);
  52583. nV4 = clipVertices(vertices[index], nV2);
  52584. }
  52585. if (v2Out) {
  52586. nV1 = vertices[index];
  52587. nV2 = vertices[index + 2];
  52588. nV3 = clipVertices(vertices[index + 1], nV1);
  52589. nV4 = clipVertices(vertices[index + 1], nV2);
  52590. result.push(nV3);
  52591. result.push(nV2.clone());
  52592. result.push(nV1.clone());
  52593. result.push(nV2.clone());
  52594. result.push(nV3.clone());
  52595. result.push(nV4);
  52596. break;
  52597. }
  52598. if (v3Out) {
  52599. nV1 = vertices[index];
  52600. nV2 = vertices[index + 1];
  52601. nV3 = clipVertices(vertices[index + 2], nV1);
  52602. nV4 = clipVertices(vertices[index + 2], nV2);
  52603. }
  52604. if (nV1 && nV2 && nV3 && nV4) {
  52605. result.push(nV1.clone());
  52606. result.push(nV2.clone());
  52607. result.push(nV3);
  52608. result.push(nV4);
  52609. result.push(nV3.clone());
  52610. result.push(nV2.clone());
  52611. }
  52612. break;
  52613. case 2:
  52614. if (!v1Out) {
  52615. nV1 = vertices[index].clone();
  52616. nV2 = clipVertices(nV1, vertices[index + 1]);
  52617. nV3 = clipVertices(nV1, vertices[index + 2]);
  52618. result.push(nV1);
  52619. result.push(nV2);
  52620. result.push(nV3);
  52621. }
  52622. if (!v2Out) {
  52623. nV1 = vertices[index + 1].clone();
  52624. nV2 = clipVertices(nV1, vertices[index + 2]);
  52625. nV3 = clipVertices(nV1, vertices[index]);
  52626. result.push(nV1);
  52627. result.push(nV2);
  52628. result.push(nV3);
  52629. }
  52630. if (!v3Out) {
  52631. nV1 = vertices[index + 2].clone();
  52632. nV2 = clipVertices(nV1, vertices[index]);
  52633. nV3 = clipVertices(nV1, vertices[index + 1]);
  52634. result.push(nV1);
  52635. result.push(nV2);
  52636. result.push(nV3);
  52637. }
  52638. break;
  52639. case 3:
  52640. break;
  52641. }
  52642. }
  52643. return result;
  52644. };
  52645. for (var index = 0; index < indices.length; index += 3) {
  52646. var faceVertices = new Array();
  52647. faceVertices.push(extractDecalVector3(index));
  52648. faceVertices.push(extractDecalVector3(index + 1));
  52649. faceVertices.push(extractDecalVector3(index + 2));
  52650. // Clip
  52651. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  52652. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  52653. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  52654. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  52655. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  52656. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  52657. if (faceVertices.length === 0) {
  52658. continue;
  52659. }
  52660. // Add UVs and get back to world
  52661. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  52662. var vertex = faceVertices[vIndex];
  52663. //TODO check for Int32Array | Uint32Array | Uint16Array
  52664. vertexData.indices.push(currentVertexDataIndex);
  52665. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  52666. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  52667. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  52668. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  52669. currentVertexDataIndex++;
  52670. }
  52671. }
  52672. // Return mesh
  52673. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  52674. vertexData.applyToMesh(decal);
  52675. decal.position = position.clone();
  52676. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  52677. return decal;
  52678. };
  52679. // Privates
  52680. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  52681. // extrusion geometry
  52682. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  52683. var tangents = path3D.getTangents();
  52684. var normals = path3D.getNormals();
  52685. var binormals = path3D.getBinormals();
  52686. var distances = path3D.getDistances();
  52687. var angle = 0;
  52688. var returnScale = function () { return scale !== null ? scale : 1; };
  52689. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  52690. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  52691. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  52692. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52693. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52694. for (var i = 0; i < curve.length; i++) {
  52695. var shapePath = new Array();
  52696. var angleStep = rotate(i, distances[i]);
  52697. var scaleRatio = scl(i, distances[i]);
  52698. for (var p = 0; p < shape.length; p++) {
  52699. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  52700. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  52701. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  52702. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  52703. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  52704. shapePath[p] = rotated;
  52705. }
  52706. shapePaths[index] = shapePath;
  52707. angle += angleStep;
  52708. index++;
  52709. }
  52710. // cap
  52711. var capPath = function (shapePath) {
  52712. var pointCap = Array();
  52713. var barycenter = BABYLON.Vector3.Zero();
  52714. var i;
  52715. for (i = 0; i < shapePath.length; i++) {
  52716. barycenter.addInPlace(shapePath[i]);
  52717. }
  52718. barycenter.scaleInPlace(1.0 / shapePath.length);
  52719. for (i = 0; i < shapePath.length; i++) {
  52720. pointCap.push(barycenter);
  52721. }
  52722. return pointCap;
  52723. };
  52724. switch (cap) {
  52725. case BABYLON.Mesh.NO_CAP:
  52726. break;
  52727. case BABYLON.Mesh.CAP_START:
  52728. shapePaths[0] = capPath(shapePaths[2]);
  52729. shapePaths[1] = shapePaths[2];
  52730. break;
  52731. case BABYLON.Mesh.CAP_END:
  52732. shapePaths[index] = shapePaths[index - 1];
  52733. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  52734. break;
  52735. case BABYLON.Mesh.CAP_ALL:
  52736. shapePaths[0] = capPath(shapePaths[2]);
  52737. shapePaths[1] = shapePaths[2];
  52738. shapePaths[index] = shapePaths[index - 1];
  52739. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  52740. break;
  52741. default:
  52742. break;
  52743. }
  52744. return shapePaths;
  52745. };
  52746. var path3D;
  52747. var pathArray;
  52748. if (instance) {
  52749. path3D = (instance.path3D).update(curve);
  52750. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  52751. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  52752. return instance;
  52753. }
  52754. // extruded shape creation
  52755. path3D = new BABYLON.Path3D(curve);
  52756. var newShapePaths = new Array();
  52757. cap = (cap < 0 || cap > 3) ? 0 : cap;
  52758. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  52759. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  52760. extrudedGeneric.pathArray = pathArray;
  52761. extrudedGeneric.path3D = path3D;
  52762. extrudedGeneric.cap = cap;
  52763. return extrudedGeneric;
  52764. };
  52765. return MeshBuilder;
  52766. }());
  52767. BABYLON.MeshBuilder = MeshBuilder;
  52768. })(BABYLON || (BABYLON = {}));
  52769. //# sourceMappingURL=babylon.meshBuilder.js.map
  52770. var BABYLON;
  52771. (function (BABYLON) {
  52772. var AudioEngine = /** @class */ (function () {
  52773. function AudioEngine() {
  52774. this._audioContext = null;
  52775. this._audioContextInitialized = false;
  52776. this.canUseWebAudio = false;
  52777. this.WarnedWebAudioUnsupported = false;
  52778. this.unlocked = false;
  52779. this.isMP3supported = false;
  52780. this.isOGGsupported = false;
  52781. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  52782. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  52783. this.canUseWebAudio = true;
  52784. }
  52785. var audioElem = document.createElement('audio');
  52786. try {
  52787. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  52788. this.isMP3supported = true;
  52789. }
  52790. }
  52791. catch (e) {
  52792. // protect error during capability check.
  52793. }
  52794. try {
  52795. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  52796. this.isOGGsupported = true;
  52797. }
  52798. }
  52799. catch (e) {
  52800. // protect error during capability check.
  52801. }
  52802. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  52803. this._unlockiOSaudio();
  52804. }
  52805. else {
  52806. this.unlocked = true;
  52807. }
  52808. }
  52809. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  52810. get: function () {
  52811. if (!this._audioContextInitialized) {
  52812. this._initializeAudioContext();
  52813. }
  52814. return this._audioContext;
  52815. },
  52816. enumerable: true,
  52817. configurable: true
  52818. });
  52819. AudioEngine.prototype._unlockiOSaudio = function () {
  52820. var _this = this;
  52821. var unlockaudio = function () {
  52822. if (!_this.audioContext) {
  52823. return;
  52824. }
  52825. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  52826. var source = _this.audioContext.createBufferSource();
  52827. source.buffer = buffer;
  52828. source.connect(_this.audioContext.destination);
  52829. source.start(0);
  52830. setTimeout(function () {
  52831. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  52832. _this.unlocked = true;
  52833. window.removeEventListener('touchend', unlockaudio, false);
  52834. if (_this.onAudioUnlocked) {
  52835. _this.onAudioUnlocked();
  52836. }
  52837. }
  52838. }, 0);
  52839. };
  52840. window.addEventListener('touchend', unlockaudio, false);
  52841. };
  52842. AudioEngine.prototype._initializeAudioContext = function () {
  52843. try {
  52844. if (this.canUseWebAudio) {
  52845. this._audioContext = new AudioContext();
  52846. // create a global volume gain node
  52847. this.masterGain = this._audioContext.createGain();
  52848. this.masterGain.gain.value = 1;
  52849. this.masterGain.connect(this._audioContext.destination);
  52850. this._audioContextInitialized = true;
  52851. }
  52852. }
  52853. catch (e) {
  52854. this.canUseWebAudio = false;
  52855. BABYLON.Tools.Error("Web Audio: " + e.message);
  52856. }
  52857. };
  52858. AudioEngine.prototype.dispose = function () {
  52859. if (this.canUseWebAudio && this._audioContextInitialized) {
  52860. if (this._connectedAnalyser && this._audioContext) {
  52861. this._connectedAnalyser.stopDebugCanvas();
  52862. this._connectedAnalyser.dispose();
  52863. this.masterGain.disconnect();
  52864. this.masterGain.connect(this._audioContext.destination);
  52865. this._connectedAnalyser = null;
  52866. }
  52867. this.masterGain.gain.value = 1;
  52868. }
  52869. this.WarnedWebAudioUnsupported = false;
  52870. };
  52871. AudioEngine.prototype.getGlobalVolume = function () {
  52872. if (this.canUseWebAudio && this._audioContextInitialized) {
  52873. return this.masterGain.gain.value;
  52874. }
  52875. else {
  52876. return -1;
  52877. }
  52878. };
  52879. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  52880. if (this.canUseWebAudio && this._audioContextInitialized) {
  52881. this.masterGain.gain.value = newVolume;
  52882. }
  52883. };
  52884. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  52885. if (this._connectedAnalyser) {
  52886. this._connectedAnalyser.stopDebugCanvas();
  52887. }
  52888. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  52889. this._connectedAnalyser = analyser;
  52890. this.masterGain.disconnect();
  52891. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  52892. }
  52893. };
  52894. return AudioEngine;
  52895. }());
  52896. BABYLON.AudioEngine = AudioEngine;
  52897. })(BABYLON || (BABYLON = {}));
  52898. //# sourceMappingURL=babylon.audioEngine.js.map
  52899. var BABYLON;
  52900. (function (BABYLON) {
  52901. var Sound = /** @class */ (function () {
  52902. /**
  52903. * Create a sound and attach it to a scene
  52904. * @param name Name of your sound
  52905. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  52906. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  52907. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  52908. */
  52909. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  52910. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  52911. var _this = this;
  52912. this.autoplay = false;
  52913. this.loop = false;
  52914. this.useCustomAttenuation = false;
  52915. this.spatialSound = false;
  52916. this.refDistance = 1;
  52917. this.rolloffFactor = 1;
  52918. this.maxDistance = 100;
  52919. this.distanceModel = "linear";
  52920. this._panningModel = "equalpower";
  52921. this._playbackRate = 1;
  52922. this._streaming = false;
  52923. this._startTime = 0;
  52924. this._startOffset = 0;
  52925. this._position = BABYLON.Vector3.Zero();
  52926. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  52927. this._volume = 1;
  52928. this._isReadyToPlay = false;
  52929. this.isPlaying = false;
  52930. this.isPaused = false;
  52931. this._isDirectional = false;
  52932. // Used if you'd like to create a directional sound.
  52933. // If not set, the sound will be omnidirectional
  52934. this._coneInnerAngle = 360;
  52935. this._coneOuterAngle = 360;
  52936. this._coneOuterGain = 0;
  52937. this._isOutputConnected = false;
  52938. this._urlType = "Unknown";
  52939. this.name = name;
  52940. this._scene = scene;
  52941. this._readyToPlayCallback = readyToPlayCallback;
  52942. // Default custom attenuation function is a linear attenuation
  52943. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  52944. if (currentDistance < maxDistance) {
  52945. return currentVolume * (1 - currentDistance / maxDistance);
  52946. }
  52947. else {
  52948. return 0;
  52949. }
  52950. };
  52951. if (options) {
  52952. this.autoplay = options.autoplay || false;
  52953. this.loop = options.loop || false;
  52954. // if volume === 0, we need another way to check this option
  52955. if (options.volume !== undefined) {
  52956. this._volume = options.volume;
  52957. }
  52958. this.spatialSound = options.spatialSound || false;
  52959. this.maxDistance = options.maxDistance || 100;
  52960. this.useCustomAttenuation = options.useCustomAttenuation || false;
  52961. this.rolloffFactor = options.rolloffFactor || 1;
  52962. this.refDistance = options.refDistance || 1;
  52963. this.distanceModel = options.distanceModel || "linear";
  52964. this._playbackRate = options.playbackRate || 1;
  52965. this._streaming = options.streaming || false;
  52966. }
  52967. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52968. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  52969. this._soundGain.gain.value = this._volume;
  52970. this._inputAudioNode = this._soundGain;
  52971. this._ouputAudioNode = this._soundGain;
  52972. if (this.spatialSound) {
  52973. this._createSpatialParameters();
  52974. }
  52975. this._scene.mainSoundTrack.AddSound(this);
  52976. var validParameter = true;
  52977. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  52978. if (urlOrArrayBuffer) {
  52979. if (typeof (urlOrArrayBuffer) === "string")
  52980. this._urlType = "String";
  52981. if (Array.isArray(urlOrArrayBuffer))
  52982. this._urlType = "Array";
  52983. if (urlOrArrayBuffer instanceof ArrayBuffer)
  52984. this._urlType = "ArrayBuffer";
  52985. var urls = [];
  52986. var codecSupportedFound = false;
  52987. switch (this._urlType) {
  52988. case "ArrayBuffer":
  52989. if (urlOrArrayBuffer.byteLength > 0) {
  52990. codecSupportedFound = true;
  52991. this._soundLoaded(urlOrArrayBuffer);
  52992. }
  52993. break;
  52994. case "String":
  52995. urls.push(urlOrArrayBuffer);
  52996. case "Array":
  52997. if (urls.length === 0)
  52998. urls = urlOrArrayBuffer;
  52999. // If we found a supported format, we load it immediately and stop the loop
  53000. for (var i = 0; i < urls.length; i++) {
  53001. var url = urls[i];
  53002. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  53003. codecSupportedFound = true;
  53004. }
  53005. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  53006. codecSupportedFound = true;
  53007. }
  53008. if (url.indexOf(".wav", url.length - 4) !== -1) {
  53009. codecSupportedFound = true;
  53010. }
  53011. if (url.indexOf("blob:") !== -1) {
  53012. codecSupportedFound = true;
  53013. }
  53014. if (codecSupportedFound) {
  53015. // Loading sound using XHR2
  53016. if (!this._streaming) {
  53017. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  53018. }
  53019. else {
  53020. this._htmlAudioElement = new Audio(url);
  53021. this._htmlAudioElement.controls = false;
  53022. this._htmlAudioElement.loop = this.loop;
  53023. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  53024. this._htmlAudioElement.preload = "auto";
  53025. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  53026. _this._isReadyToPlay = true;
  53027. if (_this.autoplay) {
  53028. _this.play();
  53029. }
  53030. if (_this._readyToPlayCallback) {
  53031. _this._readyToPlayCallback();
  53032. }
  53033. });
  53034. document.body.appendChild(this._htmlAudioElement);
  53035. }
  53036. break;
  53037. }
  53038. }
  53039. break;
  53040. default:
  53041. validParameter = false;
  53042. break;
  53043. }
  53044. if (!validParameter) {
  53045. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  53046. }
  53047. else {
  53048. if (!codecSupportedFound) {
  53049. this._isReadyToPlay = true;
  53050. // Simulating a ready to play event to avoid breaking code path
  53051. if (this._readyToPlayCallback) {
  53052. window.setTimeout(function () {
  53053. if (_this._readyToPlayCallback) {
  53054. _this._readyToPlayCallback();
  53055. }
  53056. }, 1000);
  53057. }
  53058. }
  53059. }
  53060. }
  53061. }
  53062. else {
  53063. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  53064. this._scene.mainSoundTrack.AddSound(this);
  53065. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  53066. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  53067. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  53068. }
  53069. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  53070. if (this._readyToPlayCallback) {
  53071. window.setTimeout(function () {
  53072. if (_this._readyToPlayCallback) {
  53073. _this._readyToPlayCallback();
  53074. }
  53075. }, 1000);
  53076. }
  53077. }
  53078. }
  53079. Sound.prototype.dispose = function () {
  53080. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  53081. if (this.isPlaying) {
  53082. this.stop();
  53083. }
  53084. this._isReadyToPlay = false;
  53085. if (this.soundTrackId === -1) {
  53086. this._scene.mainSoundTrack.RemoveSound(this);
  53087. }
  53088. else {
  53089. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  53090. }
  53091. if (this._soundGain) {
  53092. this._soundGain.disconnect();
  53093. this._soundGain = null;
  53094. }
  53095. if (this._soundPanner) {
  53096. this._soundPanner.disconnect();
  53097. this._soundPanner = null;
  53098. }
  53099. if (this._soundSource) {
  53100. this._soundSource.disconnect();
  53101. this._soundSource = null;
  53102. }
  53103. this._audioBuffer = null;
  53104. if (this._htmlAudioElement) {
  53105. this._htmlAudioElement.pause();
  53106. this._htmlAudioElement.src = "";
  53107. document.body.removeChild(this._htmlAudioElement);
  53108. }
  53109. if (this._connectedMesh && this._registerFunc) {
  53110. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53111. this._connectedMesh = null;
  53112. }
  53113. }
  53114. };
  53115. Sound.prototype.isReady = function () {
  53116. return this._isReadyToPlay;
  53117. };
  53118. Sound.prototype._soundLoaded = function (audioData) {
  53119. var _this = this;
  53120. if (!BABYLON.Engine.audioEngine.audioContext) {
  53121. return;
  53122. }
  53123. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  53124. _this._audioBuffer = buffer;
  53125. _this._isReadyToPlay = true;
  53126. if (_this.autoplay) {
  53127. _this.play();
  53128. }
  53129. if (_this._readyToPlayCallback) {
  53130. _this._readyToPlayCallback();
  53131. }
  53132. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  53133. };
  53134. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  53135. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53136. this._audioBuffer = audioBuffer;
  53137. this._isReadyToPlay = true;
  53138. }
  53139. };
  53140. Sound.prototype.updateOptions = function (options) {
  53141. if (options) {
  53142. this.loop = options.loop || this.loop;
  53143. this.maxDistance = options.maxDistance || this.maxDistance;
  53144. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  53145. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  53146. this.refDistance = options.refDistance || this.refDistance;
  53147. this.distanceModel = options.distanceModel || this.distanceModel;
  53148. this._playbackRate = options.playbackRate || this._playbackRate;
  53149. this._updateSpatialParameters();
  53150. if (this.isPlaying) {
  53151. if (this._streaming) {
  53152. this._htmlAudioElement.playbackRate = this._playbackRate;
  53153. }
  53154. else {
  53155. if (this._soundSource) {
  53156. this._soundSource.playbackRate.value = this._playbackRate;
  53157. }
  53158. }
  53159. }
  53160. }
  53161. };
  53162. Sound.prototype._createSpatialParameters = function () {
  53163. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53164. if (this._scene.headphone) {
  53165. this._panningModel = "HRTF";
  53166. }
  53167. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  53168. this._updateSpatialParameters();
  53169. this._soundPanner.connect(this._ouputAudioNode);
  53170. this._inputAudioNode = this._soundPanner;
  53171. }
  53172. };
  53173. Sound.prototype._updateSpatialParameters = function () {
  53174. if (this.spatialSound && this._soundPanner) {
  53175. if (this.useCustomAttenuation) {
  53176. // Tricks to disable in a way embedded Web Audio attenuation
  53177. this._soundPanner.distanceModel = "linear";
  53178. this._soundPanner.maxDistance = Number.MAX_VALUE;
  53179. this._soundPanner.refDistance = 1;
  53180. this._soundPanner.rolloffFactor = 1;
  53181. this._soundPanner.panningModel = this._panningModel;
  53182. }
  53183. else {
  53184. this._soundPanner.distanceModel = this.distanceModel;
  53185. this._soundPanner.maxDistance = this.maxDistance;
  53186. this._soundPanner.refDistance = this.refDistance;
  53187. this._soundPanner.rolloffFactor = this.rolloffFactor;
  53188. this._soundPanner.panningModel = this._panningModel;
  53189. }
  53190. }
  53191. };
  53192. Sound.prototype.switchPanningModelToHRTF = function () {
  53193. this._panningModel = "HRTF";
  53194. this._switchPanningModel();
  53195. };
  53196. Sound.prototype.switchPanningModelToEqualPower = function () {
  53197. this._panningModel = "equalpower";
  53198. this._switchPanningModel();
  53199. };
  53200. Sound.prototype._switchPanningModel = function () {
  53201. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53202. this._soundPanner.panningModel = this._panningModel;
  53203. }
  53204. };
  53205. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  53206. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53207. if (this._isOutputConnected) {
  53208. this._ouputAudioNode.disconnect();
  53209. }
  53210. this._ouputAudioNode.connect(soundTrackAudioNode);
  53211. this._isOutputConnected = true;
  53212. }
  53213. };
  53214. /**
  53215. * Transform this sound into a directional source
  53216. * @param coneInnerAngle Size of the inner cone in degree
  53217. * @param coneOuterAngle Size of the outer cone in degree
  53218. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  53219. */
  53220. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  53221. if (coneOuterAngle < coneInnerAngle) {
  53222. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  53223. return;
  53224. }
  53225. this._coneInnerAngle = coneInnerAngle;
  53226. this._coneOuterAngle = coneOuterAngle;
  53227. this._coneOuterGain = coneOuterGain;
  53228. this._isDirectional = true;
  53229. if (this.isPlaying && this.loop) {
  53230. this.stop();
  53231. this.play();
  53232. }
  53233. };
  53234. Sound.prototype.setPosition = function (newPosition) {
  53235. this._position = newPosition;
  53236. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53237. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53238. }
  53239. };
  53240. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  53241. this._localDirection = newLocalDirection;
  53242. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  53243. this._updateDirection();
  53244. }
  53245. };
  53246. Sound.prototype._updateDirection = function () {
  53247. if (!this._connectedMesh || !this._soundPanner) {
  53248. return;
  53249. }
  53250. var mat = this._connectedMesh.getWorldMatrix();
  53251. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  53252. direction.normalize();
  53253. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  53254. };
  53255. Sound.prototype.updateDistanceFromListener = function () {
  53256. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  53257. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  53258. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  53259. }
  53260. };
  53261. Sound.prototype.setAttenuationFunction = function (callback) {
  53262. this._customAttenuationFunction = callback;
  53263. };
  53264. /**
  53265. * Play the sound
  53266. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  53267. * @param offset (optional) Start the sound setting it at a specific time
  53268. */
  53269. Sound.prototype.play = function (time, offset) {
  53270. var _this = this;
  53271. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  53272. try {
  53273. if (this._startOffset < 0) {
  53274. time = -this._startOffset;
  53275. this._startOffset = 0;
  53276. }
  53277. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53278. if (!this._soundSource || !this._streamingSource) {
  53279. if (this.spatialSound && this._soundPanner) {
  53280. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53281. if (this._isDirectional) {
  53282. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  53283. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  53284. this._soundPanner.coneOuterGain = this._coneOuterGain;
  53285. if (this._connectedMesh) {
  53286. this._updateDirection();
  53287. }
  53288. else {
  53289. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  53290. }
  53291. }
  53292. }
  53293. }
  53294. if (this._streaming) {
  53295. if (!this._streamingSource) {
  53296. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  53297. this._htmlAudioElement.onended = function () { _this._onended(); };
  53298. this._htmlAudioElement.playbackRate = this._playbackRate;
  53299. }
  53300. this._streamingSource.disconnect();
  53301. this._streamingSource.connect(this._inputAudioNode);
  53302. this._htmlAudioElement.play();
  53303. }
  53304. else {
  53305. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  53306. this._soundSource.buffer = this._audioBuffer;
  53307. this._soundSource.connect(this._inputAudioNode);
  53308. this._soundSource.loop = this.loop;
  53309. this._soundSource.playbackRate.value = this._playbackRate;
  53310. this._soundSource.onended = function () { _this._onended(); };
  53311. if (this._soundSource.buffer) {
  53312. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  53313. }
  53314. }
  53315. this._startTime = startTime;
  53316. this.isPlaying = true;
  53317. this.isPaused = false;
  53318. }
  53319. catch (ex) {
  53320. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  53321. }
  53322. }
  53323. };
  53324. Sound.prototype._onended = function () {
  53325. this.isPlaying = false;
  53326. if (this.onended) {
  53327. this.onended();
  53328. }
  53329. };
  53330. /**
  53331. * Stop the sound
  53332. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  53333. */
  53334. Sound.prototype.stop = function (time) {
  53335. if (this.isPlaying) {
  53336. if (this._streaming) {
  53337. this._htmlAudioElement.pause();
  53338. // Test needed for Firefox or it will generate an Invalid State Error
  53339. if (this._htmlAudioElement.currentTime > 0) {
  53340. this._htmlAudioElement.currentTime = 0;
  53341. }
  53342. }
  53343. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  53344. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53345. this._soundSource.stop(stopTime);
  53346. this._soundSource.onended = function () { };
  53347. if (!this.isPaused) {
  53348. this._startOffset = 0;
  53349. }
  53350. }
  53351. this.isPlaying = false;
  53352. }
  53353. };
  53354. Sound.prototype.pause = function () {
  53355. if (this.isPlaying) {
  53356. this.isPaused = true;
  53357. if (this._streaming) {
  53358. this._htmlAudioElement.pause();
  53359. }
  53360. else if (BABYLON.Engine.audioEngine.audioContext) {
  53361. this.stop(0);
  53362. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  53363. }
  53364. }
  53365. };
  53366. Sound.prototype.setVolume = function (newVolume, time) {
  53367. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  53368. if (time && BABYLON.Engine.audioEngine.audioContext) {
  53369. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  53370. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  53371. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  53372. }
  53373. else {
  53374. this._soundGain.gain.value = newVolume;
  53375. }
  53376. }
  53377. this._volume = newVolume;
  53378. };
  53379. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  53380. this._playbackRate = newPlaybackRate;
  53381. if (this.isPlaying) {
  53382. if (this._streaming) {
  53383. this._htmlAudioElement.playbackRate = this._playbackRate;
  53384. }
  53385. else if (this._soundSource) {
  53386. this._soundSource.playbackRate.value = this._playbackRate;
  53387. }
  53388. }
  53389. };
  53390. Sound.prototype.getVolume = function () {
  53391. return this._volume;
  53392. };
  53393. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  53394. var _this = this;
  53395. if (this._connectedMesh && this._registerFunc) {
  53396. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53397. this._registerFunc = null;
  53398. }
  53399. this._connectedMesh = meshToConnectTo;
  53400. if (!this.spatialSound) {
  53401. this.spatialSound = true;
  53402. this._createSpatialParameters();
  53403. if (this.isPlaying && this.loop) {
  53404. this.stop();
  53405. this.play();
  53406. }
  53407. }
  53408. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  53409. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  53410. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  53411. };
  53412. Sound.prototype.detachFromMesh = function () {
  53413. if (this._connectedMesh && this._registerFunc) {
  53414. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53415. this._registerFunc = null;
  53416. this._connectedMesh = null;
  53417. }
  53418. };
  53419. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  53420. if (!node.getBoundingInfo) {
  53421. return;
  53422. }
  53423. var mesh = node;
  53424. var boundingInfo = mesh.getBoundingInfo();
  53425. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  53426. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  53427. this._updateDirection();
  53428. }
  53429. };
  53430. Sound.prototype.clone = function () {
  53431. var _this = this;
  53432. if (!this._streaming) {
  53433. var setBufferAndRun = function () {
  53434. if (_this._isReadyToPlay) {
  53435. clonedSound._audioBuffer = _this.getAudioBuffer();
  53436. clonedSound._isReadyToPlay = true;
  53437. if (clonedSound.autoplay) {
  53438. clonedSound.play();
  53439. }
  53440. }
  53441. else {
  53442. window.setTimeout(setBufferAndRun, 300);
  53443. }
  53444. };
  53445. var currentOptions = {
  53446. autoplay: this.autoplay, loop: this.loop,
  53447. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  53448. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  53449. refDistance: this.refDistance, distanceModel: this.distanceModel
  53450. };
  53451. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  53452. if (this.useCustomAttenuation) {
  53453. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  53454. }
  53455. clonedSound.setPosition(this._position);
  53456. clonedSound.setPlaybackRate(this._playbackRate);
  53457. setBufferAndRun();
  53458. return clonedSound;
  53459. }
  53460. else {
  53461. return null;
  53462. }
  53463. };
  53464. Sound.prototype.getAudioBuffer = function () {
  53465. return this._audioBuffer;
  53466. };
  53467. Sound.prototype.serialize = function () {
  53468. var serializationObject = {
  53469. name: this.name,
  53470. url: this.name,
  53471. autoplay: this.autoplay,
  53472. loop: this.loop,
  53473. volume: this._volume,
  53474. spatialSound: this.spatialSound,
  53475. maxDistance: this.maxDistance,
  53476. rolloffFactor: this.rolloffFactor,
  53477. refDistance: this.refDistance,
  53478. distanceModel: this.distanceModel,
  53479. playbackRate: this._playbackRate,
  53480. panningModel: this._panningModel,
  53481. soundTrackId: this.soundTrackId
  53482. };
  53483. if (this.spatialSound) {
  53484. if (this._connectedMesh)
  53485. serializationObject.connectedMeshId = this._connectedMesh.id;
  53486. serializationObject.position = this._position.asArray();
  53487. serializationObject.refDistance = this.refDistance;
  53488. serializationObject.distanceModel = this.distanceModel;
  53489. serializationObject.isDirectional = this._isDirectional;
  53490. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  53491. serializationObject.coneInnerAngle = this._coneInnerAngle;
  53492. serializationObject.coneOuterAngle = this._coneOuterAngle;
  53493. serializationObject.coneOuterGain = this._coneOuterGain;
  53494. }
  53495. return serializationObject;
  53496. };
  53497. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  53498. var soundName = parsedSound.name;
  53499. var soundUrl;
  53500. if (parsedSound.url) {
  53501. soundUrl = rootUrl + parsedSound.url;
  53502. }
  53503. else {
  53504. soundUrl = rootUrl + soundName;
  53505. }
  53506. var options = {
  53507. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  53508. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  53509. rolloffFactor: parsedSound.rolloffFactor,
  53510. refDistance: parsedSound.refDistance,
  53511. distanceModel: parsedSound.distanceModel,
  53512. playbackRate: parsedSound.playbackRate
  53513. };
  53514. var newSound;
  53515. if (!sourceSound) {
  53516. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  53517. scene._addPendingData(newSound);
  53518. }
  53519. else {
  53520. var setBufferAndRun = function () {
  53521. if (sourceSound._isReadyToPlay) {
  53522. newSound._audioBuffer = sourceSound.getAudioBuffer();
  53523. newSound._isReadyToPlay = true;
  53524. if (newSound.autoplay) {
  53525. newSound.play();
  53526. }
  53527. }
  53528. else {
  53529. window.setTimeout(setBufferAndRun, 300);
  53530. }
  53531. };
  53532. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  53533. setBufferAndRun();
  53534. }
  53535. if (parsedSound.position) {
  53536. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  53537. newSound.setPosition(soundPosition);
  53538. }
  53539. if (parsedSound.isDirectional) {
  53540. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  53541. if (parsedSound.localDirectionToMesh) {
  53542. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  53543. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  53544. }
  53545. }
  53546. if (parsedSound.connectedMeshId) {
  53547. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  53548. if (connectedMesh) {
  53549. newSound.attachToMesh(connectedMesh);
  53550. }
  53551. }
  53552. return newSound;
  53553. };
  53554. return Sound;
  53555. }());
  53556. BABYLON.Sound = Sound;
  53557. })(BABYLON || (BABYLON = {}));
  53558. //# sourceMappingURL=babylon.sound.js.map
  53559. var BABYLON;
  53560. (function (BABYLON) {
  53561. var SoundTrack = /** @class */ (function () {
  53562. function SoundTrack(scene, options) {
  53563. this.id = -1;
  53564. this._isMainTrack = false;
  53565. this._isInitialized = false;
  53566. this._scene = scene;
  53567. this.soundCollection = new Array();
  53568. this._options = options;
  53569. if (!this._isMainTrack) {
  53570. this._scene.soundTracks.push(this);
  53571. this.id = this._scene.soundTracks.length - 1;
  53572. }
  53573. }
  53574. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  53575. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53576. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  53577. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  53578. if (this._options) {
  53579. if (this._options.volume) {
  53580. this._outputAudioNode.gain.value = this._options.volume;
  53581. }
  53582. if (this._options.mainTrack) {
  53583. this._isMainTrack = this._options.mainTrack;
  53584. }
  53585. }
  53586. this._isInitialized = true;
  53587. }
  53588. };
  53589. SoundTrack.prototype.dispose = function () {
  53590. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53591. if (this._connectedAnalyser) {
  53592. this._connectedAnalyser.stopDebugCanvas();
  53593. }
  53594. while (this.soundCollection.length) {
  53595. this.soundCollection[0].dispose();
  53596. }
  53597. if (this._outputAudioNode) {
  53598. this._outputAudioNode.disconnect();
  53599. }
  53600. this._outputAudioNode = null;
  53601. }
  53602. };
  53603. SoundTrack.prototype.AddSound = function (sound) {
  53604. if (!this._isInitialized) {
  53605. this._initializeSoundTrackAudioGraph();
  53606. }
  53607. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53608. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  53609. }
  53610. if (sound.soundTrackId) {
  53611. if (sound.soundTrackId === -1) {
  53612. this._scene.mainSoundTrack.RemoveSound(sound);
  53613. }
  53614. else {
  53615. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  53616. }
  53617. }
  53618. this.soundCollection.push(sound);
  53619. sound.soundTrackId = this.id;
  53620. };
  53621. SoundTrack.prototype.RemoveSound = function (sound) {
  53622. var index = this.soundCollection.indexOf(sound);
  53623. if (index !== -1) {
  53624. this.soundCollection.splice(index, 1);
  53625. }
  53626. };
  53627. SoundTrack.prototype.setVolume = function (newVolume) {
  53628. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53629. this._outputAudioNode.gain.value = newVolume;
  53630. }
  53631. };
  53632. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  53633. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53634. for (var i = 0; i < this.soundCollection.length; i++) {
  53635. this.soundCollection[i].switchPanningModelToHRTF();
  53636. }
  53637. }
  53638. };
  53639. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  53640. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53641. for (var i = 0; i < this.soundCollection.length; i++) {
  53642. this.soundCollection[i].switchPanningModelToEqualPower();
  53643. }
  53644. }
  53645. };
  53646. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  53647. if (this._connectedAnalyser) {
  53648. this._connectedAnalyser.stopDebugCanvas();
  53649. }
  53650. this._connectedAnalyser = analyser;
  53651. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53652. this._outputAudioNode.disconnect();
  53653. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  53654. }
  53655. };
  53656. return SoundTrack;
  53657. }());
  53658. BABYLON.SoundTrack = SoundTrack;
  53659. })(BABYLON || (BABYLON = {}));
  53660. //# sourceMappingURL=babylon.soundtrack.js.map
  53661. var BABYLON;
  53662. (function (BABYLON) {
  53663. var Analyser = /** @class */ (function () {
  53664. function Analyser(scene) {
  53665. this.SMOOTHING = 0.75;
  53666. this.FFT_SIZE = 512;
  53667. this.BARGRAPHAMPLITUDE = 256;
  53668. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  53669. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  53670. this._scene = scene;
  53671. this._audioEngine = BABYLON.Engine.audioEngine;
  53672. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  53673. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  53674. this._webAudioAnalyser.minDecibels = -140;
  53675. this._webAudioAnalyser.maxDecibels = 0;
  53676. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53677. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53678. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  53679. }
  53680. }
  53681. Analyser.prototype.getFrequencyBinCount = function () {
  53682. if (this._audioEngine.canUseWebAudio) {
  53683. return this._webAudioAnalyser.frequencyBinCount;
  53684. }
  53685. else {
  53686. return 0;
  53687. }
  53688. };
  53689. Analyser.prototype.getByteFrequencyData = function () {
  53690. if (this._audioEngine.canUseWebAudio) {
  53691. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53692. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53693. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  53694. }
  53695. return this._byteFreqs;
  53696. };
  53697. Analyser.prototype.getByteTimeDomainData = function () {
  53698. if (this._audioEngine.canUseWebAudio) {
  53699. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53700. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53701. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  53702. }
  53703. return this._byteTime;
  53704. };
  53705. Analyser.prototype.getFloatFrequencyData = function () {
  53706. if (this._audioEngine.canUseWebAudio) {
  53707. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53708. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53709. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  53710. }
  53711. return this._floatFreqs;
  53712. };
  53713. Analyser.prototype.drawDebugCanvas = function () {
  53714. var _this = this;
  53715. if (this._audioEngine.canUseWebAudio) {
  53716. if (!this._debugCanvas) {
  53717. this._debugCanvas = document.createElement("canvas");
  53718. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  53719. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  53720. this._debugCanvas.style.position = "absolute";
  53721. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  53722. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  53723. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  53724. document.body.appendChild(this._debugCanvas);
  53725. this._registerFunc = function () {
  53726. _this.drawDebugCanvas();
  53727. };
  53728. this._scene.registerBeforeRender(this._registerFunc);
  53729. }
  53730. if (this._registerFunc && this._debugCanvasContext) {
  53731. var workingArray = this.getByteFrequencyData();
  53732. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  53733. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  53734. // Draw the frequency domain chart.
  53735. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  53736. var value = workingArray[i];
  53737. var percent = value / this.BARGRAPHAMPLITUDE;
  53738. var height = this.DEBUGCANVASSIZE.height * percent;
  53739. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  53740. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  53741. var hue = i / this.getFrequencyBinCount() * 360;
  53742. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  53743. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  53744. }
  53745. }
  53746. }
  53747. };
  53748. Analyser.prototype.stopDebugCanvas = function () {
  53749. if (this._debugCanvas) {
  53750. if (this._registerFunc) {
  53751. this._scene.unregisterBeforeRender(this._registerFunc);
  53752. this._registerFunc = null;
  53753. }
  53754. document.body.removeChild(this._debugCanvas);
  53755. this._debugCanvas = null;
  53756. this._debugCanvasContext = null;
  53757. }
  53758. };
  53759. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  53760. if (this._audioEngine.canUseWebAudio) {
  53761. inputAudioNode.connect(this._webAudioAnalyser);
  53762. this._webAudioAnalyser.connect(outputAudioNode);
  53763. }
  53764. };
  53765. Analyser.prototype.dispose = function () {
  53766. if (this._audioEngine.canUseWebAudio) {
  53767. this._webAudioAnalyser.disconnect();
  53768. }
  53769. };
  53770. return Analyser;
  53771. }());
  53772. BABYLON.Analyser = Analyser;
  53773. })(BABYLON || (BABYLON = {}));
  53774. //# sourceMappingURL=babylon.analyser.js.map
  53775. var BABYLON;
  53776. (function (BABYLON) {
  53777. var CubeTexture = /** @class */ (function (_super) {
  53778. __extends(CubeTexture, _super);
  53779. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  53780. if (extensions === void 0) { extensions = null; }
  53781. if (noMipmap === void 0) { noMipmap = false; }
  53782. if (files === void 0) { files = null; }
  53783. if (onLoad === void 0) { onLoad = null; }
  53784. if (onError === void 0) { onError = null; }
  53785. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  53786. if (prefiltered === void 0) { prefiltered = false; }
  53787. if (forcedExtension === void 0) { forcedExtension = null; }
  53788. var _this = _super.call(this, scene) || this;
  53789. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  53790. _this.name = rootUrl;
  53791. _this.url = rootUrl;
  53792. _this._noMipmap = noMipmap;
  53793. _this.hasAlpha = false;
  53794. _this._format = format;
  53795. _this._prefiltered = prefiltered;
  53796. _this.isCube = true;
  53797. _this._textureMatrix = BABYLON.Matrix.Identity();
  53798. if (prefiltered) {
  53799. _this.gammaSpace = false;
  53800. }
  53801. if (!rootUrl && !files) {
  53802. return _this;
  53803. }
  53804. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  53805. var lastDot = rootUrl.lastIndexOf(".");
  53806. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  53807. var isDDS = (extension === ".dds");
  53808. if (!files) {
  53809. if (!isDDS && !extensions) {
  53810. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  53811. }
  53812. files = [];
  53813. if (extensions) {
  53814. for (var index = 0; index < extensions.length; index++) {
  53815. files.push(rootUrl + extensions[index]);
  53816. }
  53817. }
  53818. }
  53819. _this._files = files;
  53820. if (!_this._texture) {
  53821. if (!scene.useDelayedTextureLoading) {
  53822. if (prefiltered) {
  53823. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  53824. }
  53825. else {
  53826. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  53827. }
  53828. }
  53829. else {
  53830. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  53831. }
  53832. }
  53833. else if (onLoad) {
  53834. if (_this._texture.isReady) {
  53835. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  53836. }
  53837. else {
  53838. _this._texture.onLoadedObservable.add(onLoad);
  53839. }
  53840. }
  53841. return _this;
  53842. }
  53843. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  53844. return new CubeTexture("", scene, null, noMipmap, files);
  53845. };
  53846. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  53847. if (forcedExtension === void 0) { forcedExtension = null; }
  53848. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  53849. };
  53850. // Methods
  53851. CubeTexture.prototype.delayLoad = function () {
  53852. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  53853. return;
  53854. }
  53855. var scene = this.getScene();
  53856. if (!scene) {
  53857. return;
  53858. }
  53859. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  53860. this._texture = this._getFromCache(this.url, this._noMipmap);
  53861. if (!this._texture) {
  53862. if (this._prefiltered) {
  53863. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  53864. }
  53865. else {
  53866. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  53867. }
  53868. }
  53869. };
  53870. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  53871. return this._textureMatrix;
  53872. };
  53873. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  53874. this._textureMatrix = value;
  53875. };
  53876. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  53877. var texture = BABYLON.SerializationHelper.Parse(function () {
  53878. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  53879. }, parsedTexture, scene);
  53880. // Animations
  53881. if (parsedTexture.animations) {
  53882. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  53883. var parsedAnimation = parsedTexture.animations[animationIndex];
  53884. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53885. }
  53886. }
  53887. return texture;
  53888. };
  53889. CubeTexture.prototype.clone = function () {
  53890. var _this = this;
  53891. return BABYLON.SerializationHelper.Clone(function () {
  53892. var scene = _this.getScene();
  53893. if (!scene) {
  53894. return _this;
  53895. }
  53896. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  53897. }, this);
  53898. };
  53899. return CubeTexture;
  53900. }(BABYLON.BaseTexture));
  53901. BABYLON.CubeTexture = CubeTexture;
  53902. })(BABYLON || (BABYLON = {}));
  53903. //# sourceMappingURL=babylon.cubeTexture.js.map
  53904. var BABYLON;
  53905. (function (BABYLON) {
  53906. var RenderTargetTexture = /** @class */ (function (_super) {
  53907. __extends(RenderTargetTexture, _super);
  53908. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  53909. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  53910. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53911. if (isCube === void 0) { isCube = false; }
  53912. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53913. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  53914. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  53915. if (isMulti === void 0) { isMulti = false; }
  53916. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  53917. _this.isCube = isCube;
  53918. /**
  53919. * Use this list to define the list of mesh you want to render.
  53920. */
  53921. _this.renderList = new Array();
  53922. _this.renderParticles = true;
  53923. _this.renderSprites = false;
  53924. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  53925. _this.ignoreCameraViewport = false;
  53926. // Events
  53927. /**
  53928. * An event triggered when the texture is unbind.
  53929. * @type {BABYLON.Observable}
  53930. */
  53931. _this.onBeforeBindObservable = new BABYLON.Observable();
  53932. /**
  53933. * An event triggered when the texture is unbind.
  53934. * @type {BABYLON.Observable}
  53935. */
  53936. _this.onAfterUnbindObservable = new BABYLON.Observable();
  53937. /**
  53938. * An event triggered before rendering the texture
  53939. * @type {BABYLON.Observable}
  53940. */
  53941. _this.onBeforeRenderObservable = new BABYLON.Observable();
  53942. /**
  53943. * An event triggered after rendering the texture
  53944. * @type {BABYLON.Observable}
  53945. */
  53946. _this.onAfterRenderObservable = new BABYLON.Observable();
  53947. /**
  53948. * An event triggered after the texture clear
  53949. * @type {BABYLON.Observable}
  53950. */
  53951. _this.onClearObservable = new BABYLON.Observable();
  53952. _this._currentRefreshId = -1;
  53953. _this._refreshRate = 1;
  53954. _this._samples = 1;
  53955. scene = _this.getScene();
  53956. if (!scene) {
  53957. return _this;
  53958. }
  53959. _this._engine = scene.getEngine();
  53960. _this.name = name;
  53961. _this.isRenderTarget = true;
  53962. _this._initialSizeParameter = size;
  53963. _this._processSizeParameter(size);
  53964. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  53965. });
  53966. _this._generateMipMaps = generateMipMaps ? true : false;
  53967. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  53968. // Rendering groups
  53969. _this._renderingManager = new BABYLON.RenderingManager(scene);
  53970. if (isMulti) {
  53971. return _this;
  53972. }
  53973. _this._renderTargetOptions = {
  53974. generateMipMaps: generateMipMaps,
  53975. type: type,
  53976. samplingMode: samplingMode,
  53977. generateDepthBuffer: generateDepthBuffer,
  53978. generateStencilBuffer: generateStencilBuffer
  53979. };
  53980. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  53981. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53982. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53983. }
  53984. if (isCube) {
  53985. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  53986. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  53987. _this._textureMatrix = BABYLON.Matrix.Identity();
  53988. }
  53989. else {
  53990. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  53991. }
  53992. return _this;
  53993. }
  53994. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  53995. get: function () {
  53996. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  53997. },
  53998. enumerable: true,
  53999. configurable: true
  54000. });
  54001. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  54002. get: function () {
  54003. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  54004. },
  54005. enumerable: true,
  54006. configurable: true
  54007. });
  54008. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  54009. get: function () {
  54010. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  54011. },
  54012. enumerable: true,
  54013. configurable: true
  54014. });
  54015. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  54016. set: function (callback) {
  54017. if (this._onAfterUnbindObserver) {
  54018. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  54019. }
  54020. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  54021. },
  54022. enumerable: true,
  54023. configurable: true
  54024. });
  54025. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  54026. set: function (callback) {
  54027. if (this._onBeforeRenderObserver) {
  54028. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  54029. }
  54030. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  54031. },
  54032. enumerable: true,
  54033. configurable: true
  54034. });
  54035. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  54036. set: function (callback) {
  54037. if (this._onAfterRenderObserver) {
  54038. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  54039. }
  54040. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  54041. },
  54042. enumerable: true,
  54043. configurable: true
  54044. });
  54045. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  54046. set: function (callback) {
  54047. if (this._onClearObserver) {
  54048. this.onClearObservable.remove(this._onClearObserver);
  54049. }
  54050. this._onClearObserver = this.onClearObservable.add(callback);
  54051. },
  54052. enumerable: true,
  54053. configurable: true
  54054. });
  54055. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  54056. get: function () {
  54057. return this._renderTargetOptions;
  54058. },
  54059. enumerable: true,
  54060. configurable: true
  54061. });
  54062. RenderTargetTexture.prototype._onRatioRescale = function () {
  54063. if (this._sizeRatio) {
  54064. this.resize(this._initialSizeParameter);
  54065. }
  54066. };
  54067. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  54068. if (size.ratio) {
  54069. this._sizeRatio = size.ratio;
  54070. this._size = {
  54071. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  54072. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  54073. };
  54074. }
  54075. else {
  54076. this._size = size;
  54077. }
  54078. };
  54079. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  54080. get: function () {
  54081. return this._samples;
  54082. },
  54083. set: function (value) {
  54084. if (this._samples === value) {
  54085. return;
  54086. }
  54087. var scene = this.getScene();
  54088. if (!scene) {
  54089. return;
  54090. }
  54091. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  54092. },
  54093. enumerable: true,
  54094. configurable: true
  54095. });
  54096. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  54097. this._currentRefreshId = -1;
  54098. };
  54099. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  54100. get: function () {
  54101. return this._refreshRate;
  54102. },
  54103. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54104. set: function (value) {
  54105. this._refreshRate = value;
  54106. this.resetRefreshCounter();
  54107. },
  54108. enumerable: true,
  54109. configurable: true
  54110. });
  54111. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  54112. if (!this._postProcessManager) {
  54113. var scene = this.getScene();
  54114. if (!scene) {
  54115. return;
  54116. }
  54117. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  54118. this._postProcesses = new Array();
  54119. }
  54120. this._postProcesses.push(postProcess);
  54121. this._postProcesses[0].autoClear = false;
  54122. };
  54123. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  54124. if (!this._postProcesses) {
  54125. return;
  54126. }
  54127. if (dispose) {
  54128. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  54129. var postProcess = _a[_i];
  54130. postProcess.dispose();
  54131. }
  54132. }
  54133. this._postProcesses = [];
  54134. };
  54135. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  54136. if (!this._postProcesses) {
  54137. return;
  54138. }
  54139. var index = this._postProcesses.indexOf(postProcess);
  54140. if (index === -1) {
  54141. return;
  54142. }
  54143. this._postProcesses.splice(index, 1);
  54144. if (this._postProcesses.length > 0) {
  54145. this._postProcesses[0].autoClear = false;
  54146. }
  54147. };
  54148. RenderTargetTexture.prototype._shouldRender = function () {
  54149. if (this._currentRefreshId === -1) {
  54150. this._currentRefreshId = 1;
  54151. return true;
  54152. }
  54153. if (this.refreshRate === this._currentRefreshId) {
  54154. this._currentRefreshId = 1;
  54155. return true;
  54156. }
  54157. this._currentRefreshId++;
  54158. return false;
  54159. };
  54160. RenderTargetTexture.prototype.getRenderSize = function () {
  54161. if (this._size.width) {
  54162. return this._size.width;
  54163. }
  54164. return this._size;
  54165. };
  54166. RenderTargetTexture.prototype.getRenderWidth = function () {
  54167. if (this._size.width) {
  54168. return this._size.width;
  54169. }
  54170. return this._size;
  54171. };
  54172. RenderTargetTexture.prototype.getRenderHeight = function () {
  54173. if (this._size.width) {
  54174. return this._size.height;
  54175. }
  54176. return this._size;
  54177. };
  54178. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  54179. get: function () {
  54180. return true;
  54181. },
  54182. enumerable: true,
  54183. configurable: true
  54184. });
  54185. RenderTargetTexture.prototype.scale = function (ratio) {
  54186. var newSize = this.getRenderSize() * ratio;
  54187. this.resize(newSize);
  54188. };
  54189. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  54190. if (this.isCube) {
  54191. return this._textureMatrix;
  54192. }
  54193. return _super.prototype.getReflectionTextureMatrix.call(this);
  54194. };
  54195. RenderTargetTexture.prototype.resize = function (size) {
  54196. this.releaseInternalTexture();
  54197. var scene = this.getScene();
  54198. if (!scene) {
  54199. return;
  54200. }
  54201. this._processSizeParameter(size);
  54202. if (this.isCube) {
  54203. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  54204. }
  54205. else {
  54206. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  54207. }
  54208. };
  54209. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  54210. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  54211. if (dumpForDebug === void 0) { dumpForDebug = false; }
  54212. var scene = this.getScene();
  54213. if (!scene) {
  54214. return;
  54215. }
  54216. var engine = scene.getEngine();
  54217. if (this.useCameraPostProcesses !== undefined) {
  54218. useCameraPostProcess = this.useCameraPostProcesses;
  54219. }
  54220. if (this._waitingRenderList) {
  54221. this.renderList = [];
  54222. for (var index = 0; index < this._waitingRenderList.length; index++) {
  54223. var id = this._waitingRenderList[index];
  54224. var mesh_1 = scene.getMeshByID(id);
  54225. if (mesh_1) {
  54226. this.renderList.push(mesh_1);
  54227. }
  54228. }
  54229. delete this._waitingRenderList;
  54230. }
  54231. // Is predicate defined?
  54232. if (this.renderListPredicate) {
  54233. if (this.renderList) {
  54234. this.renderList.splice(0); // Clear previous renderList
  54235. }
  54236. else {
  54237. this.renderList = [];
  54238. }
  54239. var scene = this.getScene();
  54240. if (!scene) {
  54241. return;
  54242. }
  54243. var sceneMeshes = scene.meshes;
  54244. for (var index = 0; index < sceneMeshes.length; index++) {
  54245. var mesh = sceneMeshes[index];
  54246. if (this.renderListPredicate(mesh)) {
  54247. this.renderList.push(mesh);
  54248. }
  54249. }
  54250. }
  54251. this.onBeforeBindObservable.notifyObservers(this);
  54252. // Set custom projection.
  54253. // Needs to be before binding to prevent changing the aspect ratio.
  54254. var camera;
  54255. if (this.activeCamera) {
  54256. camera = this.activeCamera;
  54257. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54258. if (this.activeCamera !== scene.activeCamera) {
  54259. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  54260. }
  54261. }
  54262. else {
  54263. camera = scene.activeCamera;
  54264. if (camera) {
  54265. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54266. }
  54267. }
  54268. // Prepare renderingManager
  54269. this._renderingManager.reset();
  54270. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  54271. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  54272. var sceneRenderId = scene.getRenderId();
  54273. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  54274. var mesh = currentRenderList[meshIndex];
  54275. if (mesh) {
  54276. if (!mesh.isReady()) {
  54277. // Reset _currentRefreshId
  54278. this.resetRefreshCounter();
  54279. continue;
  54280. }
  54281. mesh._preActivateForIntermediateRendering(sceneRenderId);
  54282. var isMasked = void 0;
  54283. if (!this.renderList && camera) {
  54284. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  54285. }
  54286. else {
  54287. isMasked = false;
  54288. }
  54289. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  54290. mesh._activate(sceneRenderId);
  54291. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  54292. var subMesh = mesh.subMeshes[subIndex];
  54293. scene._activeIndices.addCount(subMesh.indexCount, false);
  54294. this._renderingManager.dispatch(subMesh, mesh);
  54295. }
  54296. }
  54297. }
  54298. }
  54299. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  54300. var particleSystem = scene.particleSystems[particleIndex];
  54301. var emitter = particleSystem.emitter;
  54302. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  54303. continue;
  54304. }
  54305. if (currentRenderList.indexOf(emitter) >= 0) {
  54306. this._renderingManager.dispatchParticles(particleSystem);
  54307. }
  54308. }
  54309. if (this.isCube) {
  54310. for (var face = 0; face < 6; face++) {
  54311. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54312. scene.incrementRenderId();
  54313. scene.resetCachedMaterial();
  54314. }
  54315. }
  54316. else {
  54317. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54318. }
  54319. this.onAfterUnbindObservable.notifyObservers(this);
  54320. if (scene.activeCamera) {
  54321. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  54322. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  54323. }
  54324. engine.setViewport(scene.activeCamera.viewport);
  54325. }
  54326. scene.resetCachedMaterial();
  54327. };
  54328. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  54329. var minimum = 128;
  54330. var x = renderDimension * scale;
  54331. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  54332. // Ensure we don't exceed the render dimension (while staying POT)
  54333. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  54334. };
  54335. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54336. var _this = this;
  54337. if (!this._texture) {
  54338. return;
  54339. }
  54340. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  54341. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54342. });
  54343. };
  54344. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  54345. var scene = this.getScene();
  54346. if (!scene) {
  54347. return;
  54348. }
  54349. var engine = scene.getEngine();
  54350. if (!this._texture) {
  54351. return;
  54352. }
  54353. // Bind
  54354. if (this._postProcessManager) {
  54355. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  54356. }
  54357. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  54358. if (this._texture) {
  54359. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  54360. }
  54361. }
  54362. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  54363. // Clear
  54364. if (this.onClearObservable.hasObservers()) {
  54365. this.onClearObservable.notifyObservers(engine);
  54366. }
  54367. else {
  54368. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  54369. }
  54370. if (!this._doNotChangeAspectRatio) {
  54371. scene.updateTransformMatrix(true);
  54372. }
  54373. // Render
  54374. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  54375. if (this._postProcessManager) {
  54376. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  54377. }
  54378. else if (useCameraPostProcess) {
  54379. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  54380. }
  54381. if (!this._doNotChangeAspectRatio) {
  54382. scene.updateTransformMatrix(true);
  54383. }
  54384. // Dump ?
  54385. if (dumpForDebug) {
  54386. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  54387. }
  54388. // Unbind
  54389. if (!this.isCube || faceIndex === 5) {
  54390. if (this.isCube) {
  54391. if (faceIndex === 5) {
  54392. engine.generateMipMapsForCubemap(this._texture);
  54393. }
  54394. }
  54395. this.unbindFrameBuffer(engine, faceIndex);
  54396. }
  54397. else {
  54398. this.onAfterRenderObservable.notifyObservers(faceIndex);
  54399. }
  54400. };
  54401. /**
  54402. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  54403. * This allowed control for front to back rendering or reversly depending of the special needs.
  54404. *
  54405. * @param renderingGroupId The rendering group id corresponding to its index
  54406. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  54407. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  54408. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  54409. */
  54410. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  54411. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  54412. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  54413. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  54414. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  54415. };
  54416. /**
  54417. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  54418. *
  54419. * @param renderingGroupId The rendering group id corresponding to its index
  54420. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  54421. */
  54422. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  54423. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  54424. };
  54425. RenderTargetTexture.prototype.clone = function () {
  54426. var textureSize = this.getSize();
  54427. 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);
  54428. // Base texture
  54429. newTexture.hasAlpha = this.hasAlpha;
  54430. newTexture.level = this.level;
  54431. // RenderTarget Texture
  54432. newTexture.coordinatesMode = this.coordinatesMode;
  54433. if (this.renderList) {
  54434. newTexture.renderList = this.renderList.slice(0);
  54435. }
  54436. return newTexture;
  54437. };
  54438. RenderTargetTexture.prototype.serialize = function () {
  54439. if (!this.name) {
  54440. return null;
  54441. }
  54442. var serializationObject = _super.prototype.serialize.call(this);
  54443. serializationObject.renderTargetSize = this.getRenderSize();
  54444. serializationObject.renderList = [];
  54445. if (this.renderList) {
  54446. for (var index = 0; index < this.renderList.length; index++) {
  54447. serializationObject.renderList.push(this.renderList[index].id);
  54448. }
  54449. }
  54450. return serializationObject;
  54451. };
  54452. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  54453. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  54454. var objBuffer = this.getInternalTexture();
  54455. var scene = this.getScene();
  54456. if (objBuffer && scene) {
  54457. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  54458. }
  54459. };
  54460. RenderTargetTexture.prototype.dispose = function () {
  54461. if (this._postProcessManager) {
  54462. this._postProcessManager.dispose();
  54463. this._postProcessManager = null;
  54464. }
  54465. this.clearPostProcesses(true);
  54466. if (this._resizeObserver) {
  54467. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  54468. this._resizeObserver = null;
  54469. }
  54470. this.renderList = null;
  54471. // Remove from custom render targets
  54472. var scene = this.getScene();
  54473. if (!scene) {
  54474. return;
  54475. }
  54476. var index = scene.customRenderTargets.indexOf(this);
  54477. if (index >= 0) {
  54478. scene.customRenderTargets.splice(index, 1);
  54479. }
  54480. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  54481. var camera = _a[_i];
  54482. index = camera.customRenderTargets.indexOf(this);
  54483. if (index >= 0) {
  54484. camera.customRenderTargets.splice(index, 1);
  54485. }
  54486. }
  54487. _super.prototype.dispose.call(this);
  54488. };
  54489. RenderTargetTexture.prototype._rebuild = function () {
  54490. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54491. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54492. }
  54493. if (this._postProcessManager) {
  54494. this._postProcessManager._rebuild();
  54495. }
  54496. };
  54497. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  54498. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  54499. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  54500. return RenderTargetTexture;
  54501. }(BABYLON.Texture));
  54502. BABYLON.RenderTargetTexture = RenderTargetTexture;
  54503. })(BABYLON || (BABYLON = {}));
  54504. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  54505. var BABYLON;
  54506. (function (BABYLON) {
  54507. ;
  54508. var MultiRenderTarget = /** @class */ (function (_super) {
  54509. __extends(MultiRenderTarget, _super);
  54510. function MultiRenderTarget(name, size, count, scene, options) {
  54511. var _this = this;
  54512. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  54513. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  54514. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  54515. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  54516. _this._engine = scene.getEngine();
  54517. if (!_this.isSupported) {
  54518. _this.dispose();
  54519. return;
  54520. }
  54521. var types = [];
  54522. var samplingModes = [];
  54523. for (var i = 0; i < count; i++) {
  54524. if (options && options.types && options.types[i] !== undefined) {
  54525. types.push(options.types[i]);
  54526. }
  54527. else {
  54528. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54529. }
  54530. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  54531. samplingModes.push(options.samplingModes[i]);
  54532. }
  54533. else {
  54534. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54535. }
  54536. }
  54537. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  54538. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  54539. _this._size = size;
  54540. _this._multiRenderTargetOptions = {
  54541. samplingModes: samplingModes,
  54542. generateMipMaps: generateMipMaps,
  54543. generateDepthBuffer: generateDepthBuffer,
  54544. generateStencilBuffer: generateStencilBuffer,
  54545. generateDepthTexture: generateDepthTexture,
  54546. types: types,
  54547. textureCount: count
  54548. };
  54549. _this._createInternalTextures();
  54550. _this._createTextures();
  54551. return _this;
  54552. }
  54553. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  54554. get: function () {
  54555. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  54556. },
  54557. enumerable: true,
  54558. configurable: true
  54559. });
  54560. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  54561. get: function () {
  54562. return this._textures;
  54563. },
  54564. enumerable: true,
  54565. configurable: true
  54566. });
  54567. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  54568. get: function () {
  54569. return this._textures[this._textures.length - 1];
  54570. },
  54571. enumerable: true,
  54572. configurable: true
  54573. });
  54574. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  54575. set: function (wrap) {
  54576. if (this._textures) {
  54577. for (var i = 0; i < this._textures.length; i++) {
  54578. this._textures[i].wrapU = wrap;
  54579. }
  54580. }
  54581. },
  54582. enumerable: true,
  54583. configurable: true
  54584. });
  54585. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  54586. set: function (wrap) {
  54587. if (this._textures) {
  54588. for (var i = 0; i < this._textures.length; i++) {
  54589. this._textures[i].wrapV = wrap;
  54590. }
  54591. }
  54592. },
  54593. enumerable: true,
  54594. configurable: true
  54595. });
  54596. MultiRenderTarget.prototype._rebuild = function () {
  54597. this.releaseInternalTextures();
  54598. this._createInternalTextures();
  54599. for (var i = 0; i < this._internalTextures.length; i++) {
  54600. var texture = this._textures[i];
  54601. texture._texture = this._internalTextures[i];
  54602. }
  54603. // Keeps references to frame buffer and stencil/depth buffer
  54604. this._texture = this._internalTextures[0];
  54605. };
  54606. MultiRenderTarget.prototype._createInternalTextures = function () {
  54607. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  54608. };
  54609. MultiRenderTarget.prototype._createTextures = function () {
  54610. this._textures = [];
  54611. for (var i = 0; i < this._internalTextures.length; i++) {
  54612. var texture = new BABYLON.Texture(null, this.getScene());
  54613. texture._texture = this._internalTextures[i];
  54614. this._textures.push(texture);
  54615. }
  54616. // Keeps references to frame buffer and stencil/depth buffer
  54617. this._texture = this._internalTextures[0];
  54618. };
  54619. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  54620. get: function () {
  54621. return this._samples;
  54622. },
  54623. set: function (value) {
  54624. if (this._samples === value) {
  54625. return;
  54626. }
  54627. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  54628. },
  54629. enumerable: true,
  54630. configurable: true
  54631. });
  54632. MultiRenderTarget.prototype.resize = function (size) {
  54633. this.releaseInternalTextures();
  54634. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  54635. this._createInternalTextures();
  54636. };
  54637. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54638. var _this = this;
  54639. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  54640. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54641. });
  54642. };
  54643. MultiRenderTarget.prototype.dispose = function () {
  54644. this.releaseInternalTextures();
  54645. _super.prototype.dispose.call(this);
  54646. };
  54647. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  54648. if (!this._internalTextures) {
  54649. return;
  54650. }
  54651. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  54652. if (this._internalTextures[i] !== undefined) {
  54653. this._internalTextures[i].dispose();
  54654. this._internalTextures.splice(i, 1);
  54655. }
  54656. }
  54657. };
  54658. return MultiRenderTarget;
  54659. }(BABYLON.RenderTargetTexture));
  54660. BABYLON.MultiRenderTarget = MultiRenderTarget;
  54661. })(BABYLON || (BABYLON = {}));
  54662. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  54663. var BABYLON;
  54664. (function (BABYLON) {
  54665. var MirrorTexture = /** @class */ (function (_super) {
  54666. __extends(MirrorTexture, _super);
  54667. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  54668. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54669. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54670. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  54671. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  54672. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  54673. _this._transformMatrix = BABYLON.Matrix.Zero();
  54674. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  54675. _this._adaptiveBlurKernel = 0;
  54676. _this._blurKernelX = 0;
  54677. _this._blurKernelY = 0;
  54678. _this._blurRatio = 1.0;
  54679. _this.ignoreCameraViewport = true;
  54680. _this.onBeforeRenderObservable.add(function () {
  54681. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  54682. _this._savedViewMatrix = scene.getViewMatrix();
  54683. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  54684. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  54685. scene.clipPlane = _this.mirrorPlane;
  54686. scene.getEngine().cullBackFaces = false;
  54687. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  54688. });
  54689. _this.onAfterRenderObservable.add(function () {
  54690. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  54691. scene.getEngine().cullBackFaces = true;
  54692. scene._mirroredCameraPosition = null;
  54693. delete scene.clipPlane;
  54694. });
  54695. return _this;
  54696. }
  54697. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  54698. get: function () {
  54699. return this._blurRatio;
  54700. },
  54701. set: function (value) {
  54702. if (this._blurRatio === value) {
  54703. return;
  54704. }
  54705. this._blurRatio = value;
  54706. this._preparePostProcesses();
  54707. },
  54708. enumerable: true,
  54709. configurable: true
  54710. });
  54711. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  54712. set: function (value) {
  54713. this._adaptiveBlurKernel = value;
  54714. this._autoComputeBlurKernel();
  54715. },
  54716. enumerable: true,
  54717. configurable: true
  54718. });
  54719. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  54720. set: function (value) {
  54721. this.blurKernelX = value;
  54722. this.blurKernelY = value;
  54723. },
  54724. enumerable: true,
  54725. configurable: true
  54726. });
  54727. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  54728. get: function () {
  54729. return this._blurKernelX;
  54730. },
  54731. set: function (value) {
  54732. if (this._blurKernelX === value) {
  54733. return;
  54734. }
  54735. this._blurKernelX = value;
  54736. this._preparePostProcesses();
  54737. },
  54738. enumerable: true,
  54739. configurable: true
  54740. });
  54741. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  54742. get: function () {
  54743. return this._blurKernelY;
  54744. },
  54745. set: function (value) {
  54746. if (this._blurKernelY === value) {
  54747. return;
  54748. }
  54749. this._blurKernelY = value;
  54750. this._preparePostProcesses();
  54751. },
  54752. enumerable: true,
  54753. configurable: true
  54754. });
  54755. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  54756. var engine = this.getScene().getEngine();
  54757. var dw = this.getRenderWidth() / engine.getRenderWidth();
  54758. var dh = this.getRenderHeight() / engine.getRenderHeight();
  54759. this.blurKernelX = this._adaptiveBlurKernel * dw;
  54760. this.blurKernelY = this._adaptiveBlurKernel * dh;
  54761. };
  54762. MirrorTexture.prototype._onRatioRescale = function () {
  54763. if (this._sizeRatio) {
  54764. this.resize(this._initialSizeParameter);
  54765. if (!this._adaptiveBlurKernel) {
  54766. this._preparePostProcesses();
  54767. }
  54768. }
  54769. if (this._adaptiveBlurKernel) {
  54770. this._autoComputeBlurKernel();
  54771. }
  54772. };
  54773. MirrorTexture.prototype._preparePostProcesses = function () {
  54774. this.clearPostProcesses(true);
  54775. if (this._blurKernelX && this._blurKernelY) {
  54776. var engine = this.getScene().getEngine();
  54777. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54778. 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);
  54779. this._blurX.autoClear = false;
  54780. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  54781. this._blurX.outputTexture = this._texture;
  54782. }
  54783. else {
  54784. this._blurX.alwaysForcePOT = true;
  54785. }
  54786. 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);
  54787. this._blurY.autoClear = false;
  54788. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  54789. this.addPostProcess(this._blurX);
  54790. this.addPostProcess(this._blurY);
  54791. }
  54792. else {
  54793. if (this._blurY) {
  54794. this.removePostProcess(this._blurY);
  54795. this._blurY.dispose();
  54796. this._blurY = null;
  54797. }
  54798. if (this._blurX) {
  54799. this.removePostProcess(this._blurX);
  54800. this._blurX.dispose();
  54801. this._blurX = null;
  54802. }
  54803. }
  54804. };
  54805. MirrorTexture.prototype.clone = function () {
  54806. var scene = this.getScene();
  54807. if (!scene) {
  54808. return this;
  54809. }
  54810. var textureSize = this.getSize();
  54811. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  54812. // Base texture
  54813. newTexture.hasAlpha = this.hasAlpha;
  54814. newTexture.level = this.level;
  54815. // Mirror Texture
  54816. newTexture.mirrorPlane = this.mirrorPlane.clone();
  54817. if (this.renderList) {
  54818. newTexture.renderList = this.renderList.slice(0);
  54819. }
  54820. return newTexture;
  54821. };
  54822. MirrorTexture.prototype.serialize = function () {
  54823. if (!this.name) {
  54824. return null;
  54825. }
  54826. var serializationObject = _super.prototype.serialize.call(this);
  54827. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  54828. return serializationObject;
  54829. };
  54830. return MirrorTexture;
  54831. }(BABYLON.RenderTargetTexture));
  54832. BABYLON.MirrorTexture = MirrorTexture;
  54833. })(BABYLON || (BABYLON = {}));
  54834. //# sourceMappingURL=babylon.mirrorTexture.js.map
  54835. var BABYLON;
  54836. (function (BABYLON) {
  54837. /**
  54838. * Creates a refraction texture used by refraction channel of the standard material.
  54839. * @param name the texture name
  54840. * @param size size of the underlying texture
  54841. * @param scene root scene
  54842. */
  54843. var RefractionTexture = /** @class */ (function (_super) {
  54844. __extends(RefractionTexture, _super);
  54845. function RefractionTexture(name, size, scene, generateMipMaps) {
  54846. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  54847. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  54848. _this.depth = 2.0;
  54849. _this.onBeforeRenderObservable.add(function () {
  54850. scene.clipPlane = _this.refractionPlane;
  54851. });
  54852. _this.onAfterRenderObservable.add(function () {
  54853. delete scene.clipPlane;
  54854. });
  54855. return _this;
  54856. }
  54857. RefractionTexture.prototype.clone = function () {
  54858. var scene = this.getScene();
  54859. if (!scene) {
  54860. return this;
  54861. }
  54862. var textureSize = this.getSize();
  54863. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  54864. // Base texture
  54865. newTexture.hasAlpha = this.hasAlpha;
  54866. newTexture.level = this.level;
  54867. // Refraction Texture
  54868. newTexture.refractionPlane = this.refractionPlane.clone();
  54869. if (this.renderList) {
  54870. newTexture.renderList = this.renderList.slice(0);
  54871. }
  54872. newTexture.depth = this.depth;
  54873. return newTexture;
  54874. };
  54875. RefractionTexture.prototype.serialize = function () {
  54876. if (!this.name) {
  54877. return null;
  54878. }
  54879. var serializationObject = _super.prototype.serialize.call(this);
  54880. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  54881. serializationObject.depth = this.depth;
  54882. return serializationObject;
  54883. };
  54884. return RefractionTexture;
  54885. }(BABYLON.RenderTargetTexture));
  54886. BABYLON.RefractionTexture = RefractionTexture;
  54887. })(BABYLON || (BABYLON = {}));
  54888. //# sourceMappingURL=babylon.refractionTexture.js.map
  54889. var BABYLON;
  54890. (function (BABYLON) {
  54891. var DynamicTexture = /** @class */ (function (_super) {
  54892. __extends(DynamicTexture, _super);
  54893. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  54894. if (scene === void 0) { scene = null; }
  54895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54896. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54897. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  54898. _this.name = name;
  54899. _this._engine = _this.getScene().getEngine();
  54900. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54901. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54902. _this._generateMipMaps = generateMipMaps;
  54903. if (options.getContext) {
  54904. _this._canvas = options;
  54905. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54906. }
  54907. else {
  54908. _this._canvas = document.createElement("canvas");
  54909. if (options.width) {
  54910. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54911. }
  54912. else {
  54913. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  54914. }
  54915. }
  54916. var textureSize = _this.getSize();
  54917. _this._canvas.width = textureSize.width;
  54918. _this._canvas.height = textureSize.height;
  54919. _this._context = _this._canvas.getContext("2d");
  54920. return _this;
  54921. }
  54922. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  54923. get: function () {
  54924. return true;
  54925. },
  54926. enumerable: true,
  54927. configurable: true
  54928. });
  54929. DynamicTexture.prototype._recreate = function (textureSize) {
  54930. this._canvas.width = textureSize.width;
  54931. this._canvas.height = textureSize.height;
  54932. this.releaseInternalTexture();
  54933. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  54934. };
  54935. DynamicTexture.prototype.scale = function (ratio) {
  54936. var textureSize = this.getSize();
  54937. textureSize.width *= ratio;
  54938. textureSize.height *= ratio;
  54939. this._recreate(textureSize);
  54940. };
  54941. DynamicTexture.prototype.scaleTo = function (width, height) {
  54942. var textureSize = this.getSize();
  54943. textureSize.width = width;
  54944. textureSize.height = height;
  54945. this._recreate(textureSize);
  54946. };
  54947. DynamicTexture.prototype.getContext = function () {
  54948. return this._context;
  54949. };
  54950. DynamicTexture.prototype.clear = function () {
  54951. var size = this.getSize();
  54952. this._context.fillRect(0, 0, size.width, size.height);
  54953. };
  54954. DynamicTexture.prototype.update = function (invertY) {
  54955. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  54956. };
  54957. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  54958. if (update === void 0) { update = true; }
  54959. var size = this.getSize();
  54960. if (clearColor) {
  54961. this._context.fillStyle = clearColor;
  54962. this._context.fillRect(0, 0, size.width, size.height);
  54963. }
  54964. this._context.font = font;
  54965. if (x === null || x === undefined) {
  54966. var textSize = this._context.measureText(text);
  54967. x = (size.width - textSize.width) / 2;
  54968. }
  54969. if (y === null || y === undefined) {
  54970. var fontSize = parseInt((font.replace(/\D/g, '')));
  54971. ;
  54972. y = (size.height / 2) + (fontSize / 3.65);
  54973. }
  54974. this._context.fillStyle = color;
  54975. this._context.fillText(text, x, y);
  54976. if (update) {
  54977. this.update(invertY);
  54978. }
  54979. };
  54980. DynamicTexture.prototype.clone = function () {
  54981. var scene = this.getScene();
  54982. if (!scene) {
  54983. return this;
  54984. }
  54985. var textureSize = this.getSize();
  54986. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  54987. // Base texture
  54988. newTexture.hasAlpha = this.hasAlpha;
  54989. newTexture.level = this.level;
  54990. // Dynamic Texture
  54991. newTexture.wrapU = this.wrapU;
  54992. newTexture.wrapV = this.wrapV;
  54993. return newTexture;
  54994. };
  54995. DynamicTexture.prototype._rebuild = function () {
  54996. this.update();
  54997. };
  54998. return DynamicTexture;
  54999. }(BABYLON.Texture));
  55000. BABYLON.DynamicTexture = DynamicTexture;
  55001. })(BABYLON || (BABYLON = {}));
  55002. //# sourceMappingURL=babylon.dynamicTexture.js.map
  55003. var BABYLON;
  55004. (function (BABYLON) {
  55005. var VideoTexture = /** @class */ (function (_super) {
  55006. __extends(VideoTexture, _super);
  55007. /**
  55008. * Creates a video texture.
  55009. * Sample : https://doc.babylonjs.com/how_to/video_texture
  55010. * @param {string | null} name optional name, will detect from video source, if not defined
  55011. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  55012. * @param {BABYLON.Scene} scene is obviously the current scene.
  55013. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  55014. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  55015. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  55016. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  55017. */
  55018. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  55019. if (generateMipMaps === void 0) { generateMipMaps = false; }
  55020. if (invertY === void 0) { invertY = false; }
  55021. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55022. if (settings === void 0) { settings = {
  55023. autoPlay: true,
  55024. loop: true,
  55025. autoUpdateTexture: true,
  55026. }; }
  55027. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55028. _this._createInternalTexture = function () {
  55029. if (_this._texture != null) {
  55030. return;
  55031. }
  55032. if (!_this._engine.needPOTTextures ||
  55033. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  55034. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55035. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55036. }
  55037. else {
  55038. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55039. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55040. _this._generateMipMaps = false;
  55041. }
  55042. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  55043. _this._texture.isReady = true;
  55044. _this._updateInternalTexture();
  55045. };
  55046. _this.reset = function () {
  55047. if (_this._texture == null) {
  55048. return;
  55049. }
  55050. _this._texture.dispose();
  55051. _this._texture = null;
  55052. };
  55053. _this._updateInternalTexture = function (e) {
  55054. if (_this._texture == null || !_this._texture.isReady) {
  55055. return;
  55056. }
  55057. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  55058. return;
  55059. }
  55060. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  55061. };
  55062. _this._engine = _this.getScene().getEngine();
  55063. _this._generateMipMaps = generateMipMaps;
  55064. _this._samplingMode = samplingMode;
  55065. _this.autoUpdateTexture = settings.autoUpdateTexture;
  55066. _this.name = name || _this._getName(src);
  55067. _this.video = _this._getVideo(src);
  55068. if (settings.autoPlay !== undefined) {
  55069. _this.video.autoplay = settings.autoPlay;
  55070. }
  55071. if (settings.loop !== undefined) {
  55072. _this.video.loop = settings.loop;
  55073. }
  55074. _this.video.addEventListener("canplay", _this._createInternalTexture);
  55075. _this.video.addEventListener("paused", _this._updateInternalTexture);
  55076. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  55077. _this.video.addEventListener("emptied", _this.reset);
  55078. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  55079. _this._createInternalTexture();
  55080. }
  55081. return _this;
  55082. }
  55083. VideoTexture.prototype._getName = function (src) {
  55084. if (src instanceof HTMLVideoElement) {
  55085. return src.currentSrc;
  55086. }
  55087. if (typeof src === "object") {
  55088. return src.toString();
  55089. }
  55090. return src;
  55091. };
  55092. ;
  55093. VideoTexture.prototype._getVideo = function (src) {
  55094. if (src instanceof HTMLVideoElement) {
  55095. return src;
  55096. }
  55097. var video = document.createElement("video");
  55098. if (typeof src === "string") {
  55099. video.src = src;
  55100. }
  55101. else {
  55102. src.forEach(function (url) {
  55103. var source = document.createElement("source");
  55104. source.src = url;
  55105. video.appendChild(source);
  55106. });
  55107. }
  55108. return video;
  55109. };
  55110. ;
  55111. /**
  55112. * Internal method to initiate `update`.
  55113. */
  55114. VideoTexture.prototype._rebuild = function () {
  55115. this.update();
  55116. };
  55117. /**
  55118. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  55119. */
  55120. VideoTexture.prototype.update = function () {
  55121. if (!this.autoUpdateTexture) {
  55122. // Expecting user to call `updateTexture` manually
  55123. return;
  55124. }
  55125. this.updateTexture(true);
  55126. };
  55127. /**
  55128. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  55129. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  55130. */
  55131. VideoTexture.prototype.updateTexture = function (isVisible) {
  55132. if (!isVisible) {
  55133. return;
  55134. }
  55135. if (this.video.paused) {
  55136. return;
  55137. }
  55138. this._updateInternalTexture();
  55139. };
  55140. /**
  55141. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  55142. * @param url New url.
  55143. */
  55144. VideoTexture.prototype.updateURL = function (url) {
  55145. this.video.src = url;
  55146. };
  55147. VideoTexture.prototype.dispose = function () {
  55148. _super.prototype.dispose.call(this);
  55149. this.video.removeEventListener("canplay", this._createInternalTexture);
  55150. this.video.removeEventListener("paused", this._updateInternalTexture);
  55151. this.video.removeEventListener("seeked", this._updateInternalTexture);
  55152. this.video.removeEventListener("emptied", this.reset);
  55153. };
  55154. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  55155. var video = document.createElement("video");
  55156. var constraintsDeviceId;
  55157. if (constraints && constraints.deviceId) {
  55158. constraintsDeviceId = {
  55159. exact: constraints.deviceId,
  55160. };
  55161. }
  55162. navigator.getUserMedia =
  55163. navigator.getUserMedia ||
  55164. navigator.webkitGetUserMedia ||
  55165. navigator.mozGetUserMedia ||
  55166. navigator.msGetUserMedia;
  55167. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  55168. if (navigator.getUserMedia) {
  55169. navigator.getUserMedia({
  55170. video: {
  55171. deviceId: constraintsDeviceId,
  55172. width: {
  55173. min: (constraints && constraints.minWidth) || 256,
  55174. max: (constraints && constraints.maxWidth) || 640,
  55175. },
  55176. height: {
  55177. min: (constraints && constraints.minHeight) || 256,
  55178. max: (constraints && constraints.maxHeight) || 480,
  55179. },
  55180. },
  55181. }, function (stream) {
  55182. if (video.mozSrcObject !== undefined) {
  55183. // hack for Firefox < 19
  55184. video.mozSrcObject = stream;
  55185. }
  55186. else {
  55187. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  55188. }
  55189. video.play();
  55190. if (onReady) {
  55191. onReady(new VideoTexture("video", video, scene, true, true));
  55192. }
  55193. }, function (e) {
  55194. BABYLON.Tools.Error(e.name);
  55195. });
  55196. }
  55197. };
  55198. return VideoTexture;
  55199. }(BABYLON.Texture));
  55200. BABYLON.VideoTexture = VideoTexture;
  55201. })(BABYLON || (BABYLON = {}));
  55202. //# sourceMappingURL=babylon.videoTexture.js.map
  55203. var BABYLON;
  55204. (function (BABYLON) {
  55205. var RawTexture = /** @class */ (function (_super) {
  55206. __extends(RawTexture, _super);
  55207. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  55208. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55209. if (invertY === void 0) { invertY = false; }
  55210. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55211. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55212. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  55213. _this.format = format;
  55214. _this._engine = scene.getEngine();
  55215. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  55216. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55217. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55218. return _this;
  55219. }
  55220. RawTexture.prototype.update = function (data) {
  55221. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  55222. };
  55223. // Statics
  55224. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55225. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55226. if (invertY === void 0) { invertY = false; }
  55227. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55228. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  55229. };
  55230. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55231. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55232. if (invertY === void 0) { invertY = false; }
  55233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55234. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55235. };
  55236. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55237. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55238. if (invertY === void 0) { invertY = false; }
  55239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55240. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55241. };
  55242. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55243. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55244. if (invertY === void 0) { invertY = false; }
  55245. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55246. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55247. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  55248. };
  55249. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55250. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55251. if (invertY === void 0) { invertY = false; }
  55252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55253. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55254. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  55255. };
  55256. return RawTexture;
  55257. }(BABYLON.Texture));
  55258. BABYLON.RawTexture = RawTexture;
  55259. })(BABYLON || (BABYLON = {}));
  55260. //# sourceMappingURL=babylon.rawTexture.js.map
  55261. var BABYLON;
  55262. (function (BABYLON) {
  55263. var PostProcess = /** @class */ (function () {
  55264. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  55265. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  55266. if (defines === void 0) { defines = null; }
  55267. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55268. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  55269. if (blockCompilation === void 0) { blockCompilation = false; }
  55270. this.name = name;
  55271. this.width = -1;
  55272. this.height = -1;
  55273. this.autoClear = true;
  55274. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  55275. this.animations = new Array();
  55276. /*
  55277. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  55278. Can only be used on a single postprocess or on the last one of a chain.
  55279. */
  55280. this.enablePixelPerfectMode = false;
  55281. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  55282. this.alwaysForcePOT = false;
  55283. this.samples = 1;
  55284. this.adaptScaleToCurrentViewport = false;
  55285. this._reusable = false;
  55286. this._textures = new BABYLON.SmartArray(2);
  55287. this._currentRenderTextureInd = 0;
  55288. this._scaleRatio = new BABYLON.Vector2(1, 1);
  55289. this._texelSize = BABYLON.Vector2.Zero();
  55290. // Events
  55291. /**
  55292. * An event triggered when the postprocess is activated.
  55293. * @type {BABYLON.Observable}
  55294. */
  55295. this.onActivateObservable = new BABYLON.Observable();
  55296. /**
  55297. * An event triggered when the postprocess changes its size.
  55298. * @type {BABYLON.Observable}
  55299. */
  55300. this.onSizeChangedObservable = new BABYLON.Observable();
  55301. /**
  55302. * An event triggered when the postprocess applies its effect.
  55303. * @type {BABYLON.Observable}
  55304. */
  55305. this.onApplyObservable = new BABYLON.Observable();
  55306. /**
  55307. * An event triggered before rendering the postprocess
  55308. * @type {BABYLON.Observable}
  55309. */
  55310. this.onBeforeRenderObservable = new BABYLON.Observable();
  55311. /**
  55312. * An event triggered after rendering the postprocess
  55313. * @type {BABYLON.Observable}
  55314. */
  55315. this.onAfterRenderObservable = new BABYLON.Observable();
  55316. if (camera != null) {
  55317. this._camera = camera;
  55318. this._scene = camera.getScene();
  55319. camera.attachPostProcess(this);
  55320. this._engine = this._scene.getEngine();
  55321. this._scene.postProcesses.push(this);
  55322. }
  55323. else if (engine) {
  55324. this._engine = engine;
  55325. this._engine.postProcesses.push(this);
  55326. }
  55327. this._options = options;
  55328. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  55329. this._reusable = reusable || false;
  55330. this._textureType = textureType;
  55331. this._samplers = samplers || [];
  55332. this._samplers.push("textureSampler");
  55333. this._fragmentUrl = fragmentUrl;
  55334. this._vertexUrl = vertexUrl;
  55335. this._parameters = parameters || [];
  55336. this._parameters.push("scale");
  55337. this._indexParameters = indexParameters;
  55338. if (!blockCompilation) {
  55339. this.updateEffect(defines);
  55340. }
  55341. }
  55342. Object.defineProperty(PostProcess.prototype, "onActivate", {
  55343. set: function (callback) {
  55344. if (this._onActivateObserver) {
  55345. this.onActivateObservable.remove(this._onActivateObserver);
  55346. }
  55347. if (callback) {
  55348. this._onActivateObserver = this.onActivateObservable.add(callback);
  55349. }
  55350. },
  55351. enumerable: true,
  55352. configurable: true
  55353. });
  55354. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  55355. set: function (callback) {
  55356. if (this._onSizeChangedObserver) {
  55357. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  55358. }
  55359. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  55360. },
  55361. enumerable: true,
  55362. configurable: true
  55363. });
  55364. Object.defineProperty(PostProcess.prototype, "onApply", {
  55365. set: function (callback) {
  55366. if (this._onApplyObserver) {
  55367. this.onApplyObservable.remove(this._onApplyObserver);
  55368. }
  55369. this._onApplyObserver = this.onApplyObservable.add(callback);
  55370. },
  55371. enumerable: true,
  55372. configurable: true
  55373. });
  55374. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  55375. set: function (callback) {
  55376. if (this._onBeforeRenderObserver) {
  55377. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  55378. }
  55379. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  55380. },
  55381. enumerable: true,
  55382. configurable: true
  55383. });
  55384. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  55385. set: function (callback) {
  55386. if (this._onAfterRenderObserver) {
  55387. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  55388. }
  55389. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  55390. },
  55391. enumerable: true,
  55392. configurable: true
  55393. });
  55394. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  55395. get: function () {
  55396. return this._textures.data[this._currentRenderTextureInd];
  55397. },
  55398. set: function (value) {
  55399. this._forcedOutputTexture = value;
  55400. },
  55401. enumerable: true,
  55402. configurable: true
  55403. });
  55404. PostProcess.prototype.getCamera = function () {
  55405. return this._camera;
  55406. };
  55407. Object.defineProperty(PostProcess.prototype, "texelSize", {
  55408. get: function () {
  55409. if (this._shareOutputWithPostProcess) {
  55410. return this._shareOutputWithPostProcess.texelSize;
  55411. }
  55412. if (this._forcedOutputTexture) {
  55413. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  55414. }
  55415. return this._texelSize;
  55416. },
  55417. enumerable: true,
  55418. configurable: true
  55419. });
  55420. PostProcess.prototype.getEngine = function () {
  55421. return this._engine;
  55422. };
  55423. PostProcess.prototype.getEffect = function () {
  55424. return this._effect;
  55425. };
  55426. PostProcess.prototype.shareOutputWith = function (postProcess) {
  55427. this._disposeTextures();
  55428. this._shareOutputWithPostProcess = postProcess;
  55429. return this;
  55430. };
  55431. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  55432. if (defines === void 0) { defines = null; }
  55433. if (uniforms === void 0) { uniforms = null; }
  55434. if (samplers === void 0) { samplers = null; }
  55435. 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);
  55436. };
  55437. PostProcess.prototype.isReusable = function () {
  55438. return this._reusable;
  55439. };
  55440. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  55441. PostProcess.prototype.markTextureDirty = function () {
  55442. this.width = -1;
  55443. };
  55444. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  55445. var _this = this;
  55446. if (sourceTexture === void 0) { sourceTexture = null; }
  55447. camera = camera || this._camera;
  55448. var scene = camera.getScene();
  55449. var engine = scene.getEngine();
  55450. var maxSize = engine.getCaps().maxTextureSize;
  55451. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  55452. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  55453. var desiredWidth = (this._options.width || requiredWidth);
  55454. var desiredHeight = this._options.height || requiredHeight;
  55455. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  55456. if (this.adaptScaleToCurrentViewport) {
  55457. var currentViewport = engine.currentViewport;
  55458. if (currentViewport) {
  55459. desiredWidth *= currentViewport.width;
  55460. desiredHeight *= currentViewport.height;
  55461. }
  55462. }
  55463. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  55464. if (!this._options.width) {
  55465. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  55466. }
  55467. if (!this._options.height) {
  55468. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  55469. }
  55470. }
  55471. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  55472. if (this._textures.length > 0) {
  55473. for (var i = 0; i < this._textures.length; i++) {
  55474. this._engine._releaseTexture(this._textures.data[i]);
  55475. }
  55476. this._textures.reset();
  55477. }
  55478. this.width = desiredWidth;
  55479. this.height = desiredHeight;
  55480. var textureSize = { width: this.width, height: this.height };
  55481. var textureOptions = {
  55482. generateMipMaps: false,
  55483. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  55484. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  55485. samplingMode: this.renderTargetSamplingMode,
  55486. type: this._textureType
  55487. };
  55488. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  55489. if (this._reusable) {
  55490. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  55491. }
  55492. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  55493. this.onSizeChangedObservable.notifyObservers(this);
  55494. }
  55495. this._textures.forEach(function (texture) {
  55496. if (texture.samples !== _this.samples) {
  55497. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  55498. }
  55499. });
  55500. }
  55501. var target;
  55502. if (this._shareOutputWithPostProcess) {
  55503. target = this._shareOutputWithPostProcess.outputTexture;
  55504. }
  55505. else if (this._forcedOutputTexture) {
  55506. target = this._forcedOutputTexture;
  55507. this.width = this._forcedOutputTexture.width;
  55508. this.height = this._forcedOutputTexture.height;
  55509. }
  55510. else {
  55511. target = this.outputTexture;
  55512. }
  55513. if (this.enablePixelPerfectMode) {
  55514. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  55515. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  55516. }
  55517. else {
  55518. this._scaleRatio.copyFromFloats(1, 1);
  55519. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  55520. }
  55521. this.onActivateObservable.notifyObservers(camera);
  55522. // Clear
  55523. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  55524. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  55525. }
  55526. if (this._reusable) {
  55527. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  55528. }
  55529. };
  55530. Object.defineProperty(PostProcess.prototype, "isSupported", {
  55531. get: function () {
  55532. return this._effect.isSupported;
  55533. },
  55534. enumerable: true,
  55535. configurable: true
  55536. });
  55537. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  55538. get: function () {
  55539. if (this._shareOutputWithPostProcess) {
  55540. return this._shareOutputWithPostProcess.aspectRatio;
  55541. }
  55542. if (this._forcedOutputTexture) {
  55543. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  55544. }
  55545. return this.width / this.height;
  55546. },
  55547. enumerable: true,
  55548. configurable: true
  55549. });
  55550. /**
  55551. * Get a value indicating if the post-process is ready to be used
  55552. * @returns true if the post-process is ready (shader is compiled)
  55553. */
  55554. PostProcess.prototype.isReady = function () {
  55555. return this._effect && this._effect.isReady();
  55556. };
  55557. PostProcess.prototype.apply = function () {
  55558. // Check
  55559. if (!this._effect || !this._effect.isReady())
  55560. return null;
  55561. // States
  55562. this._engine.enableEffect(this._effect);
  55563. this._engine.setState(false);
  55564. this._engine.setDepthBuffer(false);
  55565. this._engine.setDepthWrite(false);
  55566. // Alpha
  55567. this._engine.setAlphaMode(this.alphaMode);
  55568. if (this.alphaConstants) {
  55569. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  55570. }
  55571. // Texture
  55572. var source;
  55573. if (this._shareOutputWithPostProcess) {
  55574. source = this._shareOutputWithPostProcess.outputTexture;
  55575. }
  55576. else if (this._forcedOutputTexture) {
  55577. source = this._forcedOutputTexture;
  55578. }
  55579. else {
  55580. source = this.outputTexture;
  55581. }
  55582. this._effect._bindTexture("textureSampler", source);
  55583. // Parameters
  55584. this._effect.setVector2("scale", this._scaleRatio);
  55585. this.onApplyObservable.notifyObservers(this._effect);
  55586. return this._effect;
  55587. };
  55588. PostProcess.prototype._disposeTextures = function () {
  55589. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  55590. return;
  55591. }
  55592. if (this._textures.length > 0) {
  55593. for (var i = 0; i < this._textures.length; i++) {
  55594. this._engine._releaseTexture(this._textures.data[i]);
  55595. }
  55596. }
  55597. this._textures.dispose();
  55598. };
  55599. PostProcess.prototype.dispose = function (camera) {
  55600. camera = camera || this._camera;
  55601. this._disposeTextures();
  55602. if (this._scene) {
  55603. var index_1 = this._scene.postProcesses.indexOf(this);
  55604. if (index_1 !== -1) {
  55605. this._scene.postProcesses.splice(index_1, 1);
  55606. }
  55607. }
  55608. else {
  55609. var index_2 = this._engine.postProcesses.indexOf(this);
  55610. if (index_2 !== -1) {
  55611. this._engine.postProcesses.splice(index_2, 1);
  55612. }
  55613. }
  55614. if (!camera) {
  55615. return;
  55616. }
  55617. camera.detachPostProcess(this);
  55618. var index = camera._postProcesses.indexOf(this);
  55619. if (index === 0 && camera._postProcesses.length > 0) {
  55620. this._camera._postProcesses[0].markTextureDirty();
  55621. }
  55622. this.onActivateObservable.clear();
  55623. this.onAfterRenderObservable.clear();
  55624. this.onApplyObservable.clear();
  55625. this.onBeforeRenderObservable.clear();
  55626. this.onSizeChangedObservable.clear();
  55627. };
  55628. return PostProcess;
  55629. }());
  55630. BABYLON.PostProcess = PostProcess;
  55631. })(BABYLON || (BABYLON = {}));
  55632. //# sourceMappingURL=babylon.postProcess.js.map
  55633. var BABYLON;
  55634. (function (BABYLON) {
  55635. var PassPostProcess = /** @class */ (function (_super) {
  55636. __extends(PassPostProcess, _super);
  55637. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55638. if (camera === void 0) { camera = null; }
  55639. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55640. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  55641. }
  55642. return PassPostProcess;
  55643. }(BABYLON.PostProcess));
  55644. BABYLON.PassPostProcess = PassPostProcess;
  55645. })(BABYLON || (BABYLON = {}));
  55646. //# sourceMappingURL=babylon.passPostProcess.js.map
  55647. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55648. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55649. s = arguments[i];
  55650. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55651. t[p] = s[p];
  55652. }
  55653. return t;
  55654. };
  55655. var BABYLON;
  55656. (function (BABYLON) {
  55657. var ShadowGenerator = /** @class */ (function () {
  55658. /**
  55659. * Creates a ShadowGenerator object.
  55660. * A ShadowGenerator is the required tool to use the shadows.
  55661. * Each light casting shadows needs to use its own ShadowGenerator.
  55662. * Required parameters :
  55663. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  55664. * - `light`: the light object generating the shadows.
  55665. * - `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.
  55666. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  55667. */
  55668. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  55669. // Members
  55670. this._bias = 0.00005;
  55671. this._blurBoxOffset = 1;
  55672. this._blurScale = 2;
  55673. this._blurKernel = 1;
  55674. this._useKernelBlur = false;
  55675. this._filter = ShadowGenerator.FILTER_NONE;
  55676. this._darkness = 0;
  55677. this._transparencyShadow = false;
  55678. /**
  55679. * Controls the extent to which the shadows fade out at the edge of the frustum
  55680. * Used only by directionals and spots
  55681. */
  55682. this.frustumEdgeFalloff = 0;
  55683. this.forceBackFacesOnly = false;
  55684. this._lightDirection = BABYLON.Vector3.Zero();
  55685. this._viewMatrix = BABYLON.Matrix.Zero();
  55686. this._projectionMatrix = BABYLON.Matrix.Zero();
  55687. this._transformMatrix = BABYLON.Matrix.Zero();
  55688. this._currentFaceIndex = 0;
  55689. this._currentFaceIndexCache = 0;
  55690. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  55691. this._mapSize = mapSize;
  55692. this._light = light;
  55693. this._scene = light.getScene();
  55694. light._shadowGenerator = this;
  55695. // Texture type fallback from float to int if not supported.
  55696. var caps = this._scene.getEngine().getCaps();
  55697. if (!useFullFloatFirst) {
  55698. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  55699. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55700. }
  55701. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  55702. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55703. }
  55704. else {
  55705. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55706. }
  55707. }
  55708. else {
  55709. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  55710. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55711. }
  55712. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  55713. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55714. }
  55715. else {
  55716. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55717. }
  55718. }
  55719. this._initializeGenerator();
  55720. }
  55721. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  55722. // Static
  55723. get: function () {
  55724. return ShadowGenerator._FILTER_NONE;
  55725. },
  55726. enumerable: true,
  55727. configurable: true
  55728. });
  55729. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  55730. get: function () {
  55731. return ShadowGenerator._FILTER_POISSONSAMPLING;
  55732. },
  55733. enumerable: true,
  55734. configurable: true
  55735. });
  55736. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  55737. get: function () {
  55738. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  55739. },
  55740. enumerable: true,
  55741. configurable: true
  55742. });
  55743. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  55744. get: function () {
  55745. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  55746. },
  55747. enumerable: true,
  55748. configurable: true
  55749. });
  55750. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  55751. get: function () {
  55752. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  55753. },
  55754. enumerable: true,
  55755. configurable: true
  55756. });
  55757. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  55758. get: function () {
  55759. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  55760. },
  55761. enumerable: true,
  55762. configurable: true
  55763. });
  55764. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  55765. get: function () {
  55766. return this._bias;
  55767. },
  55768. set: function (bias) {
  55769. this._bias = bias;
  55770. },
  55771. enumerable: true,
  55772. configurable: true
  55773. });
  55774. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  55775. get: function () {
  55776. return this._blurBoxOffset;
  55777. },
  55778. set: function (value) {
  55779. if (this._blurBoxOffset === value) {
  55780. return;
  55781. }
  55782. this._blurBoxOffset = value;
  55783. this._disposeBlurPostProcesses();
  55784. },
  55785. enumerable: true,
  55786. configurable: true
  55787. });
  55788. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  55789. get: function () {
  55790. return this._blurScale;
  55791. },
  55792. set: function (value) {
  55793. if (this._blurScale === value) {
  55794. return;
  55795. }
  55796. this._blurScale = value;
  55797. this._disposeBlurPostProcesses();
  55798. },
  55799. enumerable: true,
  55800. configurable: true
  55801. });
  55802. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  55803. get: function () {
  55804. return this._blurKernel;
  55805. },
  55806. set: function (value) {
  55807. if (this._blurKernel === value) {
  55808. return;
  55809. }
  55810. this._blurKernel = value;
  55811. this._disposeBlurPostProcesses();
  55812. },
  55813. enumerable: true,
  55814. configurable: true
  55815. });
  55816. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  55817. get: function () {
  55818. return this._useKernelBlur;
  55819. },
  55820. set: function (value) {
  55821. if (this._useKernelBlur === value) {
  55822. return;
  55823. }
  55824. this._useKernelBlur = value;
  55825. this._disposeBlurPostProcesses();
  55826. },
  55827. enumerable: true,
  55828. configurable: true
  55829. });
  55830. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  55831. get: function () {
  55832. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  55833. },
  55834. set: function (value) {
  55835. this._depthScale = value;
  55836. },
  55837. enumerable: true,
  55838. configurable: true
  55839. });
  55840. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  55841. get: function () {
  55842. return this._filter;
  55843. },
  55844. set: function (value) {
  55845. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  55846. if (this._light.needCube()) {
  55847. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55848. this.useExponentialShadowMap = true;
  55849. return;
  55850. }
  55851. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55852. this.useCloseExponentialShadowMap = true;
  55853. return;
  55854. }
  55855. }
  55856. if (this._filter === value) {
  55857. return;
  55858. }
  55859. this._filter = value;
  55860. this._disposeBlurPostProcesses();
  55861. this._applyFilterValues();
  55862. this._light._markMeshesAsLightDirty();
  55863. },
  55864. enumerable: true,
  55865. configurable: true
  55866. });
  55867. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  55868. get: function () {
  55869. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  55870. },
  55871. set: function (value) {
  55872. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  55873. return;
  55874. }
  55875. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  55876. },
  55877. enumerable: true,
  55878. configurable: true
  55879. });
  55880. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  55881. get: function () {
  55882. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55883. return this.useExponentialShadowMap;
  55884. },
  55885. set: function (value) {
  55886. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55887. this.useExponentialShadowMap = value;
  55888. },
  55889. enumerable: true,
  55890. configurable: true
  55891. });
  55892. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  55893. get: function () {
  55894. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55895. return this.useBlurExponentialShadowMap;
  55896. },
  55897. set: function (value) {
  55898. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55899. this.useBlurExponentialShadowMap = value;
  55900. },
  55901. enumerable: true,
  55902. configurable: true
  55903. });
  55904. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  55905. get: function () {
  55906. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  55907. },
  55908. set: function (value) {
  55909. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  55910. return;
  55911. }
  55912. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55913. },
  55914. enumerable: true,
  55915. configurable: true
  55916. });
  55917. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  55918. get: function () {
  55919. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  55920. },
  55921. set: function (value) {
  55922. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55923. return;
  55924. }
  55925. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55926. },
  55927. enumerable: true,
  55928. configurable: true
  55929. });
  55930. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  55931. get: function () {
  55932. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  55933. },
  55934. set: function (value) {
  55935. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  55936. return;
  55937. }
  55938. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55939. },
  55940. enumerable: true,
  55941. configurable: true
  55942. });
  55943. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  55944. get: function () {
  55945. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  55946. },
  55947. set: function (value) {
  55948. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55949. return;
  55950. }
  55951. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55952. },
  55953. enumerable: true,
  55954. configurable: true
  55955. });
  55956. /**
  55957. * Returns the darkness value (float).
  55958. */
  55959. ShadowGenerator.prototype.getDarkness = function () {
  55960. return this._darkness;
  55961. };
  55962. /**
  55963. * Sets the ShadowGenerator darkness value (float <= 1.0).
  55964. * Returns the ShadowGenerator.
  55965. */
  55966. ShadowGenerator.prototype.setDarkness = function (darkness) {
  55967. if (darkness >= 1.0)
  55968. this._darkness = 1.0;
  55969. else if (darkness <= 0.0)
  55970. this._darkness = 0.0;
  55971. else
  55972. this._darkness = darkness;
  55973. return this;
  55974. };
  55975. /**
  55976. * Sets the ability to have transparent shadow (boolean).
  55977. * Returns the ShadowGenerator.
  55978. */
  55979. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  55980. this._transparencyShadow = hasShadow;
  55981. return this;
  55982. };
  55983. /**
  55984. * Returns a RenderTargetTexture object : the shadow map texture.
  55985. */
  55986. ShadowGenerator.prototype.getShadowMap = function () {
  55987. return this._shadowMap;
  55988. };
  55989. /**
  55990. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  55991. */
  55992. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  55993. if (this._shadowMap2) {
  55994. return this._shadowMap2;
  55995. }
  55996. return this._shadowMap;
  55997. };
  55998. /**
  55999. * Helper function to add a mesh and its descendants to the list of shadow casters
  56000. * @param mesh Mesh to add
  56001. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  56002. */
  56003. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  56004. if (includeDescendants === void 0) { includeDescendants = true; }
  56005. if (!this._shadowMap) {
  56006. return this;
  56007. }
  56008. if (!this._shadowMap.renderList) {
  56009. this._shadowMap.renderList = [];
  56010. }
  56011. this._shadowMap.renderList.push(mesh);
  56012. if (includeDescendants) {
  56013. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  56014. }
  56015. return this;
  56016. var _a;
  56017. };
  56018. /**
  56019. * Helper function to remove a mesh and its descendants from the list of shadow casters
  56020. * @param mesh Mesh to remove
  56021. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  56022. */
  56023. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  56024. if (includeDescendants === void 0) { includeDescendants = true; }
  56025. if (!this._shadowMap || !this._shadowMap.renderList) {
  56026. return this;
  56027. }
  56028. var index = this._shadowMap.renderList.indexOf(mesh);
  56029. if (index !== -1) {
  56030. this._shadowMap.renderList.splice(index, 1);
  56031. }
  56032. if (includeDescendants) {
  56033. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  56034. var child = _a[_i];
  56035. this.removeShadowCaster(child);
  56036. }
  56037. }
  56038. return this;
  56039. };
  56040. /**
  56041. * Returns the associated light object.
  56042. */
  56043. ShadowGenerator.prototype.getLight = function () {
  56044. return this._light;
  56045. };
  56046. ShadowGenerator.prototype._initializeGenerator = function () {
  56047. this._light._markMeshesAsLightDirty();
  56048. this._initializeShadowMap();
  56049. };
  56050. ShadowGenerator.prototype._initializeShadowMap = function () {
  56051. var _this = this;
  56052. // Render target
  56053. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  56054. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56055. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56056. this._shadowMap.anisotropicFilteringLevel = 1;
  56057. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56058. this._shadowMap.renderParticles = false;
  56059. this._shadowMap.ignoreCameraViewport = true;
  56060. // Record Face Index before render.
  56061. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  56062. _this._currentFaceIndex = faceIndex;
  56063. });
  56064. // Custom render function.
  56065. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  56066. // Blur if required afer render.
  56067. this._shadowMap.onAfterUnbindObservable.add(function () {
  56068. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  56069. return;
  56070. }
  56071. var shadowMap = _this.getShadowMapForRendering();
  56072. if (shadowMap) {
  56073. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  56074. }
  56075. });
  56076. // Clear according to the chosen filter.
  56077. this._shadowMap.onClearObservable.add(function (engine) {
  56078. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  56079. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  56080. }
  56081. else {
  56082. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56083. }
  56084. });
  56085. };
  56086. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  56087. var _this = this;
  56088. var engine = this._scene.getEngine();
  56089. var targetSize = this._mapSize / this.blurScale;
  56090. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  56091. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  56092. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56093. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56094. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56095. }
  56096. if (this.useKernelBlur) {
  56097. 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);
  56098. this._kernelBlurXPostprocess.width = targetSize;
  56099. this._kernelBlurXPostprocess.height = targetSize;
  56100. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  56101. effect.setTexture("textureSampler", _this._shadowMap);
  56102. });
  56103. 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);
  56104. this._kernelBlurXPostprocess.autoClear = false;
  56105. this._kernelBlurYPostprocess.autoClear = false;
  56106. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56107. this._kernelBlurXPostprocess.packedFloat = true;
  56108. this._kernelBlurYPostprocess.packedFloat = true;
  56109. }
  56110. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  56111. }
  56112. else {
  56113. 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);
  56114. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  56115. effect.setFloat2("screenSize", targetSize, targetSize);
  56116. effect.setTexture("textureSampler", _this._shadowMap);
  56117. });
  56118. this._boxBlurPostprocess.autoClear = false;
  56119. this._blurPostProcesses = [this._boxBlurPostprocess];
  56120. }
  56121. };
  56122. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56123. var index;
  56124. var engine = this._scene.getEngine();
  56125. if (depthOnlySubMeshes.length) {
  56126. engine.setColorWrite(false);
  56127. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56128. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  56129. }
  56130. engine.setColorWrite(true);
  56131. }
  56132. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56133. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  56134. }
  56135. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56136. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  56137. }
  56138. if (this._transparencyShadow) {
  56139. for (index = 0; index < transparentSubMeshes.length; index++) {
  56140. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  56141. }
  56142. }
  56143. };
  56144. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  56145. var _this = this;
  56146. var mesh = subMesh.getRenderingMesh();
  56147. var scene = this._scene;
  56148. var engine = scene.getEngine();
  56149. var material = subMesh.getMaterial();
  56150. if (!material) {
  56151. return;
  56152. }
  56153. // Culling
  56154. engine.setState(material.backFaceCulling);
  56155. // Managing instances
  56156. var batch = mesh._getInstancesRenderList(subMesh._id);
  56157. if (batch.mustReturn) {
  56158. return;
  56159. }
  56160. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  56161. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  56162. engine.enableEffect(this._effect);
  56163. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  56164. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  56165. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  56166. this._effect.setVector3("lightPosition", this.getLight().position);
  56167. if (scene.activeCamera) {
  56168. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  56169. }
  56170. // Alpha test
  56171. if (material && material.needAlphaTesting()) {
  56172. var alphaTexture = material.getAlphaTestTexture();
  56173. if (alphaTexture) {
  56174. this._effect.setTexture("diffuseSampler", alphaTexture);
  56175. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  56176. }
  56177. }
  56178. // Bones
  56179. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56180. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  56181. }
  56182. if (this.forceBackFacesOnly) {
  56183. engine.setState(true, 0, false, true);
  56184. }
  56185. // Draw
  56186. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  56187. if (this.forceBackFacesOnly) {
  56188. engine.setState(true, 0, false, false);
  56189. }
  56190. }
  56191. else {
  56192. // Need to reset refresh rate of the shadowMap
  56193. if (this._shadowMap) {
  56194. this._shadowMap.resetRefreshCounter();
  56195. }
  56196. }
  56197. };
  56198. ShadowGenerator.prototype._applyFilterValues = function () {
  56199. if (!this._shadowMap) {
  56200. return;
  56201. }
  56202. if (this.filter === ShadowGenerator.FILTER_NONE) {
  56203. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56204. }
  56205. else {
  56206. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56207. }
  56208. };
  56209. /**
  56210. * Force shader compilation including textures ready check
  56211. */
  56212. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  56213. var _this = this;
  56214. var localOptions = __assign({ useInstances: false }, options);
  56215. var shadowMap = this.getShadowMap();
  56216. if (!shadowMap) {
  56217. if (onCompiled) {
  56218. onCompiled(this);
  56219. }
  56220. return;
  56221. }
  56222. var renderList = shadowMap.renderList;
  56223. if (!renderList) {
  56224. if (onCompiled) {
  56225. onCompiled(this);
  56226. }
  56227. return;
  56228. }
  56229. var subMeshes = new Array();
  56230. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  56231. var mesh = renderList_1[_i];
  56232. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  56233. }
  56234. if (subMeshes.length === 0) {
  56235. if (onCompiled) {
  56236. onCompiled(this);
  56237. }
  56238. return;
  56239. }
  56240. var currentIndex = 0;
  56241. var checkReady = function () {
  56242. if (!_this._scene || !_this._scene.getEngine()) {
  56243. return;
  56244. }
  56245. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  56246. currentIndex++;
  56247. if (currentIndex >= subMeshes.length) {
  56248. if (onCompiled) {
  56249. onCompiled(_this);
  56250. }
  56251. return;
  56252. }
  56253. }
  56254. setTimeout(checkReady, 16);
  56255. };
  56256. checkReady();
  56257. };
  56258. /**
  56259. * Boolean : true when the ShadowGenerator is finally computed.
  56260. */
  56261. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  56262. var defines = [];
  56263. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56264. defines.push("#define FLOAT");
  56265. }
  56266. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  56267. defines.push("#define ESM");
  56268. }
  56269. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56270. var mesh = subMesh.getMesh();
  56271. var material = subMesh.getMaterial();
  56272. // Alpha test
  56273. if (material && material.needAlphaTesting()) {
  56274. var alphaTexture = material.getAlphaTestTexture();
  56275. if (alphaTexture) {
  56276. defines.push("#define ALPHATEST");
  56277. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56278. attribs.push(BABYLON.VertexBuffer.UVKind);
  56279. defines.push("#define UV1");
  56280. }
  56281. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56282. if (alphaTexture.coordinatesIndex === 1) {
  56283. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56284. defines.push("#define UV2");
  56285. }
  56286. }
  56287. }
  56288. }
  56289. // Bones
  56290. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56291. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56292. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56293. if (mesh.numBoneInfluencers > 4) {
  56294. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56295. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56296. }
  56297. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56298. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56299. }
  56300. else {
  56301. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56302. }
  56303. // Instances
  56304. if (useInstances) {
  56305. defines.push("#define INSTANCES");
  56306. attribs.push("world0");
  56307. attribs.push("world1");
  56308. attribs.push("world2");
  56309. attribs.push("world3");
  56310. }
  56311. // Get correct effect
  56312. var join = defines.join("\n");
  56313. if (this._cachedDefines !== join) {
  56314. this._cachedDefines = join;
  56315. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  56316. }
  56317. if (!this._effect.isReady()) {
  56318. return false;
  56319. }
  56320. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  56321. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  56322. this._initializeBlurRTTAndPostProcesses();
  56323. }
  56324. }
  56325. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  56326. return false;
  56327. }
  56328. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  56329. return false;
  56330. }
  56331. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  56332. return false;
  56333. }
  56334. return true;
  56335. };
  56336. /**
  56337. * This creates the defines related to the standard BJS materials.
  56338. */
  56339. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  56340. var scene = this._scene;
  56341. var light = this._light;
  56342. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  56343. return;
  56344. }
  56345. defines["SHADOW" + lightIndex] = true;
  56346. if (this.usePoissonSampling) {
  56347. defines["SHADOWPCF" + lightIndex] = true;
  56348. }
  56349. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  56350. defines["SHADOWESM" + lightIndex] = true;
  56351. }
  56352. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  56353. defines["SHADOWCLOSEESM" + lightIndex] = true;
  56354. }
  56355. if (light.needCube()) {
  56356. defines["SHADOWCUBE" + lightIndex] = true;
  56357. }
  56358. };
  56359. /**
  56360. * This binds shadow lights related to the standard BJS materials.
  56361. * It implies the unifroms available on the materials are the standard BJS ones.
  56362. */
  56363. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  56364. var light = this._light;
  56365. var scene = this._scene;
  56366. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  56367. return;
  56368. }
  56369. var camera = scene.activeCamera;
  56370. if (!camera) {
  56371. return;
  56372. }
  56373. var shadowMap = this.getShadowMap();
  56374. if (!shadowMap) {
  56375. return;
  56376. }
  56377. if (!light.needCube()) {
  56378. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  56379. }
  56380. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  56381. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  56382. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  56383. };
  56384. // Methods
  56385. /**
  56386. * Returns a Matrix object : the updated transformation matrix.
  56387. */
  56388. ShadowGenerator.prototype.getTransformMatrix = function () {
  56389. var scene = this._scene;
  56390. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  56391. return this._transformMatrix;
  56392. }
  56393. this._currentRenderID = scene.getRenderId();
  56394. this._currentFaceIndexCache = this._currentFaceIndex;
  56395. var lightPosition = this._light.position;
  56396. if (this._light.computeTransformedInformation()) {
  56397. lightPosition = this._light.transformedPosition;
  56398. }
  56399. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  56400. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  56401. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  56402. }
  56403. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  56404. this._cachedPosition = lightPosition.clone();
  56405. this._cachedDirection = this._lightDirection.clone();
  56406. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  56407. var shadowMap = this.getShadowMap();
  56408. if (shadowMap) {
  56409. var renderList = shadowMap.renderList;
  56410. if (renderList) {
  56411. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  56412. }
  56413. }
  56414. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  56415. }
  56416. return this._transformMatrix;
  56417. };
  56418. ShadowGenerator.prototype.recreateShadowMap = function () {
  56419. var shadowMap = this._shadowMap;
  56420. if (!shadowMap) {
  56421. return;
  56422. }
  56423. // Track render list.
  56424. var renderList = shadowMap.renderList;
  56425. // Clean up existing data.
  56426. this._disposeRTTandPostProcesses();
  56427. // Reinitializes.
  56428. this._initializeGenerator();
  56429. // Reaffect the filter to ensure a correct fallback if necessary.
  56430. this.filter = this.filter;
  56431. // Reaffect the filter.
  56432. this._applyFilterValues();
  56433. // Reaffect Render List.
  56434. this._shadowMap.renderList = renderList;
  56435. };
  56436. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  56437. if (this._shadowMap2) {
  56438. this._shadowMap2.dispose();
  56439. this._shadowMap2 = null;
  56440. }
  56441. if (this._boxBlurPostprocess) {
  56442. this._boxBlurPostprocess.dispose();
  56443. this._boxBlurPostprocess = null;
  56444. }
  56445. if (this._kernelBlurXPostprocess) {
  56446. this._kernelBlurXPostprocess.dispose();
  56447. this._kernelBlurXPostprocess = null;
  56448. }
  56449. if (this._kernelBlurYPostprocess) {
  56450. this._kernelBlurYPostprocess.dispose();
  56451. this._kernelBlurYPostprocess = null;
  56452. }
  56453. this._blurPostProcesses = [];
  56454. };
  56455. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  56456. if (this._shadowMap) {
  56457. this._shadowMap.dispose();
  56458. this._shadowMap = null;
  56459. }
  56460. this._disposeBlurPostProcesses();
  56461. };
  56462. /**
  56463. * Disposes the ShadowGenerator.
  56464. * Returns nothing.
  56465. */
  56466. ShadowGenerator.prototype.dispose = function () {
  56467. this._disposeRTTandPostProcesses();
  56468. if (this._light) {
  56469. this._light._shadowGenerator = null;
  56470. this._light._markMeshesAsLightDirty();
  56471. }
  56472. };
  56473. /**
  56474. * Serializes the ShadowGenerator and returns a serializationObject.
  56475. */
  56476. ShadowGenerator.prototype.serialize = function () {
  56477. var serializationObject = {};
  56478. var shadowMap = this.getShadowMap();
  56479. if (!shadowMap) {
  56480. return serializationObject;
  56481. }
  56482. serializationObject.lightId = this._light.id;
  56483. serializationObject.mapSize = shadowMap.getRenderSize();
  56484. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  56485. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  56486. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  56487. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  56488. serializationObject.usePoissonSampling = this.usePoissonSampling;
  56489. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  56490. serializationObject.depthScale = this.depthScale;
  56491. serializationObject.darkness = this.getDarkness();
  56492. serializationObject.blurBoxOffset = this.blurBoxOffset;
  56493. serializationObject.blurKernel = this.blurKernel;
  56494. serializationObject.blurScale = this.blurScale;
  56495. serializationObject.useKernelBlur = this.useKernelBlur;
  56496. serializationObject.transparencyShadow = this._transparencyShadow;
  56497. serializationObject.renderList = [];
  56498. if (shadowMap.renderList) {
  56499. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  56500. var mesh = shadowMap.renderList[meshIndex];
  56501. serializationObject.renderList.push(mesh.id);
  56502. }
  56503. }
  56504. return serializationObject;
  56505. };
  56506. /**
  56507. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  56508. */
  56509. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  56510. //casting to point light, as light is missing the position attr and typescript complains.
  56511. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  56512. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  56513. var shadowMap = shadowGenerator.getShadowMap();
  56514. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  56515. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  56516. meshes.forEach(function (mesh) {
  56517. if (!shadowMap) {
  56518. return;
  56519. }
  56520. if (!shadowMap.renderList) {
  56521. shadowMap.renderList = [];
  56522. }
  56523. shadowMap.renderList.push(mesh);
  56524. });
  56525. }
  56526. if (parsedShadowGenerator.usePoissonSampling) {
  56527. shadowGenerator.usePoissonSampling = true;
  56528. }
  56529. else if (parsedShadowGenerator.useExponentialShadowMap) {
  56530. shadowGenerator.useExponentialShadowMap = true;
  56531. }
  56532. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  56533. shadowGenerator.useBlurExponentialShadowMap = true;
  56534. }
  56535. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  56536. shadowGenerator.useCloseExponentialShadowMap = true;
  56537. }
  56538. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  56539. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  56540. }
  56541. else if (parsedShadowGenerator.useVarianceShadowMap) {
  56542. shadowGenerator.useExponentialShadowMap = true;
  56543. }
  56544. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  56545. shadowGenerator.useBlurExponentialShadowMap = true;
  56546. }
  56547. if (parsedShadowGenerator.depthScale) {
  56548. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  56549. }
  56550. if (parsedShadowGenerator.blurScale) {
  56551. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  56552. }
  56553. if (parsedShadowGenerator.blurBoxOffset) {
  56554. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  56555. }
  56556. if (parsedShadowGenerator.useKernelBlur) {
  56557. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  56558. }
  56559. if (parsedShadowGenerator.blurKernel) {
  56560. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  56561. }
  56562. if (parsedShadowGenerator.bias !== undefined) {
  56563. shadowGenerator.bias = parsedShadowGenerator.bias;
  56564. }
  56565. if (parsedShadowGenerator.darkness) {
  56566. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  56567. }
  56568. if (parsedShadowGenerator.transparencyShadow) {
  56569. shadowGenerator.setTransparencyShadow(true);
  56570. }
  56571. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  56572. return shadowGenerator;
  56573. };
  56574. ShadowGenerator._FILTER_NONE = 0;
  56575. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  56576. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  56577. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  56578. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  56579. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  56580. return ShadowGenerator;
  56581. }());
  56582. BABYLON.ShadowGenerator = ShadowGenerator;
  56583. })(BABYLON || (BABYLON = {}));
  56584. //# sourceMappingURL=babylon.shadowGenerator.js.map
  56585. var BABYLON;
  56586. (function (BABYLON) {
  56587. var DefaultLoadingScreen = /** @class */ (function () {
  56588. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  56589. if (_loadingText === void 0) { _loadingText = ""; }
  56590. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  56591. var _this = this;
  56592. this._renderingCanvas = _renderingCanvas;
  56593. this._loadingText = _loadingText;
  56594. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  56595. // Resize
  56596. this._resizeLoadingUI = function () {
  56597. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  56598. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  56599. if (!_this._loadingDiv) {
  56600. return;
  56601. }
  56602. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  56603. _this._loadingDiv.style.left = canvasRect.left + "px";
  56604. _this._loadingDiv.style.top = canvasRect.top + "px";
  56605. _this._loadingDiv.style.width = canvasRect.width + "px";
  56606. _this._loadingDiv.style.height = canvasRect.height + "px";
  56607. };
  56608. }
  56609. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  56610. if (this._loadingDiv) {
  56611. // Do not add a loading screen if there is already one
  56612. return;
  56613. }
  56614. this._loadingDiv = document.createElement("div");
  56615. this._loadingDiv.id = "babylonjsLoadingDiv";
  56616. this._loadingDiv.style.opacity = "0";
  56617. this._loadingDiv.style.transition = "opacity 1.5s ease";
  56618. this._loadingDiv.style.pointerEvents = "none";
  56619. // Loading text
  56620. this._loadingTextDiv = document.createElement("div");
  56621. this._loadingTextDiv.style.position = "absolute";
  56622. this._loadingTextDiv.style.left = "0";
  56623. this._loadingTextDiv.style.top = "50%";
  56624. this._loadingTextDiv.style.marginTop = "80px";
  56625. this._loadingTextDiv.style.width = "100%";
  56626. this._loadingTextDiv.style.height = "20px";
  56627. this._loadingTextDiv.style.fontFamily = "Arial";
  56628. this._loadingTextDiv.style.fontSize = "14px";
  56629. this._loadingTextDiv.style.color = "white";
  56630. this._loadingTextDiv.style.textAlign = "center";
  56631. this._loadingTextDiv.innerHTML = "Loading";
  56632. this._loadingDiv.appendChild(this._loadingTextDiv);
  56633. //set the predefined text
  56634. this._loadingTextDiv.innerHTML = this._loadingText;
  56635. // Generating keyframes
  56636. var style = document.createElement('style');
  56637. style.type = 'text/css';
  56638. 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 }";
  56639. style.innerHTML = keyFrames;
  56640. document.getElementsByTagName('head')[0].appendChild(style);
  56641. // Loading img
  56642. var imgBack = new Image();
  56643. 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";
  56644. imgBack.style.position = "absolute";
  56645. imgBack.style.left = "50%";
  56646. imgBack.style.top = "50%";
  56647. imgBack.style.marginLeft = "-60px";
  56648. imgBack.style.marginTop = "-60px";
  56649. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  56650. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  56651. imgBack.style.transformOrigin = "50% 50%";
  56652. imgBack.style.webkitTransformOrigin = "50% 50%";
  56653. this._loadingDiv.appendChild(imgBack);
  56654. this._resizeLoadingUI();
  56655. window.addEventListener("resize", this._resizeLoadingUI);
  56656. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  56657. document.body.appendChild(this._loadingDiv);
  56658. this._loadingDiv.style.opacity = "1";
  56659. };
  56660. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  56661. var _this = this;
  56662. if (!this._loadingDiv) {
  56663. return;
  56664. }
  56665. var onTransitionEnd = function () {
  56666. if (!_this._loadingDiv) {
  56667. return;
  56668. }
  56669. document.body.removeChild(_this._loadingDiv);
  56670. window.removeEventListener("resize", _this._resizeLoadingUI);
  56671. _this._loadingDiv = null;
  56672. };
  56673. this._loadingDiv.style.opacity = "0";
  56674. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  56675. };
  56676. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  56677. set: function (text) {
  56678. this._loadingText = text;
  56679. if (this._loadingTextDiv) {
  56680. this._loadingTextDiv.innerHTML = this._loadingText;
  56681. }
  56682. },
  56683. enumerable: true,
  56684. configurable: true
  56685. });
  56686. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  56687. get: function () {
  56688. return this._loadingDivBackgroundColor;
  56689. },
  56690. set: function (color) {
  56691. this._loadingDivBackgroundColor = color;
  56692. if (!this._loadingDiv) {
  56693. return;
  56694. }
  56695. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  56696. },
  56697. enumerable: true,
  56698. configurable: true
  56699. });
  56700. return DefaultLoadingScreen;
  56701. }());
  56702. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  56703. })(BABYLON || (BABYLON = {}));
  56704. //# sourceMappingURL=babylon.loadingScreen.js.map
  56705. var BABYLON;
  56706. (function (BABYLON) {
  56707. var SceneLoaderProgressEvent = /** @class */ (function () {
  56708. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  56709. this.lengthComputable = lengthComputable;
  56710. this.loaded = loaded;
  56711. this.total = total;
  56712. }
  56713. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  56714. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  56715. };
  56716. return SceneLoaderProgressEvent;
  56717. }());
  56718. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  56719. var SceneLoader = /** @class */ (function () {
  56720. function SceneLoader() {
  56721. }
  56722. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  56723. get: function () {
  56724. return 0;
  56725. },
  56726. enumerable: true,
  56727. configurable: true
  56728. });
  56729. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  56730. get: function () {
  56731. return 1;
  56732. },
  56733. enumerable: true,
  56734. configurable: true
  56735. });
  56736. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  56737. get: function () {
  56738. return 2;
  56739. },
  56740. enumerable: true,
  56741. configurable: true
  56742. });
  56743. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  56744. get: function () {
  56745. return 3;
  56746. },
  56747. enumerable: true,
  56748. configurable: true
  56749. });
  56750. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  56751. get: function () {
  56752. return SceneLoader._ForceFullSceneLoadingForIncremental;
  56753. },
  56754. set: function (value) {
  56755. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  56756. },
  56757. enumerable: true,
  56758. configurable: true
  56759. });
  56760. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  56761. get: function () {
  56762. return SceneLoader._ShowLoadingScreen;
  56763. },
  56764. set: function (value) {
  56765. SceneLoader._ShowLoadingScreen = value;
  56766. },
  56767. enumerable: true,
  56768. configurable: true
  56769. });
  56770. Object.defineProperty(SceneLoader, "loggingLevel", {
  56771. get: function () {
  56772. return SceneLoader._loggingLevel;
  56773. },
  56774. set: function (value) {
  56775. SceneLoader._loggingLevel = value;
  56776. },
  56777. enumerable: true,
  56778. configurable: true
  56779. });
  56780. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  56781. get: function () {
  56782. return SceneLoader._CleanBoneMatrixWeights;
  56783. },
  56784. set: function (value) {
  56785. SceneLoader._CleanBoneMatrixWeights = value;
  56786. },
  56787. enumerable: true,
  56788. configurable: true
  56789. });
  56790. SceneLoader._getDefaultPlugin = function () {
  56791. return SceneLoader._registeredPlugins[".babylon"];
  56792. };
  56793. SceneLoader._getPluginForExtension = function (extension) {
  56794. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  56795. if (registeredPlugin) {
  56796. return registeredPlugin;
  56797. }
  56798. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  56799. return SceneLoader._getDefaultPlugin();
  56800. };
  56801. SceneLoader._getPluginForDirectLoad = function (data) {
  56802. for (var extension in SceneLoader._registeredPlugins) {
  56803. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  56804. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  56805. return SceneLoader._registeredPlugins[extension];
  56806. }
  56807. }
  56808. return SceneLoader._getDefaultPlugin();
  56809. };
  56810. SceneLoader._getPluginForFilename = function (sceneFilename) {
  56811. if (sceneFilename.name) {
  56812. sceneFilename = sceneFilename.name;
  56813. }
  56814. var queryStringPosition = sceneFilename.indexOf("?");
  56815. if (queryStringPosition !== -1) {
  56816. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  56817. }
  56818. var dotPosition = sceneFilename.lastIndexOf(".");
  56819. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  56820. return SceneLoader._getPluginForExtension(extension);
  56821. };
  56822. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  56823. SceneLoader._getDirectLoad = function (sceneFilename) {
  56824. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  56825. return sceneFilename.substr(5);
  56826. }
  56827. return null;
  56828. };
  56829. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  56830. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  56831. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  56832. var plugin;
  56833. if (registeredPlugin.plugin.createPlugin) {
  56834. plugin = registeredPlugin.plugin.createPlugin();
  56835. }
  56836. else {
  56837. plugin = registeredPlugin.plugin;
  56838. }
  56839. var useArrayBuffer = registeredPlugin.isBinary;
  56840. var database;
  56841. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  56842. var dataCallback = function (data, responseURL) {
  56843. if (scene.isDisposed) {
  56844. onError("Scene has been disposed");
  56845. return;
  56846. }
  56847. scene.database = database;
  56848. onSuccess(plugin, data, responseURL);
  56849. };
  56850. var request = null;
  56851. var pluginDisposed = false;
  56852. var onDisposeObservable = plugin.onDisposeObservable;
  56853. if (onDisposeObservable) {
  56854. onDisposeObservable.add(function () {
  56855. pluginDisposed = true;
  56856. if (request) {
  56857. request.abort();
  56858. request = null;
  56859. }
  56860. onDispose();
  56861. });
  56862. }
  56863. var manifestChecked = function () {
  56864. if (pluginDisposed) {
  56865. return;
  56866. }
  56867. var url = rootUrl + sceneFilename;
  56868. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  56869. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  56870. } : undefined, database, useArrayBuffer, function (request, exception) {
  56871. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  56872. });
  56873. };
  56874. if (directLoad) {
  56875. dataCallback(directLoad);
  56876. return plugin;
  56877. }
  56878. if (rootUrl.indexOf("file:") === -1) {
  56879. if (scene.getEngine().enableOfflineSupport) {
  56880. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  56881. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  56882. }
  56883. else {
  56884. manifestChecked();
  56885. }
  56886. }
  56887. else {
  56888. var fileOrString = sceneFilename;
  56889. if (fileOrString.name) {
  56890. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  56891. }
  56892. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  56893. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  56894. }
  56895. else {
  56896. onError("Unable to find file named " + sceneFilename);
  56897. }
  56898. }
  56899. return plugin;
  56900. };
  56901. // Public functions
  56902. SceneLoader.GetPluginForExtension = function (extension) {
  56903. return SceneLoader._getPluginForExtension(extension).plugin;
  56904. };
  56905. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  56906. return !!SceneLoader._registeredPlugins[extension];
  56907. };
  56908. SceneLoader.RegisterPlugin = function (plugin) {
  56909. if (typeof plugin.extensions === "string") {
  56910. var extension = plugin.extensions;
  56911. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56912. plugin: plugin,
  56913. isBinary: false
  56914. };
  56915. }
  56916. else {
  56917. var extensions = plugin.extensions;
  56918. Object.keys(extensions).forEach(function (extension) {
  56919. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56920. plugin: plugin,
  56921. isBinary: extensions[extension].isBinary
  56922. };
  56923. });
  56924. }
  56925. };
  56926. /**
  56927. * Import meshes into a scene
  56928. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  56929. * @param rootUrl a string that defines the root url for scene and resources
  56930. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56931. * @param scene the instance of BABYLON.Scene to append to
  56932. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  56933. * @param onProgress a callback with a progress event for each file being loaded
  56934. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56935. */
  56936. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56937. if (onSuccess === void 0) { onSuccess = null; }
  56938. if (onProgress === void 0) { onProgress = null; }
  56939. if (onError === void 0) { onError = null; }
  56940. if (pluginExtension === void 0) { pluginExtension = null; }
  56941. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56942. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56943. return null;
  56944. }
  56945. var loadingToken = {};
  56946. scene._addPendingData(loadingToken);
  56947. var disposeHandler = function () {
  56948. scene._removePendingData(loadingToken);
  56949. };
  56950. var errorHandler = function (message, exception) {
  56951. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  56952. if (onError) {
  56953. onError(scene, errorMessage, exception);
  56954. }
  56955. else {
  56956. BABYLON.Tools.Error(errorMessage);
  56957. // should the exception be thrown?
  56958. }
  56959. disposeHandler();
  56960. };
  56961. var progressHandler = onProgress ? function (event) {
  56962. try {
  56963. onProgress(event);
  56964. }
  56965. catch (e) {
  56966. errorHandler("Error in onProgress callback", e);
  56967. }
  56968. } : undefined;
  56969. var successHandler = function (meshes, particleSystems, skeletons) {
  56970. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  56971. if (onSuccess) {
  56972. try {
  56973. onSuccess(meshes, particleSystems, skeletons);
  56974. }
  56975. catch (e) {
  56976. errorHandler("Error in onSuccess callback", e);
  56977. }
  56978. }
  56979. scene._removePendingData(loadingToken);
  56980. };
  56981. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56982. if (plugin.rewriteRootURL) {
  56983. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  56984. }
  56985. if (plugin.importMesh) {
  56986. var syncedPlugin = plugin;
  56987. var meshes = new Array();
  56988. var particleSystems = new Array();
  56989. var skeletons = new Array();
  56990. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  56991. return;
  56992. }
  56993. scene.loadingPluginName = plugin.name;
  56994. successHandler(meshes, particleSystems, skeletons);
  56995. }
  56996. else {
  56997. var asyncedPlugin = plugin;
  56998. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  56999. scene.loadingPluginName = plugin.name;
  57000. successHandler(meshes, particleSystems, skeletons);
  57001. }, progressHandler, errorHandler);
  57002. }
  57003. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57004. };
  57005. /**
  57006. * Load a scene
  57007. * @param rootUrl a string that defines the root url for scene and resources
  57008. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57009. * @param engine is the instance of BABYLON.Engine to use to create the scene
  57010. * @param onSuccess a callback with the scene when import succeeds
  57011. * @param onProgress a callback with a progress event for each file being loaded
  57012. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57013. */
  57014. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  57015. if (onSuccess === void 0) { onSuccess = null; }
  57016. if (onProgress === void 0) { onProgress = null; }
  57017. if (onError === void 0) { onError = null; }
  57018. if (pluginExtension === void 0) { pluginExtension = null; }
  57019. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  57020. };
  57021. /**
  57022. * Append a scene
  57023. * @param rootUrl a string that defines the root url for scene and resources
  57024. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  57025. * @param scene is the instance of BABYLON.Scene to append to
  57026. * @param onSuccess a callback with the scene when import succeeds
  57027. * @param onProgress a callback with a progress event for each file being loaded
  57028. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  57029. */
  57030. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57031. if (onSuccess === void 0) { onSuccess = null; }
  57032. if (onProgress === void 0) { onProgress = null; }
  57033. if (onError === void 0) { onError = null; }
  57034. if (pluginExtension === void 0) { pluginExtension = null; }
  57035. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57036. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57037. return null;
  57038. }
  57039. if (SceneLoader.ShowLoadingScreen) {
  57040. scene.getEngine().displayLoadingUI();
  57041. }
  57042. var loadingToken = {};
  57043. scene._addPendingData(loadingToken);
  57044. var disposeHandler = function () {
  57045. scene._removePendingData(loadingToken);
  57046. scene.getEngine().hideLoadingUI();
  57047. };
  57048. var errorHandler = function (message, exception) {
  57049. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  57050. if (onError) {
  57051. onError(scene, errorMessage, exception);
  57052. }
  57053. else {
  57054. BABYLON.Tools.Error(errorMessage);
  57055. // should the exception be thrown?
  57056. }
  57057. disposeHandler();
  57058. };
  57059. var progressHandler = onProgress ? function (event) {
  57060. try {
  57061. onProgress(event);
  57062. }
  57063. catch (e) {
  57064. errorHandler("Error in onProgress callback", e);
  57065. }
  57066. } : undefined;
  57067. var successHandler = function () {
  57068. if (onSuccess) {
  57069. try {
  57070. onSuccess(scene);
  57071. }
  57072. catch (e) {
  57073. errorHandler("Error in onSuccess callback", e);
  57074. }
  57075. }
  57076. scene._removePendingData(loadingToken);
  57077. };
  57078. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57079. if (plugin.load) {
  57080. var syncedPlugin = plugin;
  57081. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  57082. return;
  57083. }
  57084. scene.loadingPluginName = plugin.name;
  57085. successHandler();
  57086. }
  57087. else {
  57088. var asyncedPlugin = plugin;
  57089. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  57090. scene.loadingPluginName = plugin.name;
  57091. successHandler();
  57092. }, progressHandler, errorHandler);
  57093. }
  57094. if (SceneLoader.ShowLoadingScreen) {
  57095. scene.executeWhenReady(function () {
  57096. scene.getEngine().hideLoadingUI();
  57097. });
  57098. }
  57099. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57100. };
  57101. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  57102. if (onSuccess === void 0) { onSuccess = null; }
  57103. if (onProgress === void 0) { onProgress = null; }
  57104. if (onError === void 0) { onError = null; }
  57105. if (pluginExtension === void 0) { pluginExtension = null; }
  57106. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  57107. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  57108. return null;
  57109. }
  57110. var loadingToken = {};
  57111. scene._addPendingData(loadingToken);
  57112. var disposeHandler = function () {
  57113. scene._removePendingData(loadingToken);
  57114. };
  57115. var errorHandler = function (message, exception) {
  57116. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  57117. if (onError) {
  57118. onError(scene, errorMessage, exception);
  57119. }
  57120. else {
  57121. BABYLON.Tools.Error(errorMessage);
  57122. // should the exception be thrown?
  57123. }
  57124. disposeHandler();
  57125. };
  57126. var progressHandler = onProgress ? function (event) {
  57127. try {
  57128. onProgress(event);
  57129. }
  57130. catch (e) {
  57131. errorHandler("Error in onProgress callback", e);
  57132. }
  57133. } : undefined;
  57134. var successHandler = function (assets) {
  57135. if (onSuccess) {
  57136. try {
  57137. onSuccess(assets);
  57138. }
  57139. catch (e) {
  57140. errorHandler("Error in onSuccess callback", e);
  57141. }
  57142. }
  57143. scene._removePendingData(loadingToken);
  57144. };
  57145. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  57146. if (plugin.loadAssets) {
  57147. var syncedPlugin = plugin;
  57148. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  57149. if (!assetContainer) {
  57150. return;
  57151. }
  57152. scene.loadingPluginName = plugin.name;
  57153. successHandler(assetContainer);
  57154. }
  57155. else if (plugin.loadAssetsAsync) {
  57156. var asyncedPlugin = plugin;
  57157. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  57158. if (assetContainer) {
  57159. scene.loadingPluginName = plugin.name;
  57160. successHandler(assetContainer);
  57161. }
  57162. }, progressHandler, errorHandler);
  57163. }
  57164. else {
  57165. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  57166. }
  57167. if (SceneLoader.ShowLoadingScreen) {
  57168. scene.executeWhenReady(function () {
  57169. scene.getEngine().hideLoadingUI();
  57170. });
  57171. }
  57172. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  57173. };
  57174. // Flags
  57175. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  57176. SceneLoader._ShowLoadingScreen = true;
  57177. SceneLoader._CleanBoneMatrixWeights = false;
  57178. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  57179. // Members
  57180. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  57181. SceneLoader._registeredPlugins = {};
  57182. return SceneLoader;
  57183. }());
  57184. BABYLON.SceneLoader = SceneLoader;
  57185. ;
  57186. })(BABYLON || (BABYLON = {}));
  57187. //# sourceMappingURL=babylon.sceneLoader.js.map
  57188. var BABYLON;
  57189. (function (BABYLON) {
  57190. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  57191. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  57192. var parsedMaterial = parsedData.materials[index];
  57193. if (parsedMaterial.id === id) {
  57194. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  57195. }
  57196. }
  57197. return null;
  57198. };
  57199. var isDescendantOf = function (mesh, names, hierarchyIds) {
  57200. for (var i in names) {
  57201. if (mesh.name === names[i]) {
  57202. hierarchyIds.push(mesh.id);
  57203. return true;
  57204. }
  57205. }
  57206. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  57207. hierarchyIds.push(mesh.id);
  57208. return true;
  57209. }
  57210. return false;
  57211. };
  57212. var logOperation = function (operation, producer) {
  57213. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  57214. };
  57215. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  57216. if (addToScene === void 0) { addToScene = false; }
  57217. var container = new BABYLON.AssetContainer(scene);
  57218. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57219. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57220. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57221. // and avoid problems with multiple concurrent .babylon loads.
  57222. var log = "importScene has failed JSON parse";
  57223. try {
  57224. var parsedData = JSON.parse(data);
  57225. log = "";
  57226. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  57227. var index;
  57228. var cache;
  57229. // Lights
  57230. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  57231. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  57232. var parsedLight = parsedData.lights[index];
  57233. var light = BABYLON.Light.Parse(parsedLight, scene);
  57234. if (light) {
  57235. container.lights.push(light);
  57236. log += (index === 0 ? "\n\tLights:" : "");
  57237. log += "\n\t\t" + light.toString(fullDetails);
  57238. }
  57239. }
  57240. }
  57241. // Animations
  57242. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  57243. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  57244. var parsedAnimation = parsedData.animations[index];
  57245. var animation = BABYLON.Animation.Parse(parsedAnimation);
  57246. scene.animations.push(animation);
  57247. container.animations.push(animation);
  57248. log += (index === 0 ? "\n\tAnimations:" : "");
  57249. log += "\n\t\t" + animation.toString(fullDetails);
  57250. }
  57251. }
  57252. // Materials
  57253. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  57254. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  57255. var parsedMaterial = parsedData.materials[index];
  57256. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  57257. container.materials.push(mat);
  57258. log += (index === 0 ? "\n\tMaterials:" : "");
  57259. log += "\n\t\t" + mat.toString(fullDetails);
  57260. }
  57261. }
  57262. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  57263. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  57264. var parsedMultiMaterial = parsedData.multiMaterials[index];
  57265. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  57266. container.multiMaterials.push(mmat);
  57267. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  57268. log += "\n\t\t" + mmat.toString(fullDetails);
  57269. }
  57270. }
  57271. // Morph targets
  57272. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  57273. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  57274. var managerData = _a[_i];
  57275. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  57276. }
  57277. }
  57278. // Skeletons
  57279. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  57280. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  57281. var parsedSkeleton = parsedData.skeletons[index];
  57282. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  57283. container.skeletons.push(skeleton);
  57284. log += (index === 0 ? "\n\tSkeletons:" : "");
  57285. log += "\n\t\t" + skeleton.toString(fullDetails);
  57286. }
  57287. }
  57288. // Geometries
  57289. var geometries = parsedData.geometries;
  57290. if (geometries !== undefined && geometries !== null) {
  57291. var addedGeometry = new Array();
  57292. // Boxes
  57293. var boxes = geometries.boxes;
  57294. if (boxes !== undefined && boxes !== null) {
  57295. for (index = 0, cache = boxes.length; index < cache; index++) {
  57296. var parsedBox = boxes[index];
  57297. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  57298. }
  57299. }
  57300. // Spheres
  57301. var spheres = geometries.spheres;
  57302. if (spheres !== undefined && spheres !== null) {
  57303. for (index = 0, cache = spheres.length; index < cache; index++) {
  57304. var parsedSphere = spheres[index];
  57305. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  57306. }
  57307. }
  57308. // Cylinders
  57309. var cylinders = geometries.cylinders;
  57310. if (cylinders !== undefined && cylinders !== null) {
  57311. for (index = 0, cache = cylinders.length; index < cache; index++) {
  57312. var parsedCylinder = cylinders[index];
  57313. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  57314. }
  57315. }
  57316. // Toruses
  57317. var toruses = geometries.toruses;
  57318. if (toruses !== undefined && toruses !== null) {
  57319. for (index = 0, cache = toruses.length; index < cache; index++) {
  57320. var parsedTorus = toruses[index];
  57321. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  57322. }
  57323. }
  57324. // Grounds
  57325. var grounds = geometries.grounds;
  57326. if (grounds !== undefined && grounds !== null) {
  57327. for (index = 0, cache = grounds.length; index < cache; index++) {
  57328. var parsedGround = grounds[index];
  57329. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  57330. }
  57331. }
  57332. // Planes
  57333. var planes = geometries.planes;
  57334. if (planes !== undefined && planes !== null) {
  57335. for (index = 0, cache = planes.length; index < cache; index++) {
  57336. var parsedPlane = planes[index];
  57337. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  57338. }
  57339. }
  57340. // TorusKnots
  57341. var torusKnots = geometries.torusKnots;
  57342. if (torusKnots !== undefined && torusKnots !== null) {
  57343. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  57344. var parsedTorusKnot = torusKnots[index];
  57345. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  57346. }
  57347. }
  57348. // VertexData
  57349. var vertexData = geometries.vertexData;
  57350. if (vertexData !== undefined && vertexData !== null) {
  57351. for (index = 0, cache = vertexData.length; index < cache; index++) {
  57352. var parsedVertexData = vertexData[index];
  57353. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  57354. }
  57355. }
  57356. addedGeometry.forEach(function (g) {
  57357. if (g) {
  57358. container.geometries.push(g);
  57359. }
  57360. });
  57361. }
  57362. // Transform nodes
  57363. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  57364. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  57365. var parsedTransformNode = parsedData.transformNodes[index];
  57366. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  57367. container.transformNodes.push(node);
  57368. }
  57369. }
  57370. // Meshes
  57371. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  57372. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  57373. var parsedMesh = parsedData.meshes[index];
  57374. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  57375. container.meshes.push(mesh);
  57376. log += (index === 0 ? "\n\tMeshes:" : "");
  57377. log += "\n\t\t" + mesh.toString(fullDetails);
  57378. }
  57379. }
  57380. // Cameras
  57381. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  57382. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  57383. var parsedCamera = parsedData.cameras[index];
  57384. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  57385. container.cameras.push(camera);
  57386. log += (index === 0 ? "\n\tCameras:" : "");
  57387. log += "\n\t\t" + camera.toString(fullDetails);
  57388. }
  57389. }
  57390. // Browsing all the graph to connect the dots
  57391. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  57392. var camera = scene.cameras[index];
  57393. if (camera._waitingParentId) {
  57394. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  57395. camera._waitingParentId = null;
  57396. }
  57397. }
  57398. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  57399. var light_1 = scene.lights[index];
  57400. if (light_1 && light_1._waitingParentId) {
  57401. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  57402. light_1._waitingParentId = null;
  57403. }
  57404. }
  57405. // Sounds
  57406. // TODO: add sound
  57407. var loadedSounds = [];
  57408. var loadedSound;
  57409. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  57410. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  57411. var parsedSound = parsedData.sounds[index];
  57412. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57413. if (!parsedSound.url)
  57414. parsedSound.url = parsedSound.name;
  57415. if (!loadedSounds[parsedSound.url]) {
  57416. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  57417. loadedSounds[parsedSound.url] = loadedSound;
  57418. container.sounds.push(loadedSound);
  57419. }
  57420. else {
  57421. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  57422. }
  57423. }
  57424. else {
  57425. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  57426. }
  57427. }
  57428. }
  57429. loadedSounds = [];
  57430. // Connect parents & children and parse actions
  57431. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  57432. var transformNode = scene.transformNodes[index];
  57433. if (transformNode._waitingParentId) {
  57434. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  57435. transformNode._waitingParentId = null;
  57436. }
  57437. }
  57438. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57439. var mesh = scene.meshes[index];
  57440. if (mesh._waitingParentId) {
  57441. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  57442. mesh._waitingParentId = null;
  57443. }
  57444. if (mesh._waitingActions) {
  57445. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  57446. mesh._waitingActions = null;
  57447. }
  57448. }
  57449. // freeze world matrix application
  57450. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57451. var currentMesh = scene.meshes[index];
  57452. if (currentMesh._waitingFreezeWorldMatrix) {
  57453. currentMesh.freezeWorldMatrix();
  57454. currentMesh._waitingFreezeWorldMatrix = null;
  57455. }
  57456. else {
  57457. currentMesh.computeWorldMatrix(true);
  57458. }
  57459. }
  57460. // Particles Systems
  57461. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57462. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57463. var parsedParticleSystem = parsedData.particleSystems[index];
  57464. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57465. container.particleSystems.push(ps);
  57466. }
  57467. }
  57468. // Lens flares
  57469. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  57470. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  57471. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  57472. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  57473. container.lensFlareSystems.push(lf);
  57474. }
  57475. }
  57476. // Shadows
  57477. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  57478. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  57479. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  57480. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  57481. container.shadowGenerators.push(sg);
  57482. }
  57483. }
  57484. // Lights exclusions / inclusions
  57485. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  57486. var light_2 = scene.lights[index];
  57487. // Excluded check
  57488. if (light_2._excludedMeshesIds.length > 0) {
  57489. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  57490. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  57491. if (excludedMesh) {
  57492. light_2.excludedMeshes.push(excludedMesh);
  57493. }
  57494. }
  57495. light_2._excludedMeshesIds = [];
  57496. }
  57497. // Included check
  57498. if (light_2._includedOnlyMeshesIds.length > 0) {
  57499. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  57500. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  57501. if (includedOnlyMesh) {
  57502. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  57503. }
  57504. }
  57505. light_2._includedOnlyMeshesIds = [];
  57506. }
  57507. }
  57508. // Actions (scene)
  57509. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  57510. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  57511. }
  57512. if (!addToScene) {
  57513. container.removeAllFromScene();
  57514. }
  57515. return container;
  57516. }
  57517. catch (err) {
  57518. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  57519. if (onError) {
  57520. onError(msg, err);
  57521. }
  57522. else {
  57523. BABYLON.Tools.Log(msg);
  57524. throw err;
  57525. }
  57526. }
  57527. finally {
  57528. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57529. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57530. }
  57531. }
  57532. return null;
  57533. };
  57534. BABYLON.SceneLoader.RegisterPlugin({
  57535. name: "babylon.js",
  57536. extensions: ".babylon",
  57537. canDirectLoad: function (data) {
  57538. if (data.indexOf("babylon") !== -1) {
  57539. return true;
  57540. }
  57541. return false;
  57542. },
  57543. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  57544. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57545. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57546. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57547. // and avoid problems with multiple concurrent .babylon loads.
  57548. var log = "importMesh has failed JSON parse";
  57549. try {
  57550. var parsedData = JSON.parse(data);
  57551. log = "";
  57552. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  57553. if (!meshesNames) {
  57554. meshesNames = null;
  57555. }
  57556. else if (!Array.isArray(meshesNames)) {
  57557. meshesNames = [meshesNames];
  57558. }
  57559. var hierarchyIds = new Array();
  57560. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  57561. var loadedSkeletonsIds = [];
  57562. var loadedMaterialsIds = [];
  57563. var index;
  57564. var cache;
  57565. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  57566. var parsedMesh = parsedData.meshes[index];
  57567. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  57568. if (meshesNames !== null) {
  57569. // Remove found mesh name from list.
  57570. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  57571. }
  57572. //Geometry?
  57573. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  57574. //does the file contain geometries?
  57575. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  57576. //find the correct geometry and add it to the scene
  57577. var found = false;
  57578. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  57579. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  57580. return;
  57581. }
  57582. else {
  57583. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  57584. if (parsedGeometryData.id === parsedMesh.geometryId) {
  57585. switch (geometryType) {
  57586. case "boxes":
  57587. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  57588. break;
  57589. case "spheres":
  57590. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  57591. break;
  57592. case "cylinders":
  57593. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  57594. break;
  57595. case "toruses":
  57596. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  57597. break;
  57598. case "grounds":
  57599. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  57600. break;
  57601. case "planes":
  57602. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  57603. break;
  57604. case "torusKnots":
  57605. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  57606. break;
  57607. case "vertexData":
  57608. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  57609. break;
  57610. }
  57611. found = true;
  57612. }
  57613. });
  57614. }
  57615. });
  57616. if (found === false) {
  57617. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  57618. }
  57619. }
  57620. }
  57621. // Material ?
  57622. if (parsedMesh.materialId) {
  57623. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  57624. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  57625. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  57626. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  57627. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  57628. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  57629. var subMatId = parsedMultiMaterial.materials[matIndex];
  57630. loadedMaterialsIds.push(subMatId);
  57631. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  57632. log += "\n\tMaterial " + mat.toString(fullDetails);
  57633. }
  57634. loadedMaterialsIds.push(parsedMultiMaterial.id);
  57635. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  57636. materialFound = true;
  57637. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  57638. break;
  57639. }
  57640. }
  57641. }
  57642. if (materialFound === false) {
  57643. loadedMaterialsIds.push(parsedMesh.materialId);
  57644. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  57645. if (!mat) {
  57646. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  57647. }
  57648. else {
  57649. log += "\n\tMaterial " + mat.toString(fullDetails);
  57650. }
  57651. }
  57652. }
  57653. // Skeleton ?
  57654. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  57655. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  57656. if (skeletonAlreadyLoaded === false) {
  57657. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  57658. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  57659. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  57660. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  57661. skeletons.push(skeleton);
  57662. loadedSkeletonsIds.push(parsedSkeleton.id);
  57663. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  57664. }
  57665. }
  57666. }
  57667. }
  57668. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  57669. meshes.push(mesh);
  57670. log += "\n\tMesh " + mesh.toString(fullDetails);
  57671. }
  57672. }
  57673. // Connecting parents
  57674. var currentMesh;
  57675. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57676. currentMesh = scene.meshes[index];
  57677. if (currentMesh._waitingParentId) {
  57678. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  57679. currentMesh._waitingParentId = null;
  57680. }
  57681. }
  57682. // freeze and compute world matrix application
  57683. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57684. currentMesh = scene.meshes[index];
  57685. if (currentMesh._waitingFreezeWorldMatrix) {
  57686. currentMesh.freezeWorldMatrix();
  57687. currentMesh._waitingFreezeWorldMatrix = null;
  57688. }
  57689. else {
  57690. currentMesh.computeWorldMatrix(true);
  57691. }
  57692. }
  57693. }
  57694. // Particles
  57695. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57696. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57697. var parsedParticleSystem = parsedData.particleSystems[index];
  57698. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  57699. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  57700. }
  57701. }
  57702. }
  57703. return true;
  57704. }
  57705. catch (err) {
  57706. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  57707. if (onError) {
  57708. onError(msg, err);
  57709. }
  57710. else {
  57711. BABYLON.Tools.Log(msg);
  57712. throw err;
  57713. }
  57714. }
  57715. finally {
  57716. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57717. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57718. }
  57719. }
  57720. return false;
  57721. },
  57722. load: function (scene, data, rootUrl, onError) {
  57723. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57724. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57725. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57726. // and avoid problems with multiple concurrent .babylon loads.
  57727. var log = "importScene has failed JSON parse";
  57728. try {
  57729. var parsedData = JSON.parse(data);
  57730. log = "";
  57731. // Scene
  57732. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  57733. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  57734. }
  57735. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  57736. scene.autoClear = parsedData.autoClear;
  57737. }
  57738. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  57739. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  57740. }
  57741. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  57742. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  57743. }
  57744. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  57745. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  57746. }
  57747. // Fog
  57748. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  57749. scene.fogMode = parsedData.fogMode;
  57750. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  57751. scene.fogStart = parsedData.fogStart;
  57752. scene.fogEnd = parsedData.fogEnd;
  57753. scene.fogDensity = parsedData.fogDensity;
  57754. log += "\tFog mode for scene: ";
  57755. switch (scene.fogMode) {
  57756. // getters not compiling, so using hardcoded
  57757. case 1:
  57758. log += "exp\n";
  57759. break;
  57760. case 2:
  57761. log += "exp2\n";
  57762. break;
  57763. case 3:
  57764. log += "linear\n";
  57765. break;
  57766. }
  57767. }
  57768. //Physics
  57769. if (parsedData.physicsEnabled) {
  57770. var physicsPlugin;
  57771. if (parsedData.physicsEngine === "cannon") {
  57772. physicsPlugin = new BABYLON.CannonJSPlugin();
  57773. }
  57774. else if (parsedData.physicsEngine === "oimo") {
  57775. physicsPlugin = new BABYLON.OimoJSPlugin();
  57776. }
  57777. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  57778. //else - default engine, which is currently oimo
  57779. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  57780. scene.enablePhysics(physicsGravity, physicsPlugin);
  57781. }
  57782. // Metadata
  57783. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  57784. scene.metadata = parsedData.metadata;
  57785. }
  57786. //collisions, if defined. otherwise, default is true
  57787. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  57788. scene.collisionsEnabled = parsedData.collisionsEnabled;
  57789. }
  57790. scene.workerCollisions = !!parsedData.workerCollisions;
  57791. var container = loadAssets(scene, data, rootUrl, onerror, true);
  57792. if (!container) {
  57793. return false;
  57794. }
  57795. if (parsedData.autoAnimate) {
  57796. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  57797. }
  57798. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  57799. scene.setActiveCameraByID(parsedData.activeCameraID);
  57800. }
  57801. // Environment texture
  57802. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  57803. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  57804. if (parsedData.createDefaultSkybox === true) {
  57805. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  57806. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  57807. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  57808. }
  57809. }
  57810. // Finish
  57811. return true;
  57812. }
  57813. catch (err) {
  57814. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  57815. if (onError) {
  57816. onError(msg, err);
  57817. }
  57818. else {
  57819. BABYLON.Tools.Log(msg);
  57820. throw err;
  57821. }
  57822. }
  57823. finally {
  57824. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57825. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57826. }
  57827. }
  57828. return false;
  57829. },
  57830. loadAssets: function (scene, data, rootUrl, onError) {
  57831. var container = loadAssets(scene, data, rootUrl, onerror);
  57832. return container;
  57833. }
  57834. });
  57835. })(BABYLON || (BABYLON = {}));
  57836. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  57837. var BABYLON;
  57838. (function (BABYLON) {
  57839. var FilesInput = /** @class */ (function () {
  57840. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  57841. this.onProcessFileCallback = function () { return true; };
  57842. this._engine = engine;
  57843. this._currentScene = scene;
  57844. this._sceneLoadedCallback = sceneLoadedCallback;
  57845. this._progressCallback = progressCallback;
  57846. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  57847. this._textureLoadingCallback = textureLoadingCallback;
  57848. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  57849. this._onReloadCallback = onReloadCallback;
  57850. this._errorCallback = errorCallback;
  57851. }
  57852. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  57853. var _this = this;
  57854. if (elementToMonitor) {
  57855. this._elementToMonitor = elementToMonitor;
  57856. this._dragEnterHandler = function (e) { _this.drag(e); };
  57857. this._dragOverHandler = function (e) { _this.drag(e); };
  57858. this._dropHandler = function (e) { _this.drop(e); };
  57859. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  57860. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  57861. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  57862. }
  57863. };
  57864. FilesInput.prototype.dispose = function () {
  57865. if (!this._elementToMonitor) {
  57866. return;
  57867. }
  57868. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  57869. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  57870. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  57871. };
  57872. FilesInput.prototype.renderFunction = function () {
  57873. if (this._additionalRenderLoopLogicCallback) {
  57874. this._additionalRenderLoopLogicCallback();
  57875. }
  57876. if (this._currentScene) {
  57877. if (this._textureLoadingCallback) {
  57878. var remaining = this._currentScene.getWaitingItemsCount();
  57879. if (remaining > 0) {
  57880. this._textureLoadingCallback(remaining);
  57881. }
  57882. }
  57883. this._currentScene.render();
  57884. }
  57885. };
  57886. FilesInput.prototype.drag = function (e) {
  57887. e.stopPropagation();
  57888. e.preventDefault();
  57889. };
  57890. FilesInput.prototype.drop = function (eventDrop) {
  57891. eventDrop.stopPropagation();
  57892. eventDrop.preventDefault();
  57893. this.loadFiles(eventDrop);
  57894. };
  57895. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  57896. var _this = this;
  57897. var reader = folder.createReader();
  57898. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  57899. reader.readEntries(function (entries) {
  57900. remaining.count += entries.length;
  57901. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  57902. var entry = entries_1[_i];
  57903. if (entry.isFile) {
  57904. entry.file(function (file) {
  57905. file.correctName = relativePath + file.name;
  57906. files.push(file);
  57907. if (--remaining.count === 0) {
  57908. callback();
  57909. }
  57910. });
  57911. }
  57912. else if (entry.isDirectory) {
  57913. _this._traverseFolder(entry, files, remaining, callback);
  57914. }
  57915. }
  57916. if (--remaining.count) {
  57917. callback();
  57918. }
  57919. });
  57920. };
  57921. FilesInput.prototype._processFiles = function (files) {
  57922. for (var i = 0; i < files.length; i++) {
  57923. var name = files[i].correctName.toLowerCase();
  57924. var extension = name.split('.').pop();
  57925. if (!this.onProcessFileCallback(files[i], name, extension)) {
  57926. continue;
  57927. }
  57928. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  57929. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  57930. this._sceneFileToLoad = files[i];
  57931. }
  57932. else {
  57933. FilesInput.FilesToLoad[name] = files[i];
  57934. }
  57935. }
  57936. };
  57937. FilesInput.prototype.loadFiles = function (event) {
  57938. var _this = this;
  57939. if (this._startingProcessingFilesCallback)
  57940. this._startingProcessingFilesCallback();
  57941. // Handling data transfer via drag'n'drop
  57942. if (event && event.dataTransfer && event.dataTransfer.files) {
  57943. this._filesToLoad = event.dataTransfer.files;
  57944. }
  57945. // Handling files from input files
  57946. if (event && event.target && event.target.files) {
  57947. this._filesToLoad = event.target.files;
  57948. }
  57949. if (this._filesToLoad && this._filesToLoad.length > 0) {
  57950. var files_1 = new Array();
  57951. var folders = [];
  57952. var items = event.dataTransfer ? event.dataTransfer.items : null;
  57953. for (var i = 0; i < this._filesToLoad.length; i++) {
  57954. var fileToLoad = this._filesToLoad[i];
  57955. var name_1 = fileToLoad.name.toLowerCase();
  57956. var entry = void 0;
  57957. fileToLoad.correctName = name_1;
  57958. if (items) {
  57959. var item = items[i];
  57960. if (item.getAsEntry) {
  57961. entry = item.getAsEntry();
  57962. }
  57963. else if (item.webkitGetAsEntry) {
  57964. entry = item.webkitGetAsEntry();
  57965. }
  57966. }
  57967. if (!entry) {
  57968. files_1.push(fileToLoad);
  57969. }
  57970. else {
  57971. if (entry.isDirectory) {
  57972. folders.push(entry);
  57973. }
  57974. else {
  57975. files_1.push(fileToLoad);
  57976. }
  57977. }
  57978. }
  57979. if (folders.length === 0) {
  57980. this._processFiles(files_1);
  57981. this._processReload();
  57982. }
  57983. else {
  57984. var remaining = { count: folders.length };
  57985. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  57986. var folder = folders_1[_i];
  57987. this._traverseFolder(folder, files_1, remaining, function () {
  57988. _this._processFiles(files_1);
  57989. if (remaining.count === 0) {
  57990. _this._processReload();
  57991. }
  57992. });
  57993. }
  57994. }
  57995. }
  57996. };
  57997. FilesInput.prototype._processReload = function () {
  57998. if (this._onReloadCallback) {
  57999. this._onReloadCallback(this._sceneFileToLoad);
  58000. }
  58001. else {
  58002. this.reload();
  58003. }
  58004. };
  58005. FilesInput.prototype.reload = function () {
  58006. var _this = this;
  58007. // If a scene file has been provided
  58008. if (this._sceneFileToLoad) {
  58009. if (this._currentScene) {
  58010. if (BABYLON.Tools.errorsCount > 0) {
  58011. BABYLON.Tools.ClearLogCache();
  58012. }
  58013. this._engine.stopRenderLoop();
  58014. this._currentScene.dispose();
  58015. }
  58016. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  58017. _this._currentScene = newScene;
  58018. if (_this._sceneLoadedCallback) {
  58019. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  58020. }
  58021. // Wait for textures and shaders to be ready
  58022. _this._currentScene.executeWhenReady(function () {
  58023. _this._engine.runRenderLoop(function () {
  58024. _this.renderFunction();
  58025. });
  58026. });
  58027. }, function (progress) {
  58028. if (_this._progressCallback) {
  58029. _this._progressCallback(progress);
  58030. }
  58031. }, function (scene, message) {
  58032. _this._currentScene = scene;
  58033. if (_this._errorCallback) {
  58034. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  58035. }
  58036. });
  58037. }
  58038. else {
  58039. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  58040. }
  58041. };
  58042. FilesInput.FilesToLoad = {};
  58043. return FilesInput;
  58044. }());
  58045. BABYLON.FilesInput = FilesInput;
  58046. })(BABYLON || (BABYLON = {}));
  58047. //# sourceMappingURL=babylon.filesInput.js.map
  58048. var BABYLON;
  58049. (function (BABYLON) {
  58050. /**
  58051. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58052. * The underlying implementation relies on an associative array to ensure the best performances.
  58053. * The value can be anything including 'null' but except 'undefined'
  58054. */
  58055. var StringDictionary = /** @class */ (function () {
  58056. function StringDictionary() {
  58057. this._count = 0;
  58058. this._data = {};
  58059. }
  58060. /**
  58061. * This will clear this dictionary and copy the content from the 'source' one.
  58062. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58063. * @param source the dictionary to take the content from and copy to this dictionary
  58064. */
  58065. StringDictionary.prototype.copyFrom = function (source) {
  58066. var _this = this;
  58067. this.clear();
  58068. source.forEach(function (t, v) { return _this.add(t, v); });
  58069. };
  58070. /**
  58071. * Get a value based from its key
  58072. * @param key the given key to get the matching value from
  58073. * @return the value if found, otherwise undefined is returned
  58074. */
  58075. StringDictionary.prototype.get = function (key) {
  58076. var val = this._data[key];
  58077. if (val !== undefined) {
  58078. return val;
  58079. }
  58080. return undefined;
  58081. };
  58082. /**
  58083. * Get a value from its key or add it if it doesn't exist.
  58084. * This method will ensure you that a given key/data will be present in the dictionary.
  58085. * @param key the given key to get the matching value from
  58086. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58087. * The factory will only be invoked if there's no data for the given key.
  58088. * @return the value corresponding to the key.
  58089. */
  58090. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58091. var val = this.get(key);
  58092. if (val !== undefined) {
  58093. return val;
  58094. }
  58095. val = factory(key);
  58096. if (val) {
  58097. this.add(key, val);
  58098. }
  58099. return val;
  58100. };
  58101. /**
  58102. * Get a value from its key if present in the dictionary otherwise add it
  58103. * @param key the key to get the value from
  58104. * @param val if there's no such key/value pair in the dictionary add it with this value
  58105. * @return the value corresponding to the key
  58106. */
  58107. StringDictionary.prototype.getOrAdd = function (key, val) {
  58108. var curVal = this.get(key);
  58109. if (curVal !== undefined) {
  58110. return curVal;
  58111. }
  58112. this.add(key, val);
  58113. return val;
  58114. };
  58115. /**
  58116. * Check if there's a given key in the dictionary
  58117. * @param key the key to check for
  58118. * @return true if the key is present, false otherwise
  58119. */
  58120. StringDictionary.prototype.contains = function (key) {
  58121. return this._data[key] !== undefined;
  58122. };
  58123. /**
  58124. * Add a new key and its corresponding value
  58125. * @param key the key to add
  58126. * @param value the value corresponding to the key
  58127. * @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
  58128. */
  58129. StringDictionary.prototype.add = function (key, value) {
  58130. if (this._data[key] !== undefined) {
  58131. return false;
  58132. }
  58133. this._data[key] = value;
  58134. ++this._count;
  58135. return true;
  58136. };
  58137. StringDictionary.prototype.set = function (key, value) {
  58138. if (this._data[key] === undefined) {
  58139. return false;
  58140. }
  58141. this._data[key] = value;
  58142. return true;
  58143. };
  58144. /**
  58145. * Get the element of the given key and remove it from the dictionary
  58146. * @param key
  58147. */
  58148. StringDictionary.prototype.getAndRemove = function (key) {
  58149. var val = this.get(key);
  58150. if (val !== undefined) {
  58151. delete this._data[key];
  58152. --this._count;
  58153. return val;
  58154. }
  58155. return null;
  58156. };
  58157. /**
  58158. * Remove a key/value from the dictionary.
  58159. * @param key the key to remove
  58160. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  58161. */
  58162. StringDictionary.prototype.remove = function (key) {
  58163. if (this.contains(key)) {
  58164. delete this._data[key];
  58165. --this._count;
  58166. return true;
  58167. }
  58168. return false;
  58169. };
  58170. /**
  58171. * Clear the whole content of the dictionary
  58172. */
  58173. StringDictionary.prototype.clear = function () {
  58174. this._data = {};
  58175. this._count = 0;
  58176. };
  58177. Object.defineProperty(StringDictionary.prototype, "count", {
  58178. get: function () {
  58179. return this._count;
  58180. },
  58181. enumerable: true,
  58182. configurable: true
  58183. });
  58184. /**
  58185. * Execute a callback on each key/val of the dictionary.
  58186. * Note that you can remove any element in this dictionary in the callback implementation
  58187. * @param callback the callback to execute on a given key/value pair
  58188. */
  58189. StringDictionary.prototype.forEach = function (callback) {
  58190. for (var cur in this._data) {
  58191. var val = this._data[cur];
  58192. callback(cur, val);
  58193. }
  58194. };
  58195. /**
  58196. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  58197. * If the callback returns null or undefined the method will iterate to the next key/value pair
  58198. * Note that you can remove any element in this dictionary in the callback implementation
  58199. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  58200. */
  58201. StringDictionary.prototype.first = function (callback) {
  58202. for (var cur in this._data) {
  58203. var val = this._data[cur];
  58204. var res = callback(cur, val);
  58205. if (res) {
  58206. return res;
  58207. }
  58208. }
  58209. return null;
  58210. };
  58211. return StringDictionary;
  58212. }());
  58213. BABYLON.StringDictionary = StringDictionary;
  58214. })(BABYLON || (BABYLON = {}));
  58215. //# sourceMappingURL=babylon.stringDictionary.js.map
  58216. var BABYLON;
  58217. (function (BABYLON) {
  58218. var Tags = /** @class */ (function () {
  58219. function Tags() {
  58220. }
  58221. Tags.EnableFor = function (obj) {
  58222. obj._tags = obj._tags || {};
  58223. obj.hasTags = function () {
  58224. return Tags.HasTags(obj);
  58225. };
  58226. obj.addTags = function (tagsString) {
  58227. return Tags.AddTagsTo(obj, tagsString);
  58228. };
  58229. obj.removeTags = function (tagsString) {
  58230. return Tags.RemoveTagsFrom(obj, tagsString);
  58231. };
  58232. obj.matchesTagsQuery = function (tagsQuery) {
  58233. return Tags.MatchesQuery(obj, tagsQuery);
  58234. };
  58235. };
  58236. Tags.DisableFor = function (obj) {
  58237. delete obj._tags;
  58238. delete obj.hasTags;
  58239. delete obj.addTags;
  58240. delete obj.removeTags;
  58241. delete obj.matchesTagsQuery;
  58242. };
  58243. Tags.HasTags = function (obj) {
  58244. if (!obj._tags) {
  58245. return false;
  58246. }
  58247. return !BABYLON.Tools.IsEmpty(obj._tags);
  58248. };
  58249. Tags.GetTags = function (obj, asString) {
  58250. if (asString === void 0) { asString = true; }
  58251. if (!obj._tags) {
  58252. return null;
  58253. }
  58254. if (asString) {
  58255. var tagsArray = [];
  58256. for (var tag in obj._tags) {
  58257. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  58258. tagsArray.push(tag);
  58259. }
  58260. }
  58261. return tagsArray.join(" ");
  58262. }
  58263. else {
  58264. return obj._tags;
  58265. }
  58266. };
  58267. // the tags 'true' and 'false' are reserved and cannot be used as tags
  58268. // a tag cannot start with '||', '&&', and '!'
  58269. // it cannot contain whitespaces
  58270. Tags.AddTagsTo = function (obj, tagsString) {
  58271. if (!tagsString) {
  58272. return;
  58273. }
  58274. if (typeof tagsString !== "string") {
  58275. return;
  58276. }
  58277. var tags = tagsString.split(" ");
  58278. tags.forEach(function (tag, index, array) {
  58279. Tags._AddTagTo(obj, tag);
  58280. });
  58281. };
  58282. Tags._AddTagTo = function (obj, tag) {
  58283. tag = tag.trim();
  58284. if (tag === "" || tag === "true" || tag === "false") {
  58285. return;
  58286. }
  58287. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  58288. return;
  58289. }
  58290. Tags.EnableFor(obj);
  58291. obj._tags[tag] = true;
  58292. };
  58293. Tags.RemoveTagsFrom = function (obj, tagsString) {
  58294. if (!Tags.HasTags(obj)) {
  58295. return;
  58296. }
  58297. var tags = tagsString.split(" ");
  58298. for (var t in tags) {
  58299. Tags._RemoveTagFrom(obj, tags[t]);
  58300. }
  58301. };
  58302. Tags._RemoveTagFrom = function (obj, tag) {
  58303. delete obj._tags[tag];
  58304. };
  58305. Tags.MatchesQuery = function (obj, tagsQuery) {
  58306. if (tagsQuery === undefined) {
  58307. return true;
  58308. }
  58309. if (tagsQuery === "") {
  58310. return Tags.HasTags(obj);
  58311. }
  58312. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  58313. };
  58314. return Tags;
  58315. }());
  58316. BABYLON.Tags = Tags;
  58317. })(BABYLON || (BABYLON = {}));
  58318. //# sourceMappingURL=babylon.tags.js.map
  58319. var BABYLON;
  58320. (function (BABYLON) {
  58321. var AndOrNotEvaluator = /** @class */ (function () {
  58322. function AndOrNotEvaluator() {
  58323. }
  58324. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  58325. if (!query.match(/\([^\(\)]*\)/g)) {
  58326. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  58327. }
  58328. else {
  58329. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  58330. // remove parenthesis
  58331. r = r.slice(1, r.length - 1);
  58332. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  58333. });
  58334. }
  58335. if (query === "true") {
  58336. return true;
  58337. }
  58338. if (query === "false") {
  58339. return false;
  58340. }
  58341. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  58342. };
  58343. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  58344. evaluateCallback = evaluateCallback || (function (r) {
  58345. return r === "true" ? true : false;
  58346. });
  58347. var result;
  58348. var or = parenthesisContent.split("||");
  58349. for (var i in or) {
  58350. if (or.hasOwnProperty(i)) {
  58351. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  58352. var and = ori.split("&&");
  58353. if (and.length > 1) {
  58354. for (var j = 0; j < and.length; ++j) {
  58355. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  58356. if (andj !== "true" && andj !== "false") {
  58357. if (andj[0] === "!") {
  58358. result = !evaluateCallback(andj.substring(1));
  58359. }
  58360. else {
  58361. result = evaluateCallback(andj);
  58362. }
  58363. }
  58364. else {
  58365. result = andj === "true" ? true : false;
  58366. }
  58367. if (!result) {
  58368. ori = "false";
  58369. break;
  58370. }
  58371. }
  58372. }
  58373. if (result || ori === "true") {
  58374. result = true;
  58375. break;
  58376. }
  58377. // result equals false (or undefined)
  58378. if (ori !== "true" && ori !== "false") {
  58379. if (ori[0] === "!") {
  58380. result = !evaluateCallback(ori.substring(1));
  58381. }
  58382. else {
  58383. result = evaluateCallback(ori);
  58384. }
  58385. }
  58386. else {
  58387. result = ori === "true" ? true : false;
  58388. }
  58389. }
  58390. }
  58391. // the whole parenthesis scope is replaced by 'true' or 'false'
  58392. return result ? "true" : "false";
  58393. };
  58394. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  58395. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  58396. // remove whitespaces
  58397. r = r.replace(/[\s]/g, function () { return ""; });
  58398. return r.length % 2 ? "!" : "";
  58399. });
  58400. booleanString = booleanString.trim();
  58401. if (booleanString === "!true") {
  58402. booleanString = "false";
  58403. }
  58404. else if (booleanString === "!false") {
  58405. booleanString = "true";
  58406. }
  58407. return booleanString;
  58408. };
  58409. return AndOrNotEvaluator;
  58410. }());
  58411. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  58412. })(BABYLON || (BABYLON = {}));
  58413. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  58414. var BABYLON;
  58415. (function (BABYLON) {
  58416. var Database = /** @class */ (function () {
  58417. function Database(urlToScene, callbackManifestChecked) {
  58418. // Handling various flavors of prefixed version of IndexedDB
  58419. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  58420. this.callbackManifestChecked = callbackManifestChecked;
  58421. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  58422. this.db = null;
  58423. this._enableSceneOffline = false;
  58424. this._enableTexturesOffline = false;
  58425. this.manifestVersionFound = 0;
  58426. this.mustUpdateRessources = false;
  58427. this.hasReachedQuota = false;
  58428. if (!Database.IDBStorageEnabled) {
  58429. this.callbackManifestChecked(true);
  58430. }
  58431. else {
  58432. this.checkManifestFile();
  58433. }
  58434. }
  58435. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  58436. get: function () {
  58437. return this._enableSceneOffline;
  58438. },
  58439. enumerable: true,
  58440. configurable: true
  58441. });
  58442. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  58443. get: function () {
  58444. return this._enableTexturesOffline;
  58445. },
  58446. enumerable: true,
  58447. configurable: true
  58448. });
  58449. Database.prototype.checkManifestFile = function () {
  58450. var _this = this;
  58451. var noManifestFile = function () {
  58452. _this._enableSceneOffline = false;
  58453. _this._enableTexturesOffline = false;
  58454. _this.callbackManifestChecked(false);
  58455. };
  58456. var timeStampUsed = false;
  58457. var manifestURL = this.currentSceneUrl + ".manifest";
  58458. var xhr = new XMLHttpRequest();
  58459. if (navigator.onLine) {
  58460. // Adding a timestamp to by-pass browsers' cache
  58461. timeStampUsed = true;
  58462. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  58463. }
  58464. xhr.open("GET", manifestURL, true);
  58465. xhr.addEventListener("load", function () {
  58466. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  58467. try {
  58468. var manifestFile = JSON.parse(xhr.response);
  58469. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  58470. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  58471. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  58472. _this.manifestVersionFound = manifestFile.version;
  58473. }
  58474. if (_this.callbackManifestChecked) {
  58475. _this.callbackManifestChecked(true);
  58476. }
  58477. }
  58478. catch (ex) {
  58479. noManifestFile();
  58480. }
  58481. }
  58482. else {
  58483. noManifestFile();
  58484. }
  58485. }, false);
  58486. xhr.addEventListener("error", function (event) {
  58487. if (timeStampUsed) {
  58488. timeStampUsed = false;
  58489. // Let's retry without the timeStamp
  58490. // It could fail when coupled with HTML5 Offline API
  58491. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  58492. xhr.open("GET", retryManifestURL, true);
  58493. xhr.send();
  58494. }
  58495. else {
  58496. noManifestFile();
  58497. }
  58498. }, false);
  58499. try {
  58500. xhr.send();
  58501. }
  58502. catch (ex) {
  58503. BABYLON.Tools.Error("Error on XHR send request.");
  58504. this.callbackManifestChecked(false);
  58505. }
  58506. };
  58507. Database.prototype.openAsync = function (successCallback, errorCallback) {
  58508. var _this = this;
  58509. var handleError = function () {
  58510. _this.isSupported = false;
  58511. if (errorCallback)
  58512. errorCallback();
  58513. };
  58514. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  58515. // Your browser doesn't support IndexedDB
  58516. this.isSupported = false;
  58517. if (errorCallback)
  58518. errorCallback();
  58519. }
  58520. else {
  58521. // If the DB hasn't been opened or created yet
  58522. if (!this.db) {
  58523. this.hasReachedQuota = false;
  58524. this.isSupported = true;
  58525. var request = this.idbFactory.open("babylonjs", 1);
  58526. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  58527. request.onerror = function (event) {
  58528. handleError();
  58529. };
  58530. // executes when a version change transaction cannot complete due to other active transactions
  58531. request.onblocked = function (event) {
  58532. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  58533. handleError();
  58534. };
  58535. // DB has been opened successfully
  58536. request.onsuccess = function (event) {
  58537. _this.db = request.result;
  58538. successCallback();
  58539. };
  58540. // Initialization of the DB. Creating Scenes & Textures stores
  58541. request.onupgradeneeded = function (event) {
  58542. _this.db = (event.target).result;
  58543. if (_this.db) {
  58544. try {
  58545. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  58546. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  58547. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  58548. }
  58549. catch (ex) {
  58550. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  58551. handleError();
  58552. }
  58553. }
  58554. };
  58555. }
  58556. else {
  58557. if (successCallback)
  58558. successCallback();
  58559. }
  58560. }
  58561. };
  58562. Database.prototype.loadImageFromDB = function (url, image) {
  58563. var _this = this;
  58564. var completeURL = Database.ReturnFullUrlLocation(url);
  58565. var saveAndLoadImage = function () {
  58566. if (!_this.hasReachedQuota && _this.db !== null) {
  58567. // the texture is not yet in the DB, let's try to save it
  58568. _this._saveImageIntoDBAsync(completeURL, image);
  58569. }
  58570. else {
  58571. image.src = url;
  58572. }
  58573. };
  58574. if (!this.mustUpdateRessources) {
  58575. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  58576. }
  58577. else {
  58578. saveAndLoadImage();
  58579. }
  58580. };
  58581. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  58582. if (this.isSupported && this.db !== null) {
  58583. var texture;
  58584. var transaction = this.db.transaction(["textures"]);
  58585. transaction.onabort = function (event) {
  58586. image.src = url;
  58587. };
  58588. transaction.oncomplete = function (event) {
  58589. var blobTextureURL;
  58590. if (texture) {
  58591. var URL = window.URL || window.webkitURL;
  58592. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  58593. image.onerror = function () {
  58594. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  58595. image.src = url;
  58596. };
  58597. image.src = blobTextureURL;
  58598. }
  58599. else {
  58600. notInDBCallback();
  58601. }
  58602. };
  58603. var getRequest = transaction.objectStore("textures").get(url);
  58604. getRequest.onsuccess = function (event) {
  58605. texture = (event.target).result;
  58606. };
  58607. getRequest.onerror = function (event) {
  58608. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  58609. image.src = url;
  58610. };
  58611. }
  58612. else {
  58613. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58614. image.src = url;
  58615. }
  58616. };
  58617. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  58618. var _this = this;
  58619. if (this.isSupported) {
  58620. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  58621. var generateBlobUrl = function () {
  58622. var blobTextureURL;
  58623. if (blob) {
  58624. var URL = window.URL || window.webkitURL;
  58625. try {
  58626. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  58627. }
  58628. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  58629. catch (ex) {
  58630. blobTextureURL = URL.createObjectURL(blob);
  58631. }
  58632. }
  58633. if (blobTextureURL) {
  58634. image.src = blobTextureURL;
  58635. }
  58636. };
  58637. if (Database.IsUASupportingBlobStorage) {
  58638. var xhr = new XMLHttpRequest(), blob;
  58639. xhr.open("GET", url, true);
  58640. xhr.responseType = "blob";
  58641. xhr.addEventListener("load", function () {
  58642. if (xhr.status === 200 && _this.db) {
  58643. // Blob as response (XHR2)
  58644. blob = xhr.response;
  58645. var transaction = _this.db.transaction(["textures"], "readwrite");
  58646. // the transaction could abort because of a QuotaExceededError error
  58647. transaction.onabort = function (event) {
  58648. try {
  58649. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  58650. var srcElement = (event.srcElement || event.target);
  58651. var error = srcElement.error;
  58652. if (error && error.name === "QuotaExceededError") {
  58653. _this.hasReachedQuota = true;
  58654. }
  58655. }
  58656. catch (ex) { }
  58657. generateBlobUrl();
  58658. };
  58659. transaction.oncomplete = function (event) {
  58660. generateBlobUrl();
  58661. };
  58662. var newTexture = { textureUrl: url, data: blob };
  58663. try {
  58664. // Put the blob into the dabase
  58665. var addRequest = transaction.objectStore("textures").put(newTexture);
  58666. addRequest.onsuccess = function (event) {
  58667. };
  58668. addRequest.onerror = function (event) {
  58669. generateBlobUrl();
  58670. };
  58671. }
  58672. catch (ex) {
  58673. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  58674. if (ex.code === 25) {
  58675. Database.IsUASupportingBlobStorage = false;
  58676. }
  58677. image.src = url;
  58678. }
  58679. }
  58680. else {
  58681. image.src = url;
  58682. }
  58683. }, false);
  58684. xhr.addEventListener("error", function (event) {
  58685. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  58686. image.src = url;
  58687. }, false);
  58688. xhr.send();
  58689. }
  58690. else {
  58691. image.src = url;
  58692. }
  58693. }
  58694. else {
  58695. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58696. image.src = url;
  58697. }
  58698. };
  58699. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  58700. var _this = this;
  58701. var updateVersion = function () {
  58702. // the version is not yet in the DB or we need to update it
  58703. _this._saveVersionIntoDBAsync(url, versionLoaded);
  58704. };
  58705. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  58706. };
  58707. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  58708. var _this = this;
  58709. if (this.isSupported && this.db) {
  58710. var version;
  58711. try {
  58712. var transaction = this.db.transaction(["versions"]);
  58713. transaction.oncomplete = function (event) {
  58714. if (version) {
  58715. // If the version in the JSON file is > than the version in DB
  58716. if (_this.manifestVersionFound > version.data) {
  58717. _this.mustUpdateRessources = true;
  58718. updateInDBCallback();
  58719. }
  58720. else {
  58721. callback(version.data);
  58722. }
  58723. }
  58724. else {
  58725. _this.mustUpdateRessources = true;
  58726. updateInDBCallback();
  58727. }
  58728. };
  58729. transaction.onabort = function (event) {
  58730. callback(-1);
  58731. };
  58732. var getRequest = transaction.objectStore("versions").get(url);
  58733. getRequest.onsuccess = function (event) {
  58734. version = (event.target).result;
  58735. };
  58736. getRequest.onerror = function (event) {
  58737. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  58738. callback(-1);
  58739. };
  58740. }
  58741. catch (ex) {
  58742. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  58743. callback(-1);
  58744. }
  58745. }
  58746. else {
  58747. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58748. callback(-1);
  58749. }
  58750. };
  58751. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  58752. var _this = this;
  58753. if (this.isSupported && !this.hasReachedQuota && this.db) {
  58754. try {
  58755. // Open a transaction to the database
  58756. var transaction = this.db.transaction(["versions"], "readwrite");
  58757. // the transaction could abort because of a QuotaExceededError error
  58758. transaction.onabort = function (event) {
  58759. try {
  58760. var error = event.srcElement['error'];
  58761. if (error && error.name === "QuotaExceededError") {
  58762. _this.hasReachedQuota = true;
  58763. }
  58764. }
  58765. catch (ex) { }
  58766. callback(-1);
  58767. };
  58768. transaction.oncomplete = function (event) {
  58769. callback(_this.manifestVersionFound);
  58770. };
  58771. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  58772. // Put the scene into the database
  58773. var addRequest = transaction.objectStore("versions").put(newVersion);
  58774. addRequest.onsuccess = function (event) {
  58775. };
  58776. addRequest.onerror = function (event) {
  58777. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  58778. };
  58779. }
  58780. catch (ex) {
  58781. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  58782. callback(-1);
  58783. }
  58784. }
  58785. else {
  58786. callback(-1);
  58787. }
  58788. };
  58789. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  58790. var _this = this;
  58791. var completeUrl = Database.ReturnFullUrlLocation(url);
  58792. var saveAndLoadFile = function () {
  58793. // the scene is not yet in the DB, let's try to save it
  58794. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  58795. };
  58796. this._checkVersionFromDB(completeUrl, function (version) {
  58797. if (version !== -1) {
  58798. if (!_this.mustUpdateRessources) {
  58799. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  58800. }
  58801. else {
  58802. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  58803. }
  58804. }
  58805. else {
  58806. if (errorCallback) {
  58807. errorCallback();
  58808. }
  58809. }
  58810. });
  58811. };
  58812. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  58813. if (this.isSupported && this.db) {
  58814. var targetStore;
  58815. if (url.indexOf(".babylon") !== -1) {
  58816. targetStore = "scenes";
  58817. }
  58818. else {
  58819. targetStore = "textures";
  58820. }
  58821. var file;
  58822. var transaction = this.db.transaction([targetStore]);
  58823. transaction.oncomplete = function (event) {
  58824. if (file) {
  58825. callback(file.data);
  58826. }
  58827. else {
  58828. notInDBCallback();
  58829. }
  58830. };
  58831. transaction.onabort = function (event) {
  58832. notInDBCallback();
  58833. };
  58834. var getRequest = transaction.objectStore(targetStore).get(url);
  58835. getRequest.onsuccess = function (event) {
  58836. file = (event.target).result;
  58837. };
  58838. getRequest.onerror = function (event) {
  58839. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  58840. notInDBCallback();
  58841. };
  58842. }
  58843. else {
  58844. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58845. callback();
  58846. }
  58847. };
  58848. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  58849. var _this = this;
  58850. if (this.isSupported) {
  58851. var targetStore;
  58852. if (url.indexOf(".babylon") !== -1) {
  58853. targetStore = "scenes";
  58854. }
  58855. else {
  58856. targetStore = "textures";
  58857. }
  58858. // Create XHR
  58859. var xhr = new XMLHttpRequest();
  58860. var fileData;
  58861. xhr.open("GET", url, true);
  58862. if (useArrayBuffer) {
  58863. xhr.responseType = "arraybuffer";
  58864. }
  58865. if (progressCallback) {
  58866. xhr.onprogress = progressCallback;
  58867. }
  58868. xhr.addEventListener("load", function () {
  58869. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  58870. // Blob as response (XHR2)
  58871. //fileData = xhr.responseText;
  58872. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  58873. if (!_this.hasReachedQuota && _this.db) {
  58874. // Open a transaction to the database
  58875. var transaction = _this.db.transaction([targetStore], "readwrite");
  58876. // the transaction could abort because of a QuotaExceededError error
  58877. transaction.onabort = function (event) {
  58878. try {
  58879. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  58880. var error = event.srcElement['error'];
  58881. if (error && error.name === "QuotaExceededError") {
  58882. _this.hasReachedQuota = true;
  58883. }
  58884. }
  58885. catch (ex) { }
  58886. callback(fileData);
  58887. };
  58888. transaction.oncomplete = function (event) {
  58889. callback(fileData);
  58890. };
  58891. var newFile;
  58892. if (targetStore === "scenes") {
  58893. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  58894. }
  58895. else {
  58896. newFile = { textureUrl: url, data: fileData };
  58897. }
  58898. try {
  58899. // Put the scene into the database
  58900. var addRequest = transaction.objectStore(targetStore).put(newFile);
  58901. addRequest.onsuccess = function (event) {
  58902. };
  58903. addRequest.onerror = function (event) {
  58904. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  58905. };
  58906. }
  58907. catch (ex) {
  58908. callback(fileData);
  58909. }
  58910. }
  58911. else {
  58912. callback(fileData);
  58913. }
  58914. }
  58915. else {
  58916. callback();
  58917. }
  58918. }, false);
  58919. xhr.addEventListener("error", function (event) {
  58920. BABYLON.Tools.Error("error on XHR request.");
  58921. callback();
  58922. }, false);
  58923. xhr.send();
  58924. }
  58925. else {
  58926. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58927. callback();
  58928. }
  58929. };
  58930. Database.IsUASupportingBlobStorage = true;
  58931. Database.IDBStorageEnabled = true;
  58932. Database.parseURL = function (url) {
  58933. var a = document.createElement('a');
  58934. a.href = url;
  58935. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  58936. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  58937. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  58938. return absLocation;
  58939. };
  58940. Database.ReturnFullUrlLocation = function (url) {
  58941. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  58942. return (Database.parseURL(window.location.href) + url);
  58943. }
  58944. else {
  58945. return url;
  58946. }
  58947. };
  58948. return Database;
  58949. }());
  58950. BABYLON.Database = Database;
  58951. })(BABYLON || (BABYLON = {}));
  58952. //# sourceMappingURL=babylon.database.js.map
  58953. var BABYLON;
  58954. (function (BABYLON) {
  58955. var FresnelParameters = /** @class */ (function () {
  58956. function FresnelParameters() {
  58957. this._isEnabled = true;
  58958. this.leftColor = BABYLON.Color3.White();
  58959. this.rightColor = BABYLON.Color3.Black();
  58960. this.bias = 0;
  58961. this.power = 1;
  58962. }
  58963. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  58964. get: function () {
  58965. return this._isEnabled;
  58966. },
  58967. set: function (value) {
  58968. if (this._isEnabled === value) {
  58969. return;
  58970. }
  58971. this._isEnabled = value;
  58972. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  58973. },
  58974. enumerable: true,
  58975. configurable: true
  58976. });
  58977. FresnelParameters.prototype.clone = function () {
  58978. var newFresnelParameters = new FresnelParameters();
  58979. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  58980. return newFresnelParameters;
  58981. };
  58982. FresnelParameters.prototype.serialize = function () {
  58983. var serializationObject = {};
  58984. serializationObject.isEnabled = this.isEnabled;
  58985. serializationObject.leftColor = this.leftColor;
  58986. serializationObject.rightColor = this.rightColor;
  58987. serializationObject.bias = this.bias;
  58988. serializationObject.power = this.power;
  58989. return serializationObject;
  58990. };
  58991. FresnelParameters.Parse = function (parsedFresnelParameters) {
  58992. var fresnelParameters = new FresnelParameters();
  58993. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  58994. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  58995. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  58996. fresnelParameters.bias = parsedFresnelParameters.bias;
  58997. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  58998. return fresnelParameters;
  58999. };
  59000. return FresnelParameters;
  59001. }());
  59002. BABYLON.FresnelParameters = FresnelParameters;
  59003. })(BABYLON || (BABYLON = {}));
  59004. //# sourceMappingURL=babylon.fresnelParameters.js.map
  59005. var BABYLON;
  59006. (function (BABYLON) {
  59007. var MultiMaterial = /** @class */ (function (_super) {
  59008. __extends(MultiMaterial, _super);
  59009. function MultiMaterial(name, scene) {
  59010. var _this = _super.call(this, name, scene, true) || this;
  59011. scene.multiMaterials.push(_this);
  59012. _this.subMaterials = new Array();
  59013. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  59014. return _this;
  59015. }
  59016. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  59017. get: function () {
  59018. return this._subMaterials;
  59019. },
  59020. set: function (value) {
  59021. this._subMaterials = value;
  59022. this._hookArray(value);
  59023. },
  59024. enumerable: true,
  59025. configurable: true
  59026. });
  59027. MultiMaterial.prototype._hookArray = function (array) {
  59028. var _this = this;
  59029. var oldPush = array.push;
  59030. array.push = function () {
  59031. var items = [];
  59032. for (var _i = 0; _i < arguments.length; _i++) {
  59033. items[_i] = arguments[_i];
  59034. }
  59035. var result = oldPush.apply(array, items);
  59036. _this._markAllSubMeshesAsTexturesDirty();
  59037. return result;
  59038. };
  59039. var oldSplice = array.splice;
  59040. array.splice = function (index, deleteCount) {
  59041. var deleted = oldSplice.apply(array, [index, deleteCount]);
  59042. _this._markAllSubMeshesAsTexturesDirty();
  59043. return deleted;
  59044. };
  59045. };
  59046. // Properties
  59047. MultiMaterial.prototype.getSubMaterial = function (index) {
  59048. if (index < 0 || index >= this.subMaterials.length) {
  59049. return this.getScene().defaultMaterial;
  59050. }
  59051. return this.subMaterials[index];
  59052. };
  59053. MultiMaterial.prototype.getActiveTextures = function () {
  59054. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  59055. if (subMaterial) {
  59056. return subMaterial.getActiveTextures();
  59057. }
  59058. else {
  59059. return [];
  59060. }
  59061. }));
  59062. var _a;
  59063. };
  59064. // Methods
  59065. MultiMaterial.prototype.getClassName = function () {
  59066. return "MultiMaterial";
  59067. };
  59068. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  59069. for (var index = 0; index < this.subMaterials.length; index++) {
  59070. var subMaterial = this.subMaterials[index];
  59071. if (subMaterial) {
  59072. if (subMaterial.storeEffectOnSubMeshes) {
  59073. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  59074. return false;
  59075. }
  59076. continue;
  59077. }
  59078. if (!subMaterial.isReady(mesh)) {
  59079. return false;
  59080. }
  59081. }
  59082. }
  59083. return true;
  59084. };
  59085. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  59086. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  59087. for (var index = 0; index < this.subMaterials.length; index++) {
  59088. var subMaterial = null;
  59089. var current = this.subMaterials[index];
  59090. if (cloneChildren && current) {
  59091. subMaterial = current.clone(name + "-" + current.name);
  59092. }
  59093. else {
  59094. subMaterial = this.subMaterials[index];
  59095. }
  59096. newMultiMaterial.subMaterials.push(subMaterial);
  59097. }
  59098. return newMultiMaterial;
  59099. };
  59100. MultiMaterial.prototype.serialize = function () {
  59101. var serializationObject = {};
  59102. serializationObject.name = this.name;
  59103. serializationObject.id = this.id;
  59104. if (BABYLON.Tags) {
  59105. serializationObject.tags = BABYLON.Tags.GetTags(this);
  59106. }
  59107. serializationObject.materials = [];
  59108. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  59109. var subMat = this.subMaterials[matIndex];
  59110. if (subMat) {
  59111. serializationObject.materials.push(subMat.id);
  59112. }
  59113. else {
  59114. serializationObject.materials.push(null);
  59115. }
  59116. }
  59117. return serializationObject;
  59118. };
  59119. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59120. var scene = this.getScene();
  59121. if (!scene) {
  59122. return;
  59123. }
  59124. var index = scene.multiMaterials.indexOf(this);
  59125. if (index >= 0) {
  59126. scene.multiMaterials.splice(index, 1);
  59127. }
  59128. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59129. };
  59130. return MultiMaterial;
  59131. }(BABYLON.Material));
  59132. BABYLON.MultiMaterial = MultiMaterial;
  59133. })(BABYLON || (BABYLON = {}));
  59134. //# sourceMappingURL=babylon.multiMaterial.js.map
  59135. var BABYLON;
  59136. (function (BABYLON) {
  59137. var FreeCameraTouchInput = /** @class */ (function () {
  59138. function FreeCameraTouchInput() {
  59139. this._offsetX = null;
  59140. this._offsetY = null;
  59141. this._pointerPressed = new Array();
  59142. this.touchAngularSensibility = 200000.0;
  59143. this.touchMoveSensibility = 250.0;
  59144. }
  59145. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  59146. var _this = this;
  59147. var previousPosition = null;
  59148. if (this._pointerInput === undefined) {
  59149. this._onLostFocus = function (evt) {
  59150. _this._offsetX = null;
  59151. _this._offsetY = null;
  59152. };
  59153. this._pointerInput = function (p, s) {
  59154. var evt = p.event;
  59155. if (evt.pointerType === "mouse") {
  59156. return;
  59157. }
  59158. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  59159. if (!noPreventDefault) {
  59160. evt.preventDefault();
  59161. }
  59162. _this._pointerPressed.push(evt.pointerId);
  59163. if (_this._pointerPressed.length !== 1) {
  59164. return;
  59165. }
  59166. previousPosition = {
  59167. x: evt.clientX,
  59168. y: evt.clientY
  59169. };
  59170. }
  59171. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  59172. if (!noPreventDefault) {
  59173. evt.preventDefault();
  59174. }
  59175. var index = _this._pointerPressed.indexOf(evt.pointerId);
  59176. if (index === -1) {
  59177. return;
  59178. }
  59179. _this._pointerPressed.splice(index, 1);
  59180. if (index != 0) {
  59181. return;
  59182. }
  59183. previousPosition = null;
  59184. _this._offsetX = null;
  59185. _this._offsetY = null;
  59186. }
  59187. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  59188. if (!noPreventDefault) {
  59189. evt.preventDefault();
  59190. }
  59191. if (!previousPosition) {
  59192. return;
  59193. }
  59194. var index = _this._pointerPressed.indexOf(evt.pointerId);
  59195. if (index != 0) {
  59196. return;
  59197. }
  59198. _this._offsetX = evt.clientX - previousPosition.x;
  59199. _this._offsetY = -(evt.clientY - previousPosition.y);
  59200. }
  59201. };
  59202. }
  59203. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  59204. if (this._onLostFocus) {
  59205. element.addEventListener("blur", this._onLostFocus);
  59206. }
  59207. };
  59208. FreeCameraTouchInput.prototype.detachControl = function (element) {
  59209. if (this._pointerInput && element) {
  59210. if (this._observer) {
  59211. this.camera.getScene().onPointerObservable.remove(this._observer);
  59212. this._observer = null;
  59213. }
  59214. if (this._onLostFocus) {
  59215. element.removeEventListener("blur", this._onLostFocus);
  59216. this._onLostFocus = null;
  59217. }
  59218. this._pointerPressed = [];
  59219. this._offsetX = null;
  59220. this._offsetY = null;
  59221. }
  59222. };
  59223. FreeCameraTouchInput.prototype.checkInputs = function () {
  59224. if (this._offsetX && this._offsetY) {
  59225. var camera = this.camera;
  59226. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  59227. if (this._pointerPressed.length > 1) {
  59228. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  59229. }
  59230. else {
  59231. var speed = camera._computeLocalCameraSpeed();
  59232. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  59233. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  59234. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  59235. }
  59236. }
  59237. };
  59238. FreeCameraTouchInput.prototype.getClassName = function () {
  59239. return "FreeCameraTouchInput";
  59240. };
  59241. FreeCameraTouchInput.prototype.getSimpleName = function () {
  59242. return "touch";
  59243. };
  59244. __decorate([
  59245. BABYLON.serialize()
  59246. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  59247. __decorate([
  59248. BABYLON.serialize()
  59249. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  59250. return FreeCameraTouchInput;
  59251. }());
  59252. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  59253. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  59254. })(BABYLON || (BABYLON = {}));
  59255. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  59256. var BABYLON;
  59257. (function (BABYLON) {
  59258. // We're mainly based on the logic defined into the FreeCamera code
  59259. var TouchCamera = /** @class */ (function (_super) {
  59260. __extends(TouchCamera, _super);
  59261. //-- end properties for backward compatibility for inputs
  59262. function TouchCamera(name, position, scene) {
  59263. var _this = _super.call(this, name, position, scene) || this;
  59264. _this.inputs.addTouch();
  59265. _this._setupInputs();
  59266. return _this;
  59267. }
  59268. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  59269. //-- Begin properties for backward compatibility for inputs
  59270. get: function () {
  59271. var touch = this.inputs.attached["touch"];
  59272. if (touch)
  59273. return touch.touchAngularSensibility;
  59274. return 0;
  59275. },
  59276. set: function (value) {
  59277. var touch = this.inputs.attached["touch"];
  59278. if (touch)
  59279. touch.touchAngularSensibility = value;
  59280. },
  59281. enumerable: true,
  59282. configurable: true
  59283. });
  59284. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  59285. get: function () {
  59286. var touch = this.inputs.attached["touch"];
  59287. if (touch)
  59288. return touch.touchMoveSensibility;
  59289. return 0;
  59290. },
  59291. set: function (value) {
  59292. var touch = this.inputs.attached["touch"];
  59293. if (touch)
  59294. touch.touchMoveSensibility = value;
  59295. },
  59296. enumerable: true,
  59297. configurable: true
  59298. });
  59299. TouchCamera.prototype.getClassName = function () {
  59300. return "TouchCamera";
  59301. };
  59302. TouchCamera.prototype._setupInputs = function () {
  59303. var mouse = this.inputs.attached["mouse"];
  59304. if (mouse) {
  59305. mouse.touchEnabled = false;
  59306. }
  59307. };
  59308. return TouchCamera;
  59309. }(BABYLON.FreeCamera));
  59310. BABYLON.TouchCamera = TouchCamera;
  59311. })(BABYLON || (BABYLON = {}));
  59312. //# sourceMappingURL=babylon.touchCamera.js.map
  59313. var BABYLON;
  59314. (function (BABYLON) {
  59315. var ProceduralTexture = /** @class */ (function (_super) {
  59316. __extends(ProceduralTexture, _super);
  59317. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  59318. if (fallbackTexture === void 0) { fallbackTexture = null; }
  59319. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59320. if (isCube === void 0) { isCube = false; }
  59321. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59322. _this.isCube = isCube;
  59323. _this.isEnabled = true;
  59324. _this._currentRefreshId = -1;
  59325. _this._refreshRate = 1;
  59326. _this._vertexBuffers = {};
  59327. _this._uniforms = new Array();
  59328. _this._samplers = new Array();
  59329. _this._textures = {};
  59330. _this._floats = {};
  59331. _this._floatsArrays = {};
  59332. _this._colors3 = {};
  59333. _this._colors4 = {};
  59334. _this._vectors2 = {};
  59335. _this._vectors3 = {};
  59336. _this._matrices = {};
  59337. _this._fallbackTextureUsed = false;
  59338. scene._proceduralTextures.push(_this);
  59339. _this._engine = scene.getEngine();
  59340. _this.name = name;
  59341. _this.isRenderTarget = true;
  59342. _this._size = size;
  59343. _this._generateMipMaps = generateMipMaps;
  59344. _this.setFragment(fragment);
  59345. _this._fallbackTexture = fallbackTexture;
  59346. if (isCube) {
  59347. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  59348. _this.setFloat("face", 0);
  59349. }
  59350. else {
  59351. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  59352. }
  59353. // VBO
  59354. var vertices = [];
  59355. vertices.push(1, 1);
  59356. vertices.push(-1, 1);
  59357. vertices.push(-1, -1);
  59358. vertices.push(1, -1);
  59359. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  59360. _this._createIndexBuffer();
  59361. return _this;
  59362. }
  59363. ProceduralTexture.prototype._createIndexBuffer = function () {
  59364. var engine = this._engine;
  59365. // Indices
  59366. var indices = [];
  59367. indices.push(0);
  59368. indices.push(1);
  59369. indices.push(2);
  59370. indices.push(0);
  59371. indices.push(2);
  59372. indices.push(3);
  59373. this._indexBuffer = engine.createIndexBuffer(indices);
  59374. };
  59375. ProceduralTexture.prototype._rebuild = function () {
  59376. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59377. if (vb) {
  59378. vb._rebuild();
  59379. }
  59380. this._createIndexBuffer();
  59381. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59382. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59383. }
  59384. };
  59385. ProceduralTexture.prototype.reset = function () {
  59386. if (this._effect === undefined) {
  59387. return;
  59388. }
  59389. var engine = this._engine;
  59390. engine._releaseEffect(this._effect);
  59391. };
  59392. ProceduralTexture.prototype.isReady = function () {
  59393. var _this = this;
  59394. var engine = this._engine;
  59395. var shaders;
  59396. if (!this._fragment) {
  59397. return false;
  59398. }
  59399. if (this._fallbackTextureUsed) {
  59400. return true;
  59401. }
  59402. if (this._fragment.fragmentElement !== undefined) {
  59403. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  59404. }
  59405. else {
  59406. shaders = { vertex: "procedural", fragment: this._fragment };
  59407. }
  59408. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  59409. _this.releaseInternalTexture();
  59410. if (_this._fallbackTexture) {
  59411. _this._texture = _this._fallbackTexture._texture;
  59412. if (_this._texture) {
  59413. _this._texture.incrementReferences();
  59414. }
  59415. }
  59416. _this._fallbackTextureUsed = true;
  59417. });
  59418. return this._effect.isReady();
  59419. };
  59420. ProceduralTexture.prototype.resetRefreshCounter = function () {
  59421. this._currentRefreshId = -1;
  59422. };
  59423. ProceduralTexture.prototype.setFragment = function (fragment) {
  59424. this._fragment = fragment;
  59425. };
  59426. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  59427. get: function () {
  59428. return this._refreshRate;
  59429. },
  59430. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59431. set: function (value) {
  59432. this._refreshRate = value;
  59433. this.resetRefreshCounter();
  59434. },
  59435. enumerable: true,
  59436. configurable: true
  59437. });
  59438. ProceduralTexture.prototype._shouldRender = function () {
  59439. if (!this.isEnabled || !this.isReady() || !this._texture) {
  59440. return false;
  59441. }
  59442. if (this._fallbackTextureUsed) {
  59443. return false;
  59444. }
  59445. if (this._currentRefreshId === -1) {
  59446. this._currentRefreshId = 1;
  59447. return true;
  59448. }
  59449. if (this.refreshRate === this._currentRefreshId) {
  59450. this._currentRefreshId = 1;
  59451. return true;
  59452. }
  59453. this._currentRefreshId++;
  59454. return false;
  59455. };
  59456. ProceduralTexture.prototype.getRenderSize = function () {
  59457. return this._size;
  59458. };
  59459. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  59460. if (this._fallbackTextureUsed) {
  59461. return;
  59462. }
  59463. this.releaseInternalTexture();
  59464. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  59465. };
  59466. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  59467. if (this._uniforms.indexOf(uniformName) === -1) {
  59468. this._uniforms.push(uniformName);
  59469. }
  59470. };
  59471. ProceduralTexture.prototype.setTexture = function (name, texture) {
  59472. if (this._samplers.indexOf(name) === -1) {
  59473. this._samplers.push(name);
  59474. }
  59475. this._textures[name] = texture;
  59476. return this;
  59477. };
  59478. ProceduralTexture.prototype.setFloat = function (name, value) {
  59479. this._checkUniform(name);
  59480. this._floats[name] = value;
  59481. return this;
  59482. };
  59483. ProceduralTexture.prototype.setFloats = function (name, value) {
  59484. this._checkUniform(name);
  59485. this._floatsArrays[name] = value;
  59486. return this;
  59487. };
  59488. ProceduralTexture.prototype.setColor3 = function (name, value) {
  59489. this._checkUniform(name);
  59490. this._colors3[name] = value;
  59491. return this;
  59492. };
  59493. ProceduralTexture.prototype.setColor4 = function (name, value) {
  59494. this._checkUniform(name);
  59495. this._colors4[name] = value;
  59496. return this;
  59497. };
  59498. ProceduralTexture.prototype.setVector2 = function (name, value) {
  59499. this._checkUniform(name);
  59500. this._vectors2[name] = value;
  59501. return this;
  59502. };
  59503. ProceduralTexture.prototype.setVector3 = function (name, value) {
  59504. this._checkUniform(name);
  59505. this._vectors3[name] = value;
  59506. return this;
  59507. };
  59508. ProceduralTexture.prototype.setMatrix = function (name, value) {
  59509. this._checkUniform(name);
  59510. this._matrices[name] = value;
  59511. return this;
  59512. };
  59513. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  59514. var scene = this.getScene();
  59515. if (!scene) {
  59516. return;
  59517. }
  59518. var engine = this._engine;
  59519. // Render
  59520. engine.enableEffect(this._effect);
  59521. engine.setState(false);
  59522. // Texture
  59523. for (var name in this._textures) {
  59524. this._effect.setTexture(name, this._textures[name]);
  59525. }
  59526. // Float
  59527. for (name in this._floats) {
  59528. this._effect.setFloat(name, this._floats[name]);
  59529. }
  59530. // Floats
  59531. for (name in this._floatsArrays) {
  59532. this._effect.setArray(name, this._floatsArrays[name]);
  59533. }
  59534. // Color3
  59535. for (name in this._colors3) {
  59536. this._effect.setColor3(name, this._colors3[name]);
  59537. }
  59538. // Color4
  59539. for (name in this._colors4) {
  59540. var color = this._colors4[name];
  59541. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59542. }
  59543. // Vector2
  59544. for (name in this._vectors2) {
  59545. this._effect.setVector2(name, this._vectors2[name]);
  59546. }
  59547. // Vector3
  59548. for (name in this._vectors3) {
  59549. this._effect.setVector3(name, this._vectors3[name]);
  59550. }
  59551. // Matrix
  59552. for (name in this._matrices) {
  59553. this._effect.setMatrix(name, this._matrices[name]);
  59554. }
  59555. if (!this._texture) {
  59556. return;
  59557. }
  59558. if (this.isCube) {
  59559. for (var face = 0; face < 6; face++) {
  59560. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  59561. // VBOs
  59562. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  59563. this._effect.setFloat("face", face);
  59564. // Clear
  59565. engine.clear(scene.clearColor, true, true, true);
  59566. // Draw order
  59567. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  59568. // Mipmaps
  59569. if (face === 5) {
  59570. engine.generateMipMapsForCubemap(this._texture);
  59571. }
  59572. }
  59573. }
  59574. else {
  59575. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  59576. // VBOs
  59577. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  59578. // Clear
  59579. engine.clear(scene.clearColor, true, true, true);
  59580. // Draw order
  59581. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  59582. }
  59583. // Unbind
  59584. engine.unBindFramebuffer(this._texture, this.isCube);
  59585. if (this.onGenerated) {
  59586. this.onGenerated();
  59587. }
  59588. };
  59589. ProceduralTexture.prototype.clone = function () {
  59590. var textureSize = this.getSize();
  59591. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  59592. // Base texture
  59593. newTexture.hasAlpha = this.hasAlpha;
  59594. newTexture.level = this.level;
  59595. // RenderTarget Texture
  59596. newTexture.coordinatesMode = this.coordinatesMode;
  59597. return newTexture;
  59598. };
  59599. ProceduralTexture.prototype.dispose = function () {
  59600. var scene = this.getScene();
  59601. if (!scene) {
  59602. return;
  59603. }
  59604. var index = scene._proceduralTextures.indexOf(this);
  59605. if (index >= 0) {
  59606. scene._proceduralTextures.splice(index, 1);
  59607. }
  59608. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59609. if (vertexBuffer) {
  59610. vertexBuffer.dispose();
  59611. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59612. }
  59613. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  59614. this._indexBuffer = null;
  59615. }
  59616. _super.prototype.dispose.call(this);
  59617. };
  59618. return ProceduralTexture;
  59619. }(BABYLON.Texture));
  59620. BABYLON.ProceduralTexture = ProceduralTexture;
  59621. })(BABYLON || (BABYLON = {}));
  59622. //# sourceMappingURL=babylon.proceduralTexture.js.map
  59623. var BABYLON;
  59624. (function (BABYLON) {
  59625. var CustomProceduralTexture = /** @class */ (function (_super) {
  59626. __extends(CustomProceduralTexture, _super);
  59627. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  59628. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  59629. _this._animate = true;
  59630. _this._time = 0;
  59631. _this._texturePath = texturePath;
  59632. //Try to load json
  59633. _this.loadJson(texturePath);
  59634. _this.refreshRate = 1;
  59635. return _this;
  59636. }
  59637. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  59638. var _this = this;
  59639. var noConfigFile = function () {
  59640. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  59641. try {
  59642. _this.setFragment(_this._texturePath);
  59643. }
  59644. catch (ex) {
  59645. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  59646. }
  59647. };
  59648. var configFileUrl = jsonUrl + "/config.json";
  59649. var xhr = new XMLHttpRequest();
  59650. xhr.open("GET", configFileUrl, true);
  59651. xhr.addEventListener("load", function () {
  59652. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  59653. try {
  59654. _this._config = JSON.parse(xhr.response);
  59655. _this.updateShaderUniforms();
  59656. _this.updateTextures();
  59657. _this.setFragment(_this._texturePath + "/custom");
  59658. _this._animate = _this._config.animate;
  59659. _this.refreshRate = _this._config.refreshrate;
  59660. }
  59661. catch (ex) {
  59662. noConfigFile();
  59663. }
  59664. }
  59665. else {
  59666. noConfigFile();
  59667. }
  59668. }, false);
  59669. xhr.addEventListener("error", function () {
  59670. noConfigFile();
  59671. }, false);
  59672. try {
  59673. xhr.send();
  59674. }
  59675. catch (ex) {
  59676. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  59677. }
  59678. };
  59679. CustomProceduralTexture.prototype.isReady = function () {
  59680. if (!_super.prototype.isReady.call(this)) {
  59681. return false;
  59682. }
  59683. for (var name in this._textures) {
  59684. var texture = this._textures[name];
  59685. if (!texture.isReady()) {
  59686. return false;
  59687. }
  59688. }
  59689. return true;
  59690. };
  59691. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  59692. var scene = this.getScene();
  59693. if (this._animate && scene) {
  59694. this._time += scene.getAnimationRatio() * 0.03;
  59695. this.updateShaderUniforms();
  59696. }
  59697. _super.prototype.render.call(this, useCameraPostProcess);
  59698. };
  59699. CustomProceduralTexture.prototype.updateTextures = function () {
  59700. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  59701. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  59702. }
  59703. };
  59704. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  59705. if (this._config) {
  59706. for (var j = 0; j < this._config.uniforms.length; j++) {
  59707. var uniform = this._config.uniforms[j];
  59708. switch (uniform.type) {
  59709. case "float":
  59710. this.setFloat(uniform.name, uniform.value);
  59711. break;
  59712. case "color3":
  59713. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  59714. break;
  59715. case "color4":
  59716. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  59717. break;
  59718. case "vector2":
  59719. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  59720. break;
  59721. case "vector3":
  59722. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  59723. break;
  59724. }
  59725. }
  59726. }
  59727. this.setFloat("time", this._time);
  59728. };
  59729. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  59730. get: function () {
  59731. return this._animate;
  59732. },
  59733. set: function (value) {
  59734. this._animate = value;
  59735. },
  59736. enumerable: true,
  59737. configurable: true
  59738. });
  59739. return CustomProceduralTexture;
  59740. }(BABYLON.ProceduralTexture));
  59741. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  59742. })(BABYLON || (BABYLON = {}));
  59743. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  59744. var BABYLON;
  59745. (function (BABYLON) {
  59746. var FreeCameraGamepadInput = /** @class */ (function () {
  59747. function FreeCameraGamepadInput() {
  59748. this.gamepadAngularSensibility = 200;
  59749. this.gamepadMoveSensibility = 40;
  59750. // private members
  59751. this._cameraTransform = BABYLON.Matrix.Identity();
  59752. this._deltaTransform = BABYLON.Vector3.Zero();
  59753. this._vector3 = BABYLON.Vector3.Zero();
  59754. this._vector2 = BABYLON.Vector2.Zero();
  59755. }
  59756. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  59757. var _this = this;
  59758. var manager = this.camera.getScene().gamepadManager;
  59759. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  59760. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  59761. // prioritize XBOX gamepads.
  59762. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59763. _this.gamepad = gamepad;
  59764. }
  59765. }
  59766. });
  59767. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59768. if (_this.gamepad === gamepad) {
  59769. _this.gamepad = null;
  59770. }
  59771. });
  59772. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59773. };
  59774. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  59775. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59776. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59777. this.gamepad = null;
  59778. };
  59779. FreeCameraGamepadInput.prototype.checkInputs = function () {
  59780. if (this.gamepad && this.gamepad.leftStick) {
  59781. var camera = this.camera;
  59782. var LSValues = this.gamepad.leftStick;
  59783. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  59784. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59785. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  59786. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  59787. var RSValues = this.gamepad.rightStick;
  59788. if (RSValues) {
  59789. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  59790. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  59791. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  59792. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  59793. }
  59794. else {
  59795. RSValues = { x: 0, y: 0 };
  59796. }
  59797. if (!camera.rotationQuaternion) {
  59798. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  59799. }
  59800. else {
  59801. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  59802. }
  59803. var speed = camera._computeLocalCameraSpeed() * 50.0;
  59804. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  59805. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  59806. camera.cameraDirection.addInPlace(this._deltaTransform);
  59807. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  59808. camera.cameraRotation.addInPlace(this._vector2);
  59809. }
  59810. };
  59811. FreeCameraGamepadInput.prototype.getClassName = function () {
  59812. return "FreeCameraGamepadInput";
  59813. };
  59814. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  59815. return "gamepad";
  59816. };
  59817. __decorate([
  59818. BABYLON.serialize()
  59819. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  59820. __decorate([
  59821. BABYLON.serialize()
  59822. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59823. return FreeCameraGamepadInput;
  59824. }());
  59825. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  59826. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  59827. })(BABYLON || (BABYLON = {}));
  59828. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  59829. var BABYLON;
  59830. (function (BABYLON) {
  59831. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  59832. function ArcRotateCameraGamepadInput() {
  59833. this.gamepadRotationSensibility = 80;
  59834. this.gamepadMoveSensibility = 40;
  59835. }
  59836. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  59837. var _this = this;
  59838. var manager = this.camera.getScene().gamepadManager;
  59839. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  59840. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  59841. // prioritize XBOX gamepads.
  59842. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59843. _this.gamepad = gamepad;
  59844. }
  59845. }
  59846. });
  59847. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59848. if (_this.gamepad === gamepad) {
  59849. _this.gamepad = null;
  59850. }
  59851. });
  59852. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59853. };
  59854. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  59855. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59856. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59857. this.gamepad = null;
  59858. };
  59859. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  59860. if (this.gamepad) {
  59861. var camera = this.camera;
  59862. var RSValues = this.gamepad.rightStick;
  59863. if (RSValues) {
  59864. if (RSValues.x != 0) {
  59865. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  59866. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  59867. camera.inertialAlphaOffset += normalizedRX;
  59868. }
  59869. }
  59870. if (RSValues.y != 0) {
  59871. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  59872. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  59873. camera.inertialBetaOffset += normalizedRY;
  59874. }
  59875. }
  59876. }
  59877. var LSValues = this.gamepad.leftStick;
  59878. if (LSValues && LSValues.y != 0) {
  59879. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59880. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  59881. this.camera.inertialRadiusOffset -= normalizedLY;
  59882. }
  59883. }
  59884. }
  59885. };
  59886. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  59887. return "ArcRotateCameraGamepadInput";
  59888. };
  59889. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  59890. return "gamepad";
  59891. };
  59892. __decorate([
  59893. BABYLON.serialize()
  59894. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  59895. __decorate([
  59896. BABYLON.serialize()
  59897. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59898. return ArcRotateCameraGamepadInput;
  59899. }());
  59900. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  59901. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  59902. })(BABYLON || (BABYLON = {}));
  59903. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  59904. var BABYLON;
  59905. (function (BABYLON) {
  59906. var GamepadManager = /** @class */ (function () {
  59907. function GamepadManager(_scene) {
  59908. var _this = this;
  59909. this._scene = _scene;
  59910. this._babylonGamepads = [];
  59911. this._oneGamepadConnected = false;
  59912. this._isMonitoring = false;
  59913. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  59914. if (!BABYLON.Tools.IsWindowObjectExist()) {
  59915. this._gamepadEventSupported = false;
  59916. }
  59917. else {
  59918. this._gamepadEventSupported = 'GamepadEvent' in window;
  59919. this._gamepadSupport = (navigator.getGamepads ||
  59920. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  59921. }
  59922. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  59923. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  59924. for (var i in _this._babylonGamepads) {
  59925. var gamepad = _this._babylonGamepads[i];
  59926. if (gamepad && gamepad._isConnected) {
  59927. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  59928. }
  59929. }
  59930. });
  59931. this._onGamepadConnectedEvent = function (evt) {
  59932. var gamepad = evt.gamepad;
  59933. if (gamepad.index in _this._babylonGamepads) {
  59934. if (_this._babylonGamepads[gamepad.index].isConnected) {
  59935. return;
  59936. }
  59937. }
  59938. var newGamepad;
  59939. if (_this._babylonGamepads[gamepad.index]) {
  59940. newGamepad = _this._babylonGamepads[gamepad.index];
  59941. newGamepad.browserGamepad = gamepad;
  59942. newGamepad._isConnected = true;
  59943. }
  59944. else {
  59945. newGamepad = _this._addNewGamepad(gamepad);
  59946. }
  59947. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59948. _this._startMonitoringGamepads();
  59949. };
  59950. this._onGamepadDisconnectedEvent = function (evt) {
  59951. var gamepad = evt.gamepad;
  59952. // Remove the gamepad from the list of gamepads to monitor.
  59953. for (var i in _this._babylonGamepads) {
  59954. if (_this._babylonGamepads[i].index === gamepad.index) {
  59955. var disconnectedGamepad = _this._babylonGamepads[i];
  59956. disconnectedGamepad._isConnected = false;
  59957. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  59958. break;
  59959. }
  59960. }
  59961. };
  59962. if (this._gamepadSupport) {
  59963. //first add already-connected gamepads
  59964. this._updateGamepadObjects();
  59965. if (this._babylonGamepads.length) {
  59966. this._startMonitoringGamepads();
  59967. }
  59968. // Checking if the gamepad connected event is supported (like in Firefox)
  59969. if (this._gamepadEventSupported) {
  59970. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  59971. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  59972. }
  59973. else {
  59974. this._startMonitoringGamepads();
  59975. }
  59976. }
  59977. }
  59978. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  59979. get: function () {
  59980. return this._babylonGamepads;
  59981. },
  59982. enumerable: true,
  59983. configurable: true
  59984. });
  59985. GamepadManager.prototype.getGamepadByType = function (type) {
  59986. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  59987. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  59988. var gamepad = _a[_i];
  59989. if (gamepad && gamepad.type === type) {
  59990. return gamepad;
  59991. }
  59992. }
  59993. return null;
  59994. };
  59995. GamepadManager.prototype.dispose = function () {
  59996. if (this._gamepadEventSupported) {
  59997. if (this._onGamepadConnectedEvent) {
  59998. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  59999. }
  60000. if (this._onGamepadDisconnectedEvent) {
  60001. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  60002. }
  60003. this._onGamepadConnectedEvent = null;
  60004. this._onGamepadDisconnectedEvent = null;
  60005. }
  60006. this._babylonGamepads.forEach(function (gamepad) {
  60007. gamepad.dispose();
  60008. });
  60009. this.onGamepadConnectedObservable.clear();
  60010. this.onGamepadDisconnectedObservable.clear();
  60011. this._oneGamepadConnected = false;
  60012. this._stopMonitoringGamepads();
  60013. this._babylonGamepads = [];
  60014. };
  60015. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  60016. if (!this._oneGamepadConnected) {
  60017. this._oneGamepadConnected = true;
  60018. }
  60019. var newGamepad;
  60020. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  60021. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  60022. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  60023. }
  60024. else if (gamepad.pose) {
  60025. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  60026. }
  60027. else {
  60028. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  60029. }
  60030. this._babylonGamepads[newGamepad.index] = newGamepad;
  60031. return newGamepad;
  60032. };
  60033. GamepadManager.prototype._startMonitoringGamepads = function () {
  60034. if (!this._isMonitoring) {
  60035. this._isMonitoring = true;
  60036. //back-comp
  60037. if (!this._scene) {
  60038. this._checkGamepadsStatus();
  60039. }
  60040. }
  60041. };
  60042. GamepadManager.prototype._stopMonitoringGamepads = function () {
  60043. this._isMonitoring = false;
  60044. };
  60045. GamepadManager.prototype._checkGamepadsStatus = function () {
  60046. var _this = this;
  60047. // Hack to be compatible Chrome
  60048. this._updateGamepadObjects();
  60049. for (var i in this._babylonGamepads) {
  60050. var gamepad = this._babylonGamepads[i];
  60051. if (!gamepad || !gamepad.isConnected) {
  60052. continue;
  60053. }
  60054. gamepad.update();
  60055. }
  60056. if (this._isMonitoring && !this._scene) {
  60057. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  60058. }
  60059. };
  60060. // This function is called only on Chrome, which does not properly support
  60061. // connection/disconnection events and forces you to recopy again the gamepad object
  60062. GamepadManager.prototype._updateGamepadObjects = function () {
  60063. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  60064. for (var i = 0; i < gamepads.length; i++) {
  60065. if (gamepads[i]) {
  60066. if (!this._babylonGamepads[gamepads[i].index]) {
  60067. var newGamepad = this._addNewGamepad(gamepads[i]);
  60068. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  60069. }
  60070. else {
  60071. // Forced to copy again this object for Chrome for unknown reason
  60072. this._babylonGamepads[i].browserGamepad = gamepads[i];
  60073. if (!this._babylonGamepads[i].isConnected) {
  60074. this._babylonGamepads[i]._isConnected = true;
  60075. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  60076. }
  60077. }
  60078. }
  60079. }
  60080. };
  60081. return GamepadManager;
  60082. }());
  60083. BABYLON.GamepadManager = GamepadManager;
  60084. })(BABYLON || (BABYLON = {}));
  60085. //# sourceMappingURL=babylon.gamepadManager.js.map
  60086. var BABYLON;
  60087. (function (BABYLON) {
  60088. var StickValues = /** @class */ (function () {
  60089. function StickValues(x, y) {
  60090. this.x = x;
  60091. this.y = y;
  60092. }
  60093. return StickValues;
  60094. }());
  60095. BABYLON.StickValues = StickValues;
  60096. var Gamepad = /** @class */ (function () {
  60097. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  60098. if (leftStickX === void 0) { leftStickX = 0; }
  60099. if (leftStickY === void 0) { leftStickY = 1; }
  60100. if (rightStickX === void 0) { rightStickX = 2; }
  60101. if (rightStickY === void 0) { rightStickY = 3; }
  60102. this.id = id;
  60103. this.index = index;
  60104. this.browserGamepad = browserGamepad;
  60105. this._isConnected = true;
  60106. this._invertLeftStickY = false;
  60107. this.type = Gamepad.GAMEPAD;
  60108. this._leftStickAxisX = leftStickX;
  60109. this._leftStickAxisY = leftStickY;
  60110. this._rightStickAxisX = rightStickX;
  60111. this._rightStickAxisY = rightStickY;
  60112. if (this.browserGamepad.axes.length >= 2) {
  60113. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  60114. }
  60115. if (this.browserGamepad.axes.length >= 4) {
  60116. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  60117. }
  60118. }
  60119. Object.defineProperty(Gamepad.prototype, "isConnected", {
  60120. get: function () {
  60121. return this._isConnected;
  60122. },
  60123. enumerable: true,
  60124. configurable: true
  60125. });
  60126. Gamepad.prototype.onleftstickchanged = function (callback) {
  60127. this._onleftstickchanged = callback;
  60128. };
  60129. Gamepad.prototype.onrightstickchanged = function (callback) {
  60130. this._onrightstickchanged = callback;
  60131. };
  60132. Object.defineProperty(Gamepad.prototype, "leftStick", {
  60133. get: function () {
  60134. return this._leftStick;
  60135. },
  60136. set: function (newValues) {
  60137. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  60138. this._onleftstickchanged(newValues);
  60139. }
  60140. this._leftStick = newValues;
  60141. },
  60142. enumerable: true,
  60143. configurable: true
  60144. });
  60145. Object.defineProperty(Gamepad.prototype, "rightStick", {
  60146. get: function () {
  60147. return this._rightStick;
  60148. },
  60149. set: function (newValues) {
  60150. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  60151. this._onrightstickchanged(newValues);
  60152. }
  60153. this._rightStick = newValues;
  60154. },
  60155. enumerable: true,
  60156. configurable: true
  60157. });
  60158. Gamepad.prototype.update = function () {
  60159. if (this._leftStick) {
  60160. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  60161. if (this._invertLeftStickY) {
  60162. this.leftStick.y *= -1;
  60163. }
  60164. }
  60165. if (this._rightStick) {
  60166. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  60167. }
  60168. };
  60169. Gamepad.prototype.dispose = function () {
  60170. };
  60171. Gamepad.GAMEPAD = 0;
  60172. Gamepad.GENERIC = 1;
  60173. Gamepad.XBOX = 2;
  60174. Gamepad.POSE_ENABLED = 3;
  60175. return Gamepad;
  60176. }());
  60177. BABYLON.Gamepad = Gamepad;
  60178. var GenericPad = /** @class */ (function (_super) {
  60179. __extends(GenericPad, _super);
  60180. function GenericPad(id, index, browserGamepad) {
  60181. var _this = _super.call(this, id, index, browserGamepad) || this;
  60182. _this.onButtonDownObservable = new BABYLON.Observable();
  60183. _this.onButtonUpObservable = new BABYLON.Observable();
  60184. _this.type = Gamepad.GENERIC;
  60185. _this._buttons = new Array(browserGamepad.buttons.length);
  60186. return _this;
  60187. }
  60188. GenericPad.prototype.onbuttondown = function (callback) {
  60189. this._onbuttondown = callback;
  60190. };
  60191. GenericPad.prototype.onbuttonup = function (callback) {
  60192. this._onbuttonup = callback;
  60193. };
  60194. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  60195. if (newValue !== currentValue) {
  60196. if (newValue === 1) {
  60197. if (this._onbuttondown) {
  60198. this._onbuttondown(buttonIndex);
  60199. }
  60200. this.onButtonDownObservable.notifyObservers(buttonIndex);
  60201. }
  60202. if (newValue === 0) {
  60203. if (this._onbuttonup) {
  60204. this._onbuttonup(buttonIndex);
  60205. }
  60206. this.onButtonUpObservable.notifyObservers(buttonIndex);
  60207. }
  60208. }
  60209. return newValue;
  60210. };
  60211. GenericPad.prototype.update = function () {
  60212. _super.prototype.update.call(this);
  60213. for (var index = 0; index < this._buttons.length; index++) {
  60214. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  60215. }
  60216. };
  60217. GenericPad.prototype.dispose = function () {
  60218. _super.prototype.dispose.call(this);
  60219. this.onButtonDownObservable.clear();
  60220. this.onButtonUpObservable.clear();
  60221. };
  60222. return GenericPad;
  60223. }(Gamepad));
  60224. BABYLON.GenericPad = GenericPad;
  60225. })(BABYLON || (BABYLON = {}));
  60226. //# sourceMappingURL=babylon.gamepad.js.map
  60227. var BABYLON;
  60228. (function (BABYLON) {
  60229. var Xbox360Button;
  60230. (function (Xbox360Button) {
  60231. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  60232. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  60233. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  60234. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  60235. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  60236. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  60237. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  60238. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  60239. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  60240. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  60241. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  60242. var Xbox360Dpad;
  60243. (function (Xbox360Dpad) {
  60244. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  60245. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  60246. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  60247. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  60248. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  60249. var Xbox360Pad = /** @class */ (function (_super) {
  60250. __extends(Xbox360Pad, _super);
  60251. function Xbox360Pad(id, index, gamepad, xboxOne) {
  60252. if (xboxOne === void 0) { xboxOne = false; }
  60253. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  60254. _this._leftTrigger = 0;
  60255. _this._rightTrigger = 0;
  60256. _this.onButtonDownObservable = new BABYLON.Observable();
  60257. _this.onButtonUpObservable = new BABYLON.Observable();
  60258. _this.onPadDownObservable = new BABYLON.Observable();
  60259. _this.onPadUpObservable = new BABYLON.Observable();
  60260. _this._buttonA = 0;
  60261. _this._buttonB = 0;
  60262. _this._buttonX = 0;
  60263. _this._buttonY = 0;
  60264. _this._buttonBack = 0;
  60265. _this._buttonStart = 0;
  60266. _this._buttonLB = 0;
  60267. _this._buttonRB = 0;
  60268. _this._buttonLeftStick = 0;
  60269. _this._buttonRightStick = 0;
  60270. _this._dPadUp = 0;
  60271. _this._dPadDown = 0;
  60272. _this._dPadLeft = 0;
  60273. _this._dPadRight = 0;
  60274. _this._isXboxOnePad = false;
  60275. _this.type = BABYLON.Gamepad.XBOX;
  60276. _this._isXboxOnePad = xboxOne;
  60277. return _this;
  60278. }
  60279. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  60280. this._onlefttriggerchanged = callback;
  60281. };
  60282. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  60283. this._onrighttriggerchanged = callback;
  60284. };
  60285. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  60286. get: function () {
  60287. return this._leftTrigger;
  60288. },
  60289. set: function (newValue) {
  60290. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  60291. this._onlefttriggerchanged(newValue);
  60292. }
  60293. this._leftTrigger = newValue;
  60294. },
  60295. enumerable: true,
  60296. configurable: true
  60297. });
  60298. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  60299. get: function () {
  60300. return this._rightTrigger;
  60301. },
  60302. set: function (newValue) {
  60303. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  60304. this._onrighttriggerchanged(newValue);
  60305. }
  60306. this._rightTrigger = newValue;
  60307. },
  60308. enumerable: true,
  60309. configurable: true
  60310. });
  60311. Xbox360Pad.prototype.onbuttondown = function (callback) {
  60312. this._onbuttondown = callback;
  60313. };
  60314. Xbox360Pad.prototype.onbuttonup = function (callback) {
  60315. this._onbuttonup = callback;
  60316. };
  60317. Xbox360Pad.prototype.ondpaddown = function (callback) {
  60318. this._ondpaddown = callback;
  60319. };
  60320. Xbox360Pad.prototype.ondpadup = function (callback) {
  60321. this._ondpadup = callback;
  60322. };
  60323. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  60324. if (newValue !== currentValue) {
  60325. if (newValue === 1) {
  60326. if (this._onbuttondown) {
  60327. this._onbuttondown(buttonType);
  60328. }
  60329. this.onButtonDownObservable.notifyObservers(buttonType);
  60330. }
  60331. if (newValue === 0) {
  60332. if (this._onbuttonup) {
  60333. this._onbuttonup(buttonType);
  60334. }
  60335. this.onButtonUpObservable.notifyObservers(buttonType);
  60336. }
  60337. }
  60338. return newValue;
  60339. };
  60340. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  60341. if (newValue !== currentValue) {
  60342. if (newValue === 1) {
  60343. if (this._ondpaddown) {
  60344. this._ondpaddown(buttonType);
  60345. }
  60346. this.onPadDownObservable.notifyObservers(buttonType);
  60347. }
  60348. if (newValue === 0) {
  60349. if (this._ondpadup) {
  60350. this._ondpadup(buttonType);
  60351. }
  60352. this.onPadUpObservable.notifyObservers(buttonType);
  60353. }
  60354. }
  60355. return newValue;
  60356. };
  60357. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  60358. get: function () {
  60359. return this._buttonA;
  60360. },
  60361. set: function (value) {
  60362. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  60363. },
  60364. enumerable: true,
  60365. configurable: true
  60366. });
  60367. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  60368. get: function () {
  60369. return this._buttonB;
  60370. },
  60371. set: function (value) {
  60372. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  60373. },
  60374. enumerable: true,
  60375. configurable: true
  60376. });
  60377. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  60378. get: function () {
  60379. return this._buttonX;
  60380. },
  60381. set: function (value) {
  60382. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  60383. },
  60384. enumerable: true,
  60385. configurable: true
  60386. });
  60387. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  60388. get: function () {
  60389. return this._buttonY;
  60390. },
  60391. set: function (value) {
  60392. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  60393. },
  60394. enumerable: true,
  60395. configurable: true
  60396. });
  60397. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  60398. get: function () {
  60399. return this._buttonStart;
  60400. },
  60401. set: function (value) {
  60402. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  60403. },
  60404. enumerable: true,
  60405. configurable: true
  60406. });
  60407. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  60408. get: function () {
  60409. return this._buttonBack;
  60410. },
  60411. set: function (value) {
  60412. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  60413. },
  60414. enumerable: true,
  60415. configurable: true
  60416. });
  60417. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  60418. get: function () {
  60419. return this._buttonLB;
  60420. },
  60421. set: function (value) {
  60422. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  60423. },
  60424. enumerable: true,
  60425. configurable: true
  60426. });
  60427. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  60428. get: function () {
  60429. return this._buttonRB;
  60430. },
  60431. set: function (value) {
  60432. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  60433. },
  60434. enumerable: true,
  60435. configurable: true
  60436. });
  60437. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  60438. get: function () {
  60439. return this._buttonLeftStick;
  60440. },
  60441. set: function (value) {
  60442. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  60443. },
  60444. enumerable: true,
  60445. configurable: true
  60446. });
  60447. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  60448. get: function () {
  60449. return this._buttonRightStick;
  60450. },
  60451. set: function (value) {
  60452. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  60453. },
  60454. enumerable: true,
  60455. configurable: true
  60456. });
  60457. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  60458. get: function () {
  60459. return this._dPadUp;
  60460. },
  60461. set: function (value) {
  60462. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  60463. },
  60464. enumerable: true,
  60465. configurable: true
  60466. });
  60467. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  60468. get: function () {
  60469. return this._dPadDown;
  60470. },
  60471. set: function (value) {
  60472. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  60473. },
  60474. enumerable: true,
  60475. configurable: true
  60476. });
  60477. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  60478. get: function () {
  60479. return this._dPadLeft;
  60480. },
  60481. set: function (value) {
  60482. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  60483. },
  60484. enumerable: true,
  60485. configurable: true
  60486. });
  60487. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  60488. get: function () {
  60489. return this._dPadRight;
  60490. },
  60491. set: function (value) {
  60492. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  60493. },
  60494. enumerable: true,
  60495. configurable: true
  60496. });
  60497. Xbox360Pad.prototype.update = function () {
  60498. _super.prototype.update.call(this);
  60499. if (this._isXboxOnePad) {
  60500. this.buttonA = this.browserGamepad.buttons[0].value;
  60501. this.buttonB = this.browserGamepad.buttons[1].value;
  60502. this.buttonX = this.browserGamepad.buttons[2].value;
  60503. this.buttonY = this.browserGamepad.buttons[3].value;
  60504. this.buttonLB = this.browserGamepad.buttons[4].value;
  60505. this.buttonRB = this.browserGamepad.buttons[5].value;
  60506. this.leftTrigger = this.browserGamepad.axes[2];
  60507. this.rightTrigger = this.browserGamepad.axes[5];
  60508. this.buttonBack = this.browserGamepad.buttons[9].value;
  60509. this.buttonStart = this.browserGamepad.buttons[8].value;
  60510. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  60511. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  60512. this.dPadUp = this.browserGamepad.buttons[11].value;
  60513. this.dPadDown = this.browserGamepad.buttons[12].value;
  60514. this.dPadLeft = this.browserGamepad.buttons[13].value;
  60515. this.dPadRight = this.browserGamepad.buttons[14].value;
  60516. }
  60517. else {
  60518. this.buttonA = this.browserGamepad.buttons[0].value;
  60519. this.buttonB = this.browserGamepad.buttons[1].value;
  60520. this.buttonX = this.browserGamepad.buttons[2].value;
  60521. this.buttonY = this.browserGamepad.buttons[3].value;
  60522. this.buttonLB = this.browserGamepad.buttons[4].value;
  60523. this.buttonRB = this.browserGamepad.buttons[5].value;
  60524. this.leftTrigger = this.browserGamepad.buttons[6].value;
  60525. this.rightTrigger = this.browserGamepad.buttons[7].value;
  60526. this.buttonBack = this.browserGamepad.buttons[8].value;
  60527. this.buttonStart = this.browserGamepad.buttons[9].value;
  60528. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  60529. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  60530. this.dPadUp = this.browserGamepad.buttons[12].value;
  60531. this.dPadDown = this.browserGamepad.buttons[13].value;
  60532. this.dPadLeft = this.browserGamepad.buttons[14].value;
  60533. this.dPadRight = this.browserGamepad.buttons[15].value;
  60534. }
  60535. };
  60536. Xbox360Pad.prototype.dispose = function () {
  60537. _super.prototype.dispose.call(this);
  60538. this.onButtonDownObservable.clear();
  60539. this.onButtonUpObservable.clear();
  60540. this.onPadDownObservable.clear();
  60541. this.onPadUpObservable.clear();
  60542. };
  60543. return Xbox360Pad;
  60544. }(BABYLON.Gamepad));
  60545. BABYLON.Xbox360Pad = Xbox360Pad;
  60546. })(BABYLON || (BABYLON = {}));
  60547. //# sourceMappingURL=babylon.xboxGamepad.js.map
  60548. var BABYLON;
  60549. (function (BABYLON) {
  60550. var PoseEnabledControllerType;
  60551. (function (PoseEnabledControllerType) {
  60552. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  60553. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  60554. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  60555. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  60556. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  60557. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  60558. var PoseEnabledControllerHelper = /** @class */ (function () {
  60559. function PoseEnabledControllerHelper() {
  60560. }
  60561. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  60562. // Oculus Touch
  60563. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  60564. return new BABYLON.OculusTouchController(vrGamepad);
  60565. }
  60566. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  60567. return new BABYLON.WindowsMotionController(vrGamepad);
  60568. }
  60569. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  60570. return new BABYLON.ViveController(vrGamepad);
  60571. }
  60572. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  60573. return new BABYLON.GearVRController(vrGamepad);
  60574. }
  60575. else {
  60576. return new BABYLON.GenericController(vrGamepad);
  60577. }
  60578. };
  60579. return PoseEnabledControllerHelper;
  60580. }());
  60581. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  60582. var PoseEnabledController = /** @class */ (function (_super) {
  60583. __extends(PoseEnabledController, _super);
  60584. function PoseEnabledController(browserGamepad) {
  60585. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  60586. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  60587. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  60588. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  60589. // Represents device position and rotation in babylon space
  60590. _this.devicePosition = BABYLON.Vector3.Zero();
  60591. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  60592. _this.deviceScaleFactor = 1;
  60593. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  60594. _this._deviceToWorld = BABYLON.Matrix.Identity();
  60595. _this._workingMatrix = BABYLON.Matrix.Identity();
  60596. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  60597. _this.controllerType = PoseEnabledControllerType.GENERIC;
  60598. _this.position = BABYLON.Vector3.Zero();
  60599. _this.rotationQuaternion = new BABYLON.Quaternion();
  60600. _this._calculatedPosition = BABYLON.Vector3.Zero();
  60601. _this._calculatedRotation = new BABYLON.Quaternion();
  60602. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  60603. return _this;
  60604. }
  60605. PoseEnabledController.prototype.update = function () {
  60606. _super.prototype.update.call(this);
  60607. var pose = this.browserGamepad.pose;
  60608. this.updateFromDevice(pose);
  60609. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  60610. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  60611. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  60612. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  60613. if (this._mesh) {
  60614. this._mesh.position.copyFrom(this.devicePosition);
  60615. if (this._mesh.rotationQuaternion) {
  60616. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  60617. }
  60618. }
  60619. };
  60620. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  60621. if (poseData) {
  60622. this.rawPose = poseData;
  60623. if (poseData.position) {
  60624. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  60625. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  60626. this._deviceRoomPosition.z *= -1;
  60627. }
  60628. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  60629. this._calculatedPosition.addInPlace(this.position);
  60630. }
  60631. var pose = this.rawPose;
  60632. if (poseData.orientation && pose.orientation) {
  60633. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  60634. if (this._mesh) {
  60635. if (this._mesh.getScene().useRightHandedSystem) {
  60636. this._deviceRoomRotationQuaternion.z *= -1;
  60637. this._deviceRoomRotationQuaternion.w *= -1;
  60638. }
  60639. else {
  60640. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  60641. }
  60642. }
  60643. // if the camera is set, rotate to the camera's rotation
  60644. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  60645. }
  60646. }
  60647. };
  60648. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  60649. if (this._mesh) {
  60650. this._mesh.parent = null;
  60651. }
  60652. this._mesh = mesh;
  60653. if (this._poseControlledCamera) {
  60654. this._mesh.parent = this._poseControlledCamera;
  60655. }
  60656. if (!this._mesh.rotationQuaternion) {
  60657. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  60658. }
  60659. };
  60660. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  60661. this._poseControlledCamera = camera;
  60662. if (this._mesh) {
  60663. this._mesh.parent = this._poseControlledCamera;
  60664. }
  60665. };
  60666. PoseEnabledController.prototype.dispose = function () {
  60667. if (this._mesh) {
  60668. this._mesh.dispose();
  60669. }
  60670. this._mesh = null;
  60671. _super.prototype.dispose.call(this);
  60672. };
  60673. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  60674. get: function () {
  60675. return this._mesh;
  60676. },
  60677. enumerable: true,
  60678. configurable: true
  60679. });
  60680. PoseEnabledController.prototype.getForwardRay = function (length) {
  60681. if (length === void 0) { length = 100; }
  60682. if (!this.mesh) {
  60683. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  60684. }
  60685. var m = this.mesh.getWorldMatrix();
  60686. var origin = m.getTranslation();
  60687. var forward = new BABYLON.Vector3(0, 0, -1);
  60688. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  60689. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  60690. return new BABYLON.Ray(origin, direction, length);
  60691. };
  60692. return PoseEnabledController;
  60693. }(BABYLON.Gamepad));
  60694. BABYLON.PoseEnabledController = PoseEnabledController;
  60695. })(BABYLON || (BABYLON = {}));
  60696. //# sourceMappingURL=babylon.poseEnabledController.js.map
  60697. var BABYLON;
  60698. (function (BABYLON) {
  60699. var WebVRController = /** @class */ (function (_super) {
  60700. __extends(WebVRController, _super);
  60701. function WebVRController(vrGamepad) {
  60702. var _this = _super.call(this, vrGamepad) || this;
  60703. // Observables
  60704. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  60705. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  60706. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  60707. _this.onPadStateChangedObservable = new BABYLON.Observable();
  60708. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  60709. _this.pad = { x: 0, y: 0 };
  60710. // avoid GC, store state in a tmp object
  60711. _this._changes = {
  60712. pressChanged: false,
  60713. touchChanged: false,
  60714. valueChanged: false,
  60715. changed: false
  60716. };
  60717. _this._buttons = new Array(vrGamepad.buttons.length);
  60718. _this.hand = vrGamepad.hand;
  60719. return _this;
  60720. }
  60721. WebVRController.prototype.onButtonStateChange = function (callback) {
  60722. this._onButtonStateChange = callback;
  60723. };
  60724. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  60725. get: function () {
  60726. return this._defaultModel;
  60727. },
  60728. enumerable: true,
  60729. configurable: true
  60730. });
  60731. WebVRController.prototype.update = function () {
  60732. _super.prototype.update.call(this);
  60733. for (var index = 0; index < this._buttons.length; index++) {
  60734. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  60735. }
  60736. ;
  60737. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  60738. this.pad.x = this.leftStick.x;
  60739. this.pad.y = this.leftStick.y;
  60740. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  60741. }
  60742. };
  60743. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  60744. if (!newState) {
  60745. newState = {
  60746. pressed: false,
  60747. touched: false,
  60748. value: 0
  60749. };
  60750. }
  60751. if (!currentState) {
  60752. this._buttons[buttonIndex] = {
  60753. pressed: newState.pressed,
  60754. touched: newState.touched,
  60755. value: newState.value
  60756. };
  60757. return;
  60758. }
  60759. this._checkChanges(newState, currentState);
  60760. if (this._changes.changed) {
  60761. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  60762. this.handleButtonChange(buttonIndex, newState, this._changes);
  60763. }
  60764. this._buttons[buttonIndex].pressed = newState.pressed;
  60765. this._buttons[buttonIndex].touched = newState.touched;
  60766. // oculus triggers are never 0, thou not touched.
  60767. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  60768. };
  60769. WebVRController.prototype._checkChanges = function (newState, currentState) {
  60770. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  60771. this._changes.touchChanged = newState.touched !== currentState.touched;
  60772. this._changes.valueChanged = newState.value !== currentState.value;
  60773. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  60774. return this._changes;
  60775. };
  60776. WebVRController.prototype.dispose = function () {
  60777. _super.prototype.dispose.call(this);
  60778. this.onTriggerStateChangedObservable.clear();
  60779. this.onMainButtonStateChangedObservable.clear();
  60780. this.onSecondaryButtonStateChangedObservable.clear();
  60781. this.onPadStateChangedObservable.clear();
  60782. this.onPadValuesChangedObservable.clear();
  60783. };
  60784. return WebVRController;
  60785. }(BABYLON.PoseEnabledController));
  60786. BABYLON.WebVRController = WebVRController;
  60787. })(BABYLON || (BABYLON = {}));
  60788. //# sourceMappingURL=babylon.webVRController.js.map
  60789. var BABYLON;
  60790. (function (BABYLON) {
  60791. var OculusTouchController = /** @class */ (function (_super) {
  60792. __extends(OculusTouchController, _super);
  60793. function OculusTouchController(vrGamepad) {
  60794. var _this = _super.call(this, vrGamepad) || this;
  60795. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  60796. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  60797. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  60798. return _this;
  60799. }
  60800. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60801. var _this = this;
  60802. var meshName;
  60803. // Hand
  60804. if (this.hand === 'left') {
  60805. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  60806. }
  60807. else {
  60808. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  60809. }
  60810. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  60811. /*
  60812. Parent Mesh name: oculus_touch_left
  60813. - body
  60814. - trigger
  60815. - thumbstick
  60816. - grip
  60817. - button_y
  60818. - button_x
  60819. - button_enter
  60820. */
  60821. _this._defaultModel = newMeshes[1];
  60822. _this.attachToMesh(_this._defaultModel);
  60823. if (meshLoaded) {
  60824. meshLoaded(_this._defaultModel);
  60825. }
  60826. });
  60827. };
  60828. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  60829. // helper getters for left and right hand.
  60830. get: function () {
  60831. if (this.hand === 'right') {
  60832. return this.onMainButtonStateChangedObservable;
  60833. }
  60834. else {
  60835. throw new Error('No A button on left hand');
  60836. }
  60837. },
  60838. enumerable: true,
  60839. configurable: true
  60840. });
  60841. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  60842. get: function () {
  60843. if (this.hand === 'right') {
  60844. return this.onSecondaryButtonStateChangedObservable;
  60845. }
  60846. else {
  60847. throw new Error('No B button on left hand');
  60848. }
  60849. },
  60850. enumerable: true,
  60851. configurable: true
  60852. });
  60853. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  60854. get: function () {
  60855. if (this.hand === 'left') {
  60856. return this.onMainButtonStateChangedObservable;
  60857. }
  60858. else {
  60859. throw new Error('No X button on right hand');
  60860. }
  60861. },
  60862. enumerable: true,
  60863. configurable: true
  60864. });
  60865. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  60866. get: function () {
  60867. if (this.hand === 'left') {
  60868. return this.onSecondaryButtonStateChangedObservable;
  60869. }
  60870. else {
  60871. throw new Error('No Y button on right hand');
  60872. }
  60873. },
  60874. enumerable: true,
  60875. configurable: true
  60876. });
  60877. /*
  60878. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  60879. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  60880. 2) secondary trigger (same)
  60881. 3) A (right) X (left), touch, pressed = value
  60882. 4) B / Y
  60883. 5) thumb rest
  60884. */
  60885. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60886. var notifyObject = state; //{ state: state, changes: changes };
  60887. var triggerDirection = this.hand === 'right' ? -1 : 1;
  60888. switch (buttonIdx) {
  60889. case 0:
  60890. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60891. return;
  60892. case 1:// index trigger
  60893. if (this._defaultModel) {
  60894. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  60895. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  60896. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  60897. }
  60898. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60899. return;
  60900. case 2:// secondary trigger
  60901. if (this._defaultModel) {
  60902. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  60903. }
  60904. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  60905. return;
  60906. case 3:
  60907. if (this._defaultModel) {
  60908. if (notifyObject.pressed) {
  60909. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  60910. }
  60911. else {
  60912. (this._defaultModel.getChildren()[1]).position.y = 0;
  60913. }
  60914. }
  60915. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60916. return;
  60917. case 4:
  60918. if (this._defaultModel) {
  60919. if (notifyObject.pressed) {
  60920. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60921. }
  60922. else {
  60923. (this._defaultModel.getChildren()[2]).position.y = 0;
  60924. }
  60925. }
  60926. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60927. return;
  60928. case 5:
  60929. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  60930. return;
  60931. }
  60932. };
  60933. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  60934. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  60935. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  60936. return OculusTouchController;
  60937. }(BABYLON.WebVRController));
  60938. BABYLON.OculusTouchController = OculusTouchController;
  60939. })(BABYLON || (BABYLON = {}));
  60940. //# sourceMappingURL=babylon.oculusTouchController.js.map
  60941. var BABYLON;
  60942. (function (BABYLON) {
  60943. var ViveController = /** @class */ (function (_super) {
  60944. __extends(ViveController, _super);
  60945. function ViveController(vrGamepad) {
  60946. var _this = _super.call(this, vrGamepad) || this;
  60947. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  60948. _this._invertLeftStickY = true;
  60949. return _this;
  60950. }
  60951. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60952. var _this = this;
  60953. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  60954. /*
  60955. Parent Mesh name: ViveWand
  60956. - body
  60957. - r_gripper
  60958. - l_gripper
  60959. - menu_button
  60960. - system_button
  60961. - trackpad
  60962. - trigger
  60963. - LED
  60964. */
  60965. _this._defaultModel = newMeshes[1];
  60966. _this.attachToMesh(_this._defaultModel);
  60967. if (meshLoaded) {
  60968. meshLoaded(_this._defaultModel);
  60969. }
  60970. });
  60971. };
  60972. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  60973. get: function () {
  60974. return this.onMainButtonStateChangedObservable;
  60975. },
  60976. enumerable: true,
  60977. configurable: true
  60978. });
  60979. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  60980. get: function () {
  60981. return this.onMainButtonStateChangedObservable;
  60982. },
  60983. enumerable: true,
  60984. configurable: true
  60985. });
  60986. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  60987. get: function () {
  60988. return this.onSecondaryButtonStateChangedObservable;
  60989. },
  60990. enumerable: true,
  60991. configurable: true
  60992. });
  60993. /**
  60994. * Vive mapping:
  60995. * 0: touchpad
  60996. * 1: trigger
  60997. * 2: left AND right buttons
  60998. * 3: menu button
  60999. */
  61000. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61001. var notifyObject = state; //{ state: state, changes: changes };
  61002. switch (buttonIdx) {
  61003. case 0:
  61004. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  61005. return;
  61006. case 1:// index trigger
  61007. if (this._defaultModel) {
  61008. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  61009. }
  61010. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  61011. return;
  61012. case 2:// left AND right button
  61013. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  61014. return;
  61015. case 3:
  61016. if (this._defaultModel) {
  61017. if (notifyObject.pressed) {
  61018. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  61019. }
  61020. else {
  61021. (this._defaultModel.getChildren()[2]).position.y = 0;
  61022. }
  61023. }
  61024. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  61025. return;
  61026. }
  61027. };
  61028. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  61029. ViveController.MODEL_FILENAME = 'wand.babylon';
  61030. return ViveController;
  61031. }(BABYLON.WebVRController));
  61032. BABYLON.ViveController = ViveController;
  61033. })(BABYLON || (BABYLON = {}));
  61034. //# sourceMappingURL=babylon.viveController.js.map
  61035. var BABYLON;
  61036. (function (BABYLON) {
  61037. var GenericController = /** @class */ (function (_super) {
  61038. __extends(GenericController, _super);
  61039. function GenericController(vrGamepad) {
  61040. return _super.call(this, vrGamepad) || this;
  61041. }
  61042. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61043. var _this = this;
  61044. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  61045. _this._defaultModel = newMeshes[1];
  61046. _this.attachToMesh(_this._defaultModel);
  61047. if (meshLoaded) {
  61048. meshLoaded(_this._defaultModel);
  61049. }
  61050. });
  61051. };
  61052. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61053. console.log("Button id: " + buttonIdx + "state: ");
  61054. console.dir(state);
  61055. };
  61056. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  61057. GenericController.MODEL_FILENAME = 'generic.babylon';
  61058. return GenericController;
  61059. }(BABYLON.WebVRController));
  61060. BABYLON.GenericController = GenericController;
  61061. })(BABYLON || (BABYLON = {}));
  61062. //# sourceMappingURL=babylon.genericController.js.map
  61063. var BABYLON;
  61064. (function (BABYLON) {
  61065. var LoadedMeshInfo = /** @class */ (function () {
  61066. function LoadedMeshInfo() {
  61067. this.buttonMeshes = {};
  61068. this.axisMeshes = {};
  61069. }
  61070. return LoadedMeshInfo;
  61071. }());
  61072. var WindowsMotionController = /** @class */ (function (_super) {
  61073. __extends(WindowsMotionController, _super);
  61074. function WindowsMotionController(vrGamepad) {
  61075. var _this = _super.call(this, vrGamepad) || this;
  61076. _this._mapping = {
  61077. // Semantic button names
  61078. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  61079. // A mapping of the button name to glTF model node name
  61080. // that should be transformed by button value.
  61081. buttonMeshNames: {
  61082. 'trigger': 'SELECT',
  61083. 'menu': 'MENU',
  61084. 'grip': 'GRASP',
  61085. 'thumbstick': 'THUMBSTICK_PRESS',
  61086. 'trackpad': 'TOUCHPAD_PRESS'
  61087. },
  61088. // This mapping is used to translate from the Motion Controller to Babylon semantics
  61089. buttonObservableNames: {
  61090. 'trigger': 'onTriggerStateChangedObservable',
  61091. 'menu': 'onSecondaryButtonStateChangedObservable',
  61092. 'grip': 'onMainButtonStateChangedObservable',
  61093. 'thumbstick': 'onPadStateChangedObservable',
  61094. 'trackpad': 'onTrackpadChangedObservable'
  61095. },
  61096. // A mapping of the axis name to glTF model node name
  61097. // that should be transformed by axis value.
  61098. // This array mirrors the browserGamepad.axes array, such that
  61099. // the mesh corresponding to axis 0 is in this array index 0.
  61100. axisMeshNames: [
  61101. 'THUMBSTICK_X',
  61102. 'THUMBSTICK_Y',
  61103. 'TOUCHPAD_TOUCH_X',
  61104. 'TOUCHPAD_TOUCH_Y'
  61105. ],
  61106. pointingPoseMeshName: 'POINTING_POSE'
  61107. };
  61108. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  61109. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  61110. _this.trackpad = { x: 0, y: 0 };
  61111. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  61112. _this._loadedMeshInfo = null;
  61113. return _this;
  61114. }
  61115. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  61116. get: function () {
  61117. return this.onTriggerStateChangedObservable;
  61118. },
  61119. enumerable: true,
  61120. configurable: true
  61121. });
  61122. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  61123. get: function () {
  61124. return this.onSecondaryButtonStateChangedObservable;
  61125. },
  61126. enumerable: true,
  61127. configurable: true
  61128. });
  61129. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  61130. get: function () {
  61131. return this.onMainButtonStateChangedObservable;
  61132. },
  61133. enumerable: true,
  61134. configurable: true
  61135. });
  61136. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  61137. get: function () {
  61138. return this.onPadStateChangedObservable;
  61139. },
  61140. enumerable: true,
  61141. configurable: true
  61142. });
  61143. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  61144. get: function () {
  61145. return this.onTrackpadChangedObservable;
  61146. },
  61147. enumerable: true,
  61148. configurable: true
  61149. });
  61150. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  61151. get: function () {
  61152. return this.onTrackpadValuesChangedObservable;
  61153. },
  61154. enumerable: true,
  61155. configurable: true
  61156. });
  61157. /**
  61158. * Called once per frame by the engine.
  61159. */
  61160. WindowsMotionController.prototype.update = function () {
  61161. _super.prototype.update.call(this);
  61162. // Only need to animate axes if there is a loaded mesh
  61163. if (this._loadedMeshInfo) {
  61164. if (this.browserGamepad.axes) {
  61165. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  61166. this.trackpad.x = this.browserGamepad["axes"][2];
  61167. this.trackpad.y = this.browserGamepad["axes"][3];
  61168. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  61169. }
  61170. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  61171. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  61172. }
  61173. }
  61174. }
  61175. };
  61176. /**
  61177. * Called once for each button that changed state since the last frame
  61178. * @param buttonIdx Which button index changed
  61179. * @param state New state of the button
  61180. * @param changes Which properties on the state changed since last frame
  61181. */
  61182. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61183. var buttonName = this._mapping.buttons[buttonIdx];
  61184. if (!buttonName) {
  61185. return;
  61186. }
  61187. // Only emit events for buttons that we know how to map from index to name
  61188. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  61189. if (observable) {
  61190. observable.notifyObservers(state);
  61191. }
  61192. this.lerpButtonTransform(buttonName, state.value);
  61193. };
  61194. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  61195. // If there is no loaded mesh, there is nothing to transform.
  61196. if (!this._loadedMeshInfo) {
  61197. return;
  61198. }
  61199. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  61200. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  61201. return;
  61202. }
  61203. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  61204. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  61205. };
  61206. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  61207. if (!this._loadedMeshInfo) {
  61208. return;
  61209. }
  61210. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  61211. if (!meshInfo) {
  61212. return;
  61213. }
  61214. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  61215. return;
  61216. }
  61217. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  61218. var lerpValue = axisValue * 0.5 + 0.5;
  61219. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  61220. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  61221. };
  61222. /**
  61223. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  61224. * @param scene scene in which to add meshes
  61225. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  61226. */
  61227. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  61228. var _this = this;
  61229. if (forceDefault === void 0) { forceDefault = false; }
  61230. var path;
  61231. var filename;
  61232. // Checking if GLB loader is present
  61233. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  61234. // Determine the device specific folder based on the ID suffix
  61235. var device = 'default';
  61236. if (this.id && !forceDefault) {
  61237. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  61238. device = ((match && match[0]) || device);
  61239. }
  61240. // Hand
  61241. if (this.hand === 'left') {
  61242. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  61243. }
  61244. else {
  61245. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  61246. }
  61247. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  61248. }
  61249. else {
  61250. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  61251. path = BABYLON.GenericController.MODEL_BASE_URL;
  61252. filename = BABYLON.GenericController.MODEL_FILENAME;
  61253. }
  61254. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  61255. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  61256. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  61257. if (!_this._loadedMeshInfo) {
  61258. return;
  61259. }
  61260. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  61261. _this.attachToMesh(_this._defaultModel);
  61262. if (meshLoaded) {
  61263. meshLoaded(_this._defaultModel);
  61264. }
  61265. }, null, function (scene, message) {
  61266. BABYLON.Tools.Log(message);
  61267. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  61268. if (!forceDefault) {
  61269. _this.initControllerMesh(scene, meshLoaded, true);
  61270. }
  61271. });
  61272. };
  61273. /**
  61274. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  61275. * can be transformed by button presses and axes values, based on this._mapping.
  61276. *
  61277. * @param scene scene in which the meshes exist
  61278. * @param meshes list of meshes that make up the controller model to process
  61279. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  61280. */
  61281. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  61282. var loadedMeshInfo = null;
  61283. // Create a new mesh to contain the glTF hierarchy
  61284. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  61285. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  61286. var childMesh = null;
  61287. for (var i = 0; i < meshes.length; i++) {
  61288. var mesh = meshes[i];
  61289. if (!mesh.parent) {
  61290. // Exclude controller meshes from picking results
  61291. mesh.isPickable = false;
  61292. // Handle root node, attach to the new parentMesh
  61293. childMesh = mesh;
  61294. break;
  61295. }
  61296. }
  61297. if (childMesh) {
  61298. childMesh.setParent(parentMesh);
  61299. // Create our mesh info. Note that this method will always return non-null.
  61300. loadedMeshInfo = this.createMeshInfo(parentMesh);
  61301. }
  61302. else {
  61303. BABYLON.Tools.Warn('Could not find root node in model file.');
  61304. }
  61305. return loadedMeshInfo;
  61306. };
  61307. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  61308. var loadedMeshInfo = new LoadedMeshInfo();
  61309. var i;
  61310. loadedMeshInfo.rootNode = rootNode;
  61311. // Reset the caches
  61312. loadedMeshInfo.buttonMeshes = {};
  61313. loadedMeshInfo.axisMeshes = {};
  61314. // Button Meshes
  61315. for (i = 0; i < this._mapping.buttons.length; i++) {
  61316. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  61317. if (!buttonMeshName) {
  61318. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  61319. continue;
  61320. }
  61321. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  61322. if (!buttonMesh) {
  61323. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  61324. continue;
  61325. }
  61326. var buttonMeshInfo = {
  61327. index: i,
  61328. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  61329. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  61330. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  61331. };
  61332. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  61333. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  61334. }
  61335. else {
  61336. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  61337. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  61338. '(VALUE: ' + !!buttonMeshInfo.value +
  61339. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  61340. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  61341. ')');
  61342. }
  61343. }
  61344. // Axis Meshes
  61345. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  61346. var axisMeshName = this._mapping.axisMeshNames[i];
  61347. if (!axisMeshName) {
  61348. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  61349. continue;
  61350. }
  61351. var axisMesh = getChildByName(rootNode, axisMeshName);
  61352. if (!axisMesh) {
  61353. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  61354. continue;
  61355. }
  61356. var axisMeshInfo = {
  61357. index: i,
  61358. value: getImmediateChildByName(axisMesh, 'VALUE'),
  61359. min: getImmediateChildByName(axisMesh, 'MIN'),
  61360. max: getImmediateChildByName(axisMesh, 'MAX')
  61361. };
  61362. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  61363. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  61364. }
  61365. else {
  61366. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  61367. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  61368. '(VALUE: ' + !!axisMeshInfo.value +
  61369. ', MIN: ' + !!axisMeshInfo.min +
  61370. ', MAX:' + !!axisMeshInfo.max +
  61371. ')');
  61372. }
  61373. }
  61374. // Pointing Ray
  61375. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  61376. if (!loadedMeshInfo.pointingPoseNode) {
  61377. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  61378. }
  61379. return loadedMeshInfo;
  61380. // Look through all children recursively. This will return null if no mesh exists with the given name.
  61381. function getChildByName(node, name) {
  61382. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  61383. }
  61384. // Look through only immediate children. This will return null if no mesh exists with the given name.
  61385. function getImmediateChildByName(node, name) {
  61386. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  61387. }
  61388. };
  61389. WindowsMotionController.prototype.getForwardRay = function (length) {
  61390. if (length === void 0) { length = 100; }
  61391. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  61392. return _super.prototype.getForwardRay.call(this, length);
  61393. }
  61394. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  61395. var origin = m.getTranslation();
  61396. var forward = new BABYLON.Vector3(0, 0, -1);
  61397. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  61398. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  61399. return new BABYLON.Ray(origin, direction, length);
  61400. };
  61401. WindowsMotionController.prototype.dispose = function () {
  61402. _super.prototype.dispose.call(this);
  61403. this.onTrackpadChangedObservable.clear();
  61404. };
  61405. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  61406. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  61407. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  61408. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  61409. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  61410. return WindowsMotionController;
  61411. }(BABYLON.WebVRController));
  61412. BABYLON.WindowsMotionController = WindowsMotionController;
  61413. })(BABYLON || (BABYLON = {}));
  61414. //# sourceMappingURL=babylon.windowsMotionController.js.map
  61415. var BABYLON;
  61416. (function (BABYLON) {
  61417. var GearVRController = /** @class */ (function (_super) {
  61418. __extends(GearVRController, _super);
  61419. function GearVRController(vrGamepad) {
  61420. var _this = _super.call(this, vrGamepad) || this;
  61421. _this._buttonIndexToObservableNameMap = [
  61422. 'onTrackpadChangedObservable',
  61423. 'onTriggerStateChangedObservable' // Trigger
  61424. ];
  61425. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  61426. return _this;
  61427. }
  61428. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61429. var _this = this;
  61430. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  61431. _this._defaultModel = newMeshes[1];
  61432. _this.attachToMesh(_this._defaultModel);
  61433. if (meshLoaded) {
  61434. meshLoaded(_this._defaultModel);
  61435. }
  61436. });
  61437. };
  61438. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61439. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  61440. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  61441. // Only emit events for buttons that we know how to map from index to observable
  61442. var observable = this[observableName];
  61443. if (observable) {
  61444. observable.notifyObservers(state);
  61445. }
  61446. }
  61447. };
  61448. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  61449. GearVRController.MODEL_FILENAME = 'generic.babylon';
  61450. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  61451. return GearVRController;
  61452. }(BABYLON.WebVRController));
  61453. BABYLON.GearVRController = GearVRController;
  61454. })(BABYLON || (BABYLON = {}));
  61455. //# sourceMappingURL=babylon.gearVRController.js.map
  61456. var BABYLON;
  61457. (function (BABYLON) {
  61458. var FollowCamera = /** @class */ (function (_super) {
  61459. __extends(FollowCamera, _super);
  61460. function FollowCamera(name, position, scene, lockedTarget) {
  61461. if (lockedTarget === void 0) { lockedTarget = null; }
  61462. var _this = _super.call(this, name, position, scene) || this;
  61463. _this.radius = 12;
  61464. _this.rotationOffset = 0;
  61465. _this.heightOffset = 4;
  61466. _this.cameraAcceleration = 0.05;
  61467. _this.maxCameraSpeed = 20;
  61468. _this.lockedTarget = lockedTarget;
  61469. return _this;
  61470. }
  61471. FollowCamera.prototype.getRadians = function (degrees) {
  61472. return degrees * Math.PI / 180;
  61473. };
  61474. FollowCamera.prototype.follow = function (cameraTarget) {
  61475. if (!cameraTarget)
  61476. return;
  61477. var yRotation;
  61478. if (cameraTarget.rotationQuaternion) {
  61479. var rotMatrix = new BABYLON.Matrix();
  61480. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  61481. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  61482. }
  61483. else {
  61484. yRotation = cameraTarget.rotation.y;
  61485. }
  61486. var radians = this.getRadians(this.rotationOffset) + yRotation;
  61487. var targetPosition = cameraTarget.getAbsolutePosition();
  61488. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  61489. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  61490. var dx = targetX - this.position.x;
  61491. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  61492. var dz = (targetZ) - this.position.z;
  61493. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  61494. var vy = dy * this.cameraAcceleration;
  61495. var vz = dz * this.cameraAcceleration * 2;
  61496. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  61497. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61498. }
  61499. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  61500. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61501. }
  61502. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  61503. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61504. }
  61505. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  61506. this.setTarget(targetPosition);
  61507. };
  61508. FollowCamera.prototype._checkInputs = function () {
  61509. _super.prototype._checkInputs.call(this);
  61510. if (this.lockedTarget) {
  61511. this.follow(this.lockedTarget);
  61512. }
  61513. };
  61514. FollowCamera.prototype.getClassName = function () {
  61515. return "FollowCamera";
  61516. };
  61517. __decorate([
  61518. BABYLON.serialize()
  61519. ], FollowCamera.prototype, "radius", void 0);
  61520. __decorate([
  61521. BABYLON.serialize()
  61522. ], FollowCamera.prototype, "rotationOffset", void 0);
  61523. __decorate([
  61524. BABYLON.serialize()
  61525. ], FollowCamera.prototype, "heightOffset", void 0);
  61526. __decorate([
  61527. BABYLON.serialize()
  61528. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  61529. __decorate([
  61530. BABYLON.serialize()
  61531. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  61532. __decorate([
  61533. BABYLON.serializeAsMeshReference("lockedTargetId")
  61534. ], FollowCamera.prototype, "lockedTarget", void 0);
  61535. return FollowCamera;
  61536. }(BABYLON.TargetCamera));
  61537. BABYLON.FollowCamera = FollowCamera;
  61538. var ArcFollowCamera = /** @class */ (function (_super) {
  61539. __extends(ArcFollowCamera, _super);
  61540. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  61541. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  61542. _this.alpha = alpha;
  61543. _this.beta = beta;
  61544. _this.radius = radius;
  61545. _this.target = target;
  61546. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  61547. _this.follow();
  61548. return _this;
  61549. }
  61550. ArcFollowCamera.prototype.follow = function () {
  61551. if (!this.target) {
  61552. return;
  61553. }
  61554. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  61555. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  61556. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  61557. var targetPosition = this.target.getAbsolutePosition();
  61558. this.position = targetPosition.add(this._cartesianCoordinates);
  61559. this.setTarget(targetPosition);
  61560. };
  61561. ArcFollowCamera.prototype._checkInputs = function () {
  61562. _super.prototype._checkInputs.call(this);
  61563. this.follow();
  61564. };
  61565. ArcFollowCamera.prototype.getClassName = function () {
  61566. return "ArcFollowCamera";
  61567. };
  61568. return ArcFollowCamera;
  61569. }(BABYLON.TargetCamera));
  61570. BABYLON.ArcFollowCamera = ArcFollowCamera;
  61571. })(BABYLON || (BABYLON = {}));
  61572. //# sourceMappingURL=babylon.followCamera.js.map
  61573. var BABYLON;
  61574. (function (BABYLON) {
  61575. // We're mainly based on the logic defined into the FreeCamera code
  61576. var UniversalCamera = /** @class */ (function (_super) {
  61577. __extends(UniversalCamera, _super);
  61578. //-- end properties for backward compatibility for inputs
  61579. function UniversalCamera(name, position, scene) {
  61580. var _this = _super.call(this, name, position, scene) || this;
  61581. _this.inputs.addGamepad();
  61582. return _this;
  61583. }
  61584. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  61585. //-- Begin properties for backward compatibility for inputs
  61586. get: function () {
  61587. var gamepad = this.inputs.attached["gamepad"];
  61588. if (gamepad)
  61589. return gamepad.gamepadAngularSensibility;
  61590. return 0;
  61591. },
  61592. set: function (value) {
  61593. var gamepad = this.inputs.attached["gamepad"];
  61594. if (gamepad)
  61595. gamepad.gamepadAngularSensibility = value;
  61596. },
  61597. enumerable: true,
  61598. configurable: true
  61599. });
  61600. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  61601. get: function () {
  61602. var gamepad = this.inputs.attached["gamepad"];
  61603. if (gamepad)
  61604. return gamepad.gamepadMoveSensibility;
  61605. return 0;
  61606. },
  61607. set: function (value) {
  61608. var gamepad = this.inputs.attached["gamepad"];
  61609. if (gamepad)
  61610. gamepad.gamepadMoveSensibility = value;
  61611. },
  61612. enumerable: true,
  61613. configurable: true
  61614. });
  61615. UniversalCamera.prototype.getClassName = function () {
  61616. return "UniversalCamera";
  61617. };
  61618. return UniversalCamera;
  61619. }(BABYLON.TouchCamera));
  61620. BABYLON.UniversalCamera = UniversalCamera;
  61621. })(BABYLON || (BABYLON = {}));
  61622. //# sourceMappingURL=babylon.universalCamera.js.map
  61623. var BABYLON;
  61624. (function (BABYLON) {
  61625. // We're mainly based on the logic defined into the FreeCamera code
  61626. var GamepadCamera = /** @class */ (function (_super) {
  61627. __extends(GamepadCamera, _super);
  61628. //-- end properties for backward compatibility for inputs
  61629. function GamepadCamera(name, position, scene) {
  61630. return _super.call(this, name, position, scene) || this;
  61631. }
  61632. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  61633. //-- Begin properties for backward compatibility for inputs
  61634. get: function () {
  61635. var gamepad = this.inputs.attached["gamepad"];
  61636. if (gamepad)
  61637. return gamepad.gamepadAngularSensibility;
  61638. return 0;
  61639. },
  61640. set: function (value) {
  61641. var gamepad = this.inputs.attached["gamepad"];
  61642. if (gamepad)
  61643. gamepad.gamepadAngularSensibility = value;
  61644. },
  61645. enumerable: true,
  61646. configurable: true
  61647. });
  61648. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  61649. get: function () {
  61650. var gamepad = this.inputs.attached["gamepad"];
  61651. if (gamepad)
  61652. return gamepad.gamepadMoveSensibility;
  61653. return 0;
  61654. },
  61655. set: function (value) {
  61656. var gamepad = this.inputs.attached["gamepad"];
  61657. if (gamepad)
  61658. gamepad.gamepadMoveSensibility = value;
  61659. },
  61660. enumerable: true,
  61661. configurable: true
  61662. });
  61663. GamepadCamera.prototype.getClassName = function () {
  61664. return "GamepadCamera";
  61665. };
  61666. return GamepadCamera;
  61667. }(BABYLON.UniversalCamera));
  61668. BABYLON.GamepadCamera = GamepadCamera;
  61669. })(BABYLON || (BABYLON = {}));
  61670. //# sourceMappingURL=babylon.gamepadCamera.js.map
  61671. var BABYLON;
  61672. (function (BABYLON) {
  61673. var PostProcessRenderPipelineManager = /** @class */ (function () {
  61674. function PostProcessRenderPipelineManager() {
  61675. this._renderPipelines = {};
  61676. }
  61677. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  61678. this._renderPipelines[renderPipeline._name] = renderPipeline;
  61679. };
  61680. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  61681. if (unique === void 0) { unique = false; }
  61682. var renderPipeline = this._renderPipelines[renderPipelineName];
  61683. if (!renderPipeline) {
  61684. return;
  61685. }
  61686. renderPipeline._attachCameras(cameras, unique);
  61687. };
  61688. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  61689. var renderPipeline = this._renderPipelines[renderPipelineName];
  61690. if (!renderPipeline) {
  61691. return;
  61692. }
  61693. renderPipeline._detachCameras(cameras);
  61694. };
  61695. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  61696. var renderPipeline = this._renderPipelines[renderPipelineName];
  61697. if (!renderPipeline) {
  61698. return;
  61699. }
  61700. renderPipeline._enableEffect(renderEffectName, cameras);
  61701. };
  61702. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  61703. var renderPipeline = this._renderPipelines[renderPipelineName];
  61704. if (!renderPipeline) {
  61705. return;
  61706. }
  61707. renderPipeline._disableEffect(renderEffectName, cameras);
  61708. };
  61709. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  61710. var renderPipeline = this._renderPipelines[renderPipelineName];
  61711. if (!renderPipeline) {
  61712. return;
  61713. }
  61714. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  61715. };
  61716. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  61717. var renderPipeline = this._renderPipelines[renderPipelineName];
  61718. if (!renderPipeline) {
  61719. return;
  61720. }
  61721. renderPipeline._disableDisplayOnlyPass(cameras);
  61722. };
  61723. PostProcessRenderPipelineManager.prototype.update = function () {
  61724. for (var renderPipelineName in this._renderPipelines) {
  61725. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61726. var pipeline = this._renderPipelines[renderPipelineName];
  61727. if (!pipeline.isSupported) {
  61728. pipeline.dispose();
  61729. delete this._renderPipelines[renderPipelineName];
  61730. }
  61731. else {
  61732. pipeline._update();
  61733. }
  61734. }
  61735. }
  61736. };
  61737. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  61738. for (var renderPipelineName in this._renderPipelines) {
  61739. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61740. var pipeline = this._renderPipelines[renderPipelineName];
  61741. pipeline._rebuild();
  61742. }
  61743. }
  61744. };
  61745. PostProcessRenderPipelineManager.prototype.dispose = function () {
  61746. for (var renderPipelineName in this._renderPipelines) {
  61747. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61748. var pipeline = this._renderPipelines[renderPipelineName];
  61749. pipeline.dispose();
  61750. }
  61751. }
  61752. };
  61753. return PostProcessRenderPipelineManager;
  61754. }());
  61755. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  61756. })(BABYLON || (BABYLON = {}));
  61757. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  61758. var BABYLON;
  61759. (function (BABYLON) {
  61760. var PostProcessRenderPass = /** @class */ (function () {
  61761. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  61762. this._refCount = 0;
  61763. this._name = name;
  61764. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  61765. this.setRenderList(renderList);
  61766. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  61767. this._renderTexture.onAfterRenderObservable.add(afterRender);
  61768. this._scene = scene;
  61769. this._renderList = renderList;
  61770. }
  61771. // private
  61772. PostProcessRenderPass.prototype._incRefCount = function () {
  61773. if (this._refCount === 0) {
  61774. this._scene.customRenderTargets.push(this._renderTexture);
  61775. }
  61776. return ++this._refCount;
  61777. };
  61778. PostProcessRenderPass.prototype._decRefCount = function () {
  61779. this._refCount--;
  61780. if (this._refCount <= 0) {
  61781. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  61782. }
  61783. return this._refCount;
  61784. };
  61785. PostProcessRenderPass.prototype._update = function () {
  61786. this.setRenderList(this._renderList);
  61787. };
  61788. // public
  61789. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  61790. this._renderTexture.renderList = renderList;
  61791. };
  61792. PostProcessRenderPass.prototype.getRenderTexture = function () {
  61793. return this._renderTexture;
  61794. };
  61795. return PostProcessRenderPass;
  61796. }());
  61797. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  61798. })(BABYLON || (BABYLON = {}));
  61799. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  61800. var BABYLON;
  61801. (function (BABYLON) {
  61802. var PostProcessRenderEffect = /** @class */ (function () {
  61803. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  61804. this._name = name;
  61805. this._singleInstance = singleInstance || true;
  61806. this._getPostProcess = getPostProcess;
  61807. this._cameras = {};
  61808. this._indicesForCamera = {};
  61809. this._postProcesses = {};
  61810. this._renderPasses = {};
  61811. this._renderEffectAsPasses = {};
  61812. }
  61813. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  61814. get: function () {
  61815. for (var index in this._postProcesses) {
  61816. if (!this._postProcesses[index].isSupported) {
  61817. return false;
  61818. }
  61819. }
  61820. return true;
  61821. },
  61822. enumerable: true,
  61823. configurable: true
  61824. });
  61825. PostProcessRenderEffect.prototype._update = function () {
  61826. for (var renderPassName in this._renderPasses) {
  61827. this._renderPasses[renderPassName]._update();
  61828. }
  61829. };
  61830. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  61831. this._renderPasses[renderPass._name] = renderPass;
  61832. this._linkParameters();
  61833. };
  61834. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  61835. delete this._renderPasses[renderPass._name];
  61836. this._linkParameters();
  61837. };
  61838. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  61839. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  61840. this._linkParameters();
  61841. };
  61842. PostProcessRenderEffect.prototype.getPass = function (passName) {
  61843. for (var renderPassName in this._renderPasses) {
  61844. if (renderPassName === passName) {
  61845. return this._renderPasses[passName];
  61846. }
  61847. }
  61848. return null;
  61849. };
  61850. PostProcessRenderEffect.prototype.emptyPasses = function () {
  61851. this._renderPasses = {};
  61852. this._linkParameters();
  61853. };
  61854. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  61855. var cameraKey;
  61856. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61857. if (!cams) {
  61858. return;
  61859. }
  61860. for (var i = 0; i < cams.length; i++) {
  61861. var camera = cams[i];
  61862. var cameraName = camera.name;
  61863. if (this._singleInstance) {
  61864. cameraKey = 0;
  61865. }
  61866. else {
  61867. cameraKey = cameraName;
  61868. }
  61869. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  61870. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  61871. if (!this._indicesForCamera[cameraName]) {
  61872. this._indicesForCamera[cameraName] = [];
  61873. }
  61874. this._indicesForCamera[cameraName].push(index);
  61875. if (!this._cameras[cameraName]) {
  61876. this._cameras[cameraName] = camera;
  61877. }
  61878. for (var passName in this._renderPasses) {
  61879. this._renderPasses[passName]._incRefCount();
  61880. }
  61881. }
  61882. this._linkParameters();
  61883. };
  61884. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  61885. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61886. if (!cams) {
  61887. return;
  61888. }
  61889. for (var i = 0; i < cams.length; i++) {
  61890. var camera = cams[i];
  61891. var cameraName = camera.name;
  61892. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61893. if (this._cameras[cameraName]) {
  61894. //this._indicesForCamera.splice(index, 1);
  61895. this._cameras[cameraName] = null;
  61896. }
  61897. for (var passName in this._renderPasses) {
  61898. this._renderPasses[passName]._decRefCount();
  61899. }
  61900. }
  61901. };
  61902. PostProcessRenderEffect.prototype._enable = function (cameras) {
  61903. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61904. if (!cams) {
  61905. return;
  61906. }
  61907. for (var i = 0; i < cams.length; i++) {
  61908. var camera = cams[i];
  61909. var cameraName = camera.name;
  61910. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  61911. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  61912. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  61913. }
  61914. }
  61915. for (var passName in this._renderPasses) {
  61916. this._renderPasses[passName]._incRefCount();
  61917. }
  61918. }
  61919. };
  61920. PostProcessRenderEffect.prototype._disable = function (cameras) {
  61921. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61922. if (!cams) {
  61923. return;
  61924. }
  61925. for (var i = 0; i < cams.length; i++) {
  61926. var camera = cams[i];
  61927. var cameraName = camera.Name;
  61928. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61929. for (var passName in this._renderPasses) {
  61930. this._renderPasses[passName]._decRefCount();
  61931. }
  61932. }
  61933. };
  61934. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  61935. if (this._singleInstance) {
  61936. return this._postProcesses[0];
  61937. }
  61938. else {
  61939. if (!camera) {
  61940. return null;
  61941. }
  61942. return this._postProcesses[camera.name];
  61943. }
  61944. };
  61945. PostProcessRenderEffect.prototype._linkParameters = function () {
  61946. var _this = this;
  61947. for (var index in this._postProcesses) {
  61948. if (this.applyParameters) {
  61949. this.applyParameters(this._postProcesses[index]);
  61950. }
  61951. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  61952. _this._linkTextures(effect);
  61953. });
  61954. }
  61955. };
  61956. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  61957. for (var renderPassName in this._renderPasses) {
  61958. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  61959. }
  61960. for (var renderEffectName in this._renderEffectAsPasses) {
  61961. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  61962. }
  61963. };
  61964. return PostProcessRenderEffect;
  61965. }());
  61966. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  61967. })(BABYLON || (BABYLON = {}));
  61968. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  61969. var BABYLON;
  61970. (function (BABYLON) {
  61971. var PostProcessRenderPipeline = /** @class */ (function () {
  61972. function PostProcessRenderPipeline(engine, name) {
  61973. this._engine = engine;
  61974. this._name = name;
  61975. this._renderEffects = {};
  61976. this._renderEffectsForIsolatedPass = new Array();
  61977. this._cameras = [];
  61978. }
  61979. PostProcessRenderPipeline.prototype.getClassName = function () {
  61980. return "PostProcessRenderPipeline";
  61981. };
  61982. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  61983. get: function () {
  61984. for (var renderEffectName in this._renderEffects) {
  61985. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61986. if (!this._renderEffects[renderEffectName].isSupported) {
  61987. return false;
  61988. }
  61989. }
  61990. }
  61991. return true;
  61992. },
  61993. enumerable: true,
  61994. configurable: true
  61995. });
  61996. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  61997. this._renderEffects[renderEffect._name] = renderEffect;
  61998. };
  61999. // private
  62000. PostProcessRenderPipeline.prototype._rebuild = function () {
  62001. };
  62002. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  62003. var renderEffects = this._renderEffects[renderEffectName];
  62004. if (!renderEffects) {
  62005. return;
  62006. }
  62007. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62008. };
  62009. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  62010. var renderEffects = this._renderEffects[renderEffectName];
  62011. if (!renderEffects) {
  62012. return;
  62013. }
  62014. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  62015. };
  62016. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  62017. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62018. if (!cams) {
  62019. return;
  62020. }
  62021. var indicesToDelete = [];
  62022. var i;
  62023. for (i = 0; i < cams.length; i++) {
  62024. var camera = cams[i];
  62025. var cameraName = camera.name;
  62026. if (this._cameras.indexOf(camera) === -1) {
  62027. this._cameras[cameraName] = camera;
  62028. }
  62029. else if (unique) {
  62030. indicesToDelete.push(i);
  62031. }
  62032. }
  62033. for (i = 0; i < indicesToDelete.length; i++) {
  62034. cameras.splice(indicesToDelete[i], 1);
  62035. }
  62036. for (var renderEffectName in this._renderEffects) {
  62037. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62038. this._renderEffects[renderEffectName]._attachCameras(cams);
  62039. }
  62040. }
  62041. };
  62042. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  62043. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62044. if (!cams) {
  62045. return;
  62046. }
  62047. for (var renderEffectName in this._renderEffects) {
  62048. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62049. this._renderEffects[renderEffectName]._detachCameras(cams);
  62050. }
  62051. }
  62052. for (var i = 0; i < cams.length; i++) {
  62053. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  62054. }
  62055. };
  62056. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  62057. var _this = this;
  62058. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62059. if (!cams) {
  62060. return;
  62061. }
  62062. var pass = null;
  62063. var renderEffectName;
  62064. for (renderEffectName in this._renderEffects) {
  62065. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62066. pass = this._renderEffects[renderEffectName].getPass(passName);
  62067. if (pass != null) {
  62068. break;
  62069. }
  62070. }
  62071. }
  62072. if (pass === null) {
  62073. return;
  62074. }
  62075. for (renderEffectName in this._renderEffects) {
  62076. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62077. this._renderEffects[renderEffectName]._disable(cams);
  62078. }
  62079. }
  62080. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  62081. for (var i = 0; i < cams.length; i++) {
  62082. var camera = cams[i];
  62083. var cameraName = camera.name;
  62084. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  62085. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  62086. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  62087. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  62088. }
  62089. };
  62090. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  62091. var _this = this;
  62092. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  62093. if (!cams) {
  62094. return;
  62095. }
  62096. for (var i = 0; i < cams.length; i++) {
  62097. var camera = cams[i];
  62098. var cameraName = camera.name;
  62099. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  62100. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  62101. }
  62102. for (var renderEffectName in this._renderEffects) {
  62103. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62104. this._renderEffects[renderEffectName]._enable(cams);
  62105. }
  62106. }
  62107. };
  62108. PostProcessRenderPipeline.prototype._update = function () {
  62109. for (var renderEffectName in this._renderEffects) {
  62110. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  62111. this._renderEffects[renderEffectName]._update();
  62112. }
  62113. }
  62114. for (var i = 0; i < this._cameras.length; i++) {
  62115. var cameraName = this._cameras[i].name;
  62116. if (this._renderEffectsForIsolatedPass[cameraName]) {
  62117. this._renderEffectsForIsolatedPass[cameraName]._update();
  62118. }
  62119. }
  62120. };
  62121. PostProcessRenderPipeline.prototype._reset = function () {
  62122. this._renderEffects = {};
  62123. this._renderEffectsForIsolatedPass = new Array();
  62124. };
  62125. PostProcessRenderPipeline.prototype.dispose = function () {
  62126. // Must be implemented by children
  62127. };
  62128. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  62129. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  62130. __decorate([
  62131. BABYLON.serialize()
  62132. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  62133. return PostProcessRenderPipeline;
  62134. }());
  62135. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  62136. })(BABYLON || (BABYLON = {}));
  62137. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  62138. var BABYLON;
  62139. (function (BABYLON) {
  62140. var DepthRenderer = /** @class */ (function () {
  62141. function DepthRenderer(scene, type) {
  62142. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  62143. var _this = this;
  62144. this._scene = scene;
  62145. var engine = scene.getEngine();
  62146. // Render target
  62147. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  62148. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62149. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62150. this._depthMap.refreshRate = 1;
  62151. this._depthMap.renderParticles = false;
  62152. this._depthMap.renderList = null;
  62153. // set default depth value to 1.0 (far away)
  62154. this._depthMap.onClearObservable.add(function (engine) {
  62155. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  62156. });
  62157. // Custom render function
  62158. var renderSubMesh = function (subMesh) {
  62159. var mesh = subMesh.getRenderingMesh();
  62160. var scene = _this._scene;
  62161. var engine = scene.getEngine();
  62162. var material = subMesh.getMaterial();
  62163. if (!material) {
  62164. return;
  62165. }
  62166. // Culling and reverse (right handed system)
  62167. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  62168. // Managing instances
  62169. var batch = mesh._getInstancesRenderList(subMesh._id);
  62170. if (batch.mustReturn) {
  62171. return;
  62172. }
  62173. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62174. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  62175. engine.enableEffect(_this._effect);
  62176. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  62177. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  62178. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  62179. // Alpha test
  62180. if (material && material.needAlphaTesting()) {
  62181. var alphaTexture = material.getAlphaTestTexture();
  62182. if (alphaTexture) {
  62183. _this._effect.setTexture("diffuseSampler", alphaTexture);
  62184. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62185. }
  62186. }
  62187. // Bones
  62188. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62189. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62190. }
  62191. // Draw
  62192. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  62193. }
  62194. };
  62195. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62196. var index;
  62197. if (depthOnlySubMeshes.length) {
  62198. engine.setColorWrite(false);
  62199. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62200. renderSubMesh(depthOnlySubMeshes.data[index]);
  62201. }
  62202. engine.setColorWrite(true);
  62203. }
  62204. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62205. renderSubMesh(opaqueSubMeshes.data[index]);
  62206. }
  62207. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62208. renderSubMesh(alphaTestSubMeshes.data[index]);
  62209. }
  62210. };
  62211. }
  62212. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  62213. var material = subMesh.getMaterial();
  62214. if (material.disableDepthWrite) {
  62215. return false;
  62216. }
  62217. var defines = [];
  62218. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62219. var mesh = subMesh.getMesh();
  62220. // Alpha test
  62221. if (material && material.needAlphaTesting()) {
  62222. defines.push("#define ALPHATEST");
  62223. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62224. attribs.push(BABYLON.VertexBuffer.UVKind);
  62225. defines.push("#define UV1");
  62226. }
  62227. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62228. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62229. defines.push("#define UV2");
  62230. }
  62231. }
  62232. // Bones
  62233. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62234. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62235. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62236. if (mesh.numBoneInfluencers > 4) {
  62237. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62238. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62239. }
  62240. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62241. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  62242. }
  62243. else {
  62244. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62245. }
  62246. // Instances
  62247. if (useInstances) {
  62248. defines.push("#define INSTANCES");
  62249. attribs.push("world0");
  62250. attribs.push("world1");
  62251. attribs.push("world2");
  62252. attribs.push("world3");
  62253. }
  62254. // Get correct effect
  62255. var join = defines.join("\n");
  62256. if (this._cachedDefines !== join) {
  62257. this._cachedDefines = join;
  62258. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  62259. }
  62260. return this._effect.isReady();
  62261. };
  62262. DepthRenderer.prototype.getDepthMap = function () {
  62263. return this._depthMap;
  62264. };
  62265. // Methods
  62266. DepthRenderer.prototype.dispose = function () {
  62267. this._depthMap.dispose();
  62268. };
  62269. return DepthRenderer;
  62270. }());
  62271. BABYLON.DepthRenderer = DepthRenderer;
  62272. })(BABYLON || (BABYLON = {}));
  62273. //# sourceMappingURL=babylon.depthRenderer.js.map
  62274. var BABYLON;
  62275. (function (BABYLON) {
  62276. var SSAORenderingPipeline = /** @class */ (function (_super) {
  62277. __extends(SSAORenderingPipeline, _super);
  62278. /**
  62279. * @constructor
  62280. * @param {string} name - The rendering pipeline name
  62281. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62282. * @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 }
  62283. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62284. */
  62285. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  62286. var _this = _super.call(this, scene.getEngine(), name) || this;
  62287. // Members
  62288. /**
  62289. * The PassPostProcess id in the pipeline that contains the original scene color
  62290. * @type {string}
  62291. */
  62292. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  62293. /**
  62294. * The SSAO PostProcess id in the pipeline
  62295. * @type {string}
  62296. */
  62297. _this.SSAORenderEffect = "SSAORenderEffect";
  62298. /**
  62299. * The horizontal blur PostProcess id in the pipeline
  62300. * @type {string}
  62301. */
  62302. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  62303. /**
  62304. * The vertical blur PostProcess id in the pipeline
  62305. * @type {string}
  62306. */
  62307. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  62308. /**
  62309. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  62310. * @type {string}
  62311. */
  62312. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  62313. /**
  62314. * The output strength of the SSAO post-process. Default value is 1.0.
  62315. * @type {number}
  62316. */
  62317. _this.totalStrength = 1.0;
  62318. /**
  62319. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  62320. * @type {number}
  62321. */
  62322. _this.radius = 0.0001;
  62323. /**
  62324. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  62325. * Must not be equal to fallOff and superior to fallOff.
  62326. * Default value is 0.975
  62327. * @type {number}
  62328. */
  62329. _this.area = 0.0075;
  62330. /**
  62331. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  62332. * Must not be equal to area and inferior to area.
  62333. * Default value is 0.0
  62334. * @type {number}
  62335. */
  62336. _this.fallOff = 0.000001;
  62337. /**
  62338. * The base color of the SSAO post-process
  62339. * The final result is "base + ssao" between [0, 1]
  62340. * @type {number}
  62341. */
  62342. _this.base = 0.5;
  62343. _this._firstUpdate = true;
  62344. _this._scene = scene;
  62345. // Set up assets
  62346. _this._createRandomTexture();
  62347. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62348. var ssaoRatio = ratio.ssaoRatio || ratio;
  62349. var combineRatio = ratio.combineRatio || ratio;
  62350. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62351. _this._createSSAOPostProcess(ssaoRatio);
  62352. _this._createBlurPostProcess(ssaoRatio);
  62353. _this._createSSAOCombinePostProcess(combineRatio);
  62354. // Set up pipeline
  62355. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62356. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62357. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62358. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62359. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62360. // Finish
  62361. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62362. if (cameras)
  62363. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62364. return _this;
  62365. }
  62366. // Public Methods
  62367. /**
  62368. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  62369. */
  62370. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62371. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62372. for (var i = 0; i < this._scene.cameras.length; i++) {
  62373. var camera = this._scene.cameras[i];
  62374. this._originalColorPostProcess.dispose(camera);
  62375. this._ssaoPostProcess.dispose(camera);
  62376. this._blurHPostProcess.dispose(camera);
  62377. this._blurVPostProcess.dispose(camera);
  62378. this._ssaoCombinePostProcess.dispose(camera);
  62379. }
  62380. this._randomTexture.dispose();
  62381. if (disableDepthRender)
  62382. this._scene.disableDepthRenderer();
  62383. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62384. _super.prototype.dispose.call(this);
  62385. };
  62386. // Private Methods
  62387. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  62388. var _this = this;
  62389. var size = 16;
  62390. 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);
  62391. 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);
  62392. this._blurHPostProcess.onActivateObservable.add(function () {
  62393. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  62394. _this._blurHPostProcess.kernel = size * dw;
  62395. });
  62396. this._blurVPostProcess.onActivateObservable.add(function () {
  62397. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  62398. _this._blurVPostProcess.kernel = size * dw;
  62399. });
  62400. };
  62401. SSAORenderingPipeline.prototype._rebuild = function () {
  62402. this._firstUpdate = true;
  62403. _super.prototype._rebuild.call(this);
  62404. };
  62405. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  62406. var _this = this;
  62407. var numSamples = 16;
  62408. var sampleSphere = [
  62409. 0.5381, 0.1856, -0.4319,
  62410. 0.1379, 0.2486, 0.4430,
  62411. 0.3371, 0.5679, -0.0057,
  62412. -0.6999, -0.0451, -0.0019,
  62413. 0.0689, -0.1598, -0.8547,
  62414. 0.0560, 0.0069, -0.1843,
  62415. -0.0146, 0.1402, 0.0762,
  62416. 0.0100, -0.1924, -0.0344,
  62417. -0.3577, -0.5301, -0.4358,
  62418. -0.3169, 0.1063, 0.0158,
  62419. 0.0103, -0.5869, 0.0046,
  62420. -0.0897, -0.4940, 0.3287,
  62421. 0.7119, -0.0154, -0.0918,
  62422. -0.0533, 0.0596, -0.5411,
  62423. 0.0352, -0.0631, 0.5460,
  62424. -0.4776, 0.2847, -0.0271
  62425. ];
  62426. var samplesFactor = 1.0 / numSamples;
  62427. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  62428. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  62429. "area", "fallOff", "base", "range", "viewport"
  62430. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  62431. this._ssaoPostProcess.onApply = function (effect) {
  62432. if (_this._firstUpdate) {
  62433. effect.setArray3("sampleSphere", sampleSphere);
  62434. effect.setFloat("samplesFactor", samplesFactor);
  62435. effect.setFloat("randTextureTiles", 4.0);
  62436. }
  62437. effect.setFloat("totalStrength", _this.totalStrength);
  62438. effect.setFloat("radius", _this.radius);
  62439. effect.setFloat("area", _this.area);
  62440. effect.setFloat("fallOff", _this.fallOff);
  62441. effect.setFloat("base", _this.base);
  62442. effect.setTexture("textureSampler", _this._depthTexture);
  62443. effect.setTexture("randomSampler", _this._randomTexture);
  62444. };
  62445. };
  62446. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  62447. var _this = this;
  62448. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62449. this._ssaoCombinePostProcess.onApply = function (effect) {
  62450. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  62451. };
  62452. };
  62453. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  62454. var size = 512;
  62455. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62456. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62457. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62458. var context = this._randomTexture.getContext();
  62459. var rand = function (min, max) {
  62460. return Math.random() * (max - min) + min;
  62461. };
  62462. var randVector = BABYLON.Vector3.Zero();
  62463. for (var x = 0; x < size; x++) {
  62464. for (var y = 0; y < size; y++) {
  62465. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  62466. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  62467. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  62468. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62469. context.fillRect(x, y, 1, 1);
  62470. }
  62471. }
  62472. this._randomTexture.update(false);
  62473. };
  62474. __decorate([
  62475. BABYLON.serialize()
  62476. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  62477. __decorate([
  62478. BABYLON.serialize()
  62479. ], SSAORenderingPipeline.prototype, "radius", void 0);
  62480. __decorate([
  62481. BABYLON.serialize()
  62482. ], SSAORenderingPipeline.prototype, "area", void 0);
  62483. __decorate([
  62484. BABYLON.serialize()
  62485. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  62486. __decorate([
  62487. BABYLON.serialize()
  62488. ], SSAORenderingPipeline.prototype, "base", void 0);
  62489. return SSAORenderingPipeline;
  62490. }(BABYLON.PostProcessRenderPipeline));
  62491. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  62492. })(BABYLON || (BABYLON = {}));
  62493. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  62494. var BABYLON;
  62495. (function (BABYLON) {
  62496. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  62497. __extends(SSAO2RenderingPipeline, _super);
  62498. /**
  62499. * @constructor
  62500. * @param {string} name - The rendering pipeline name
  62501. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62502. * @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 }
  62503. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62504. */
  62505. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  62506. var _this = _super.call(this, scene.getEngine(), name) || this;
  62507. // Members
  62508. /**
  62509. * The PassPostProcess id in the pipeline that contains the original scene color
  62510. * @type {string}
  62511. */
  62512. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  62513. /**
  62514. * The SSAO PostProcess id in the pipeline
  62515. * @type {string}
  62516. */
  62517. _this.SSAORenderEffect = "SSAORenderEffect";
  62518. /**
  62519. * The horizontal blur PostProcess id in the pipeline
  62520. * @type {string}
  62521. */
  62522. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  62523. /**
  62524. * The vertical blur PostProcess id in the pipeline
  62525. * @type {string}
  62526. */
  62527. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  62528. /**
  62529. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  62530. * @type {string}
  62531. */
  62532. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  62533. /**
  62534. * The output strength of the SSAO post-process. Default value is 1.0.
  62535. * @type {number}
  62536. */
  62537. _this.totalStrength = 1.0;
  62538. /**
  62539. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  62540. * @type {number}
  62541. */
  62542. _this.maxZ = 100.0;
  62543. /**
  62544. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  62545. * @type {number}
  62546. */
  62547. _this.minZAspect = 0.2;
  62548. /**
  62549. * Number of samples used for the SSAO calculations. Default value is 8
  62550. * @type {number}
  62551. */
  62552. _this._samples = 8;
  62553. /**
  62554. * Are we using bilateral blur ?
  62555. * @type {boolean}
  62556. */
  62557. _this._expensiveBlur = true;
  62558. /**
  62559. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  62560. * @type {number}
  62561. */
  62562. _this.radius = 2.0;
  62563. /**
  62564. * The base color of the SSAO post-process
  62565. * The final result is "base + ssao" between [0, 1]
  62566. * @type {number}
  62567. */
  62568. _this.base = 0.1;
  62569. _this._firstUpdate = true;
  62570. _this._scene = scene;
  62571. if (!_this.isSupported) {
  62572. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  62573. return _this;
  62574. }
  62575. var ssaoRatio = ratio.ssaoRatio || ratio;
  62576. var blurRatio = ratio.blurRatio || ratio;
  62577. // Set up assets
  62578. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  62579. _this._createRandomTexture();
  62580. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  62581. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  62582. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62583. _this._createSSAOPostProcess(1.0);
  62584. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  62585. _this._createSSAOCombinePostProcess(blurRatio);
  62586. // Set up pipeline
  62587. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62588. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62589. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62590. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62591. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62592. // Finish
  62593. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62594. if (cameras)
  62595. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62596. return _this;
  62597. }
  62598. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  62599. get: function () {
  62600. return this._samples;
  62601. },
  62602. set: function (n) {
  62603. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  62604. this._samples = n;
  62605. this._sampleSphere = this._generateHemisphere();
  62606. this._firstUpdate = true;
  62607. },
  62608. enumerable: true,
  62609. configurable: true
  62610. });
  62611. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  62612. get: function () {
  62613. return this._expensiveBlur;
  62614. },
  62615. set: function (b) {
  62616. 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"]);
  62617. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  62618. this._expensiveBlur = b;
  62619. this._firstUpdate = true;
  62620. },
  62621. enumerable: true,
  62622. configurable: true
  62623. });
  62624. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  62625. /**
  62626. * Support test.
  62627. * @type {boolean}
  62628. */
  62629. get: function () {
  62630. var engine = BABYLON.Engine.LastCreatedEngine;
  62631. if (!engine) {
  62632. return false;
  62633. }
  62634. return engine.getCaps().drawBuffersExtension;
  62635. },
  62636. enumerable: true,
  62637. configurable: true
  62638. });
  62639. // Public Methods
  62640. /**
  62641. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  62642. */
  62643. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  62644. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  62645. for (var i = 0; i < this._scene.cameras.length; i++) {
  62646. var camera = this._scene.cameras[i];
  62647. this._originalColorPostProcess.dispose(camera);
  62648. this._ssaoPostProcess.dispose(camera);
  62649. this._blurHPostProcess.dispose(camera);
  62650. this._blurVPostProcess.dispose(camera);
  62651. this._ssaoCombinePostProcess.dispose(camera);
  62652. }
  62653. this._randomTexture.dispose();
  62654. if (disableGeometryBufferRenderer)
  62655. this._scene.disableGeometryBufferRenderer();
  62656. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62657. _super.prototype.dispose.call(this);
  62658. };
  62659. // Private Methods
  62660. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  62661. var _this = this;
  62662. this._samplerOffsets = [];
  62663. var expensive = this.expensiveBlur;
  62664. for (var i = -8; i < 8; i++) {
  62665. this._samplerOffsets.push(i * 2 + 0.5);
  62666. }
  62667. 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");
  62668. this._blurHPostProcess.onApply = function (effect) {
  62669. if (!_this._scene.activeCamera) {
  62670. return;
  62671. }
  62672. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  62673. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62674. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62675. effect.setFloat("radius", _this.radius);
  62676. effect.setTexture("depthSampler", _this._depthTexture);
  62677. if (_this._firstUpdate) {
  62678. effect.setArray("samplerOffsets", _this._samplerOffsets);
  62679. }
  62680. };
  62681. 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");
  62682. this._blurVPostProcess.onApply = function (effect) {
  62683. if (!_this._scene.activeCamera) {
  62684. return;
  62685. }
  62686. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  62687. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62688. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62689. effect.setFloat("radius", _this.radius);
  62690. effect.setTexture("depthSampler", _this._depthTexture);
  62691. if (_this._firstUpdate) {
  62692. effect.setArray("samplerOffsets", _this._samplerOffsets);
  62693. _this._firstUpdate = false;
  62694. }
  62695. };
  62696. };
  62697. SSAO2RenderingPipeline.prototype._rebuild = function () {
  62698. this._firstUpdate = true;
  62699. _super.prototype._rebuild.call(this);
  62700. };
  62701. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  62702. var numSamples = this.samples;
  62703. var result = [];
  62704. var vector, scale;
  62705. var rand = function (min, max) {
  62706. return Math.random() * (max - min) + min;
  62707. };
  62708. var i = 0;
  62709. while (i < numSamples) {
  62710. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  62711. vector.normalize();
  62712. scale = i / numSamples;
  62713. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  62714. vector.scaleInPlace(scale);
  62715. result.push(vector.x, vector.y, vector.z);
  62716. i++;
  62717. }
  62718. return result;
  62719. };
  62720. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  62721. var _this = this;
  62722. var numSamples = this.samples;
  62723. this._sampleSphere = this._generateHemisphere();
  62724. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  62725. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  62726. "base", "range", "projection", "near", "far", "texelSize",
  62727. "xViewport", "yViewport", "maxZ", "minZAspect"
  62728. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  62729. this._ssaoPostProcess.onApply = function (effect) {
  62730. if (_this._firstUpdate) {
  62731. effect.setArray3("sampleSphere", _this._sampleSphere);
  62732. effect.setFloat("randTextureTiles", 4.0);
  62733. }
  62734. if (!_this._scene.activeCamera) {
  62735. return;
  62736. }
  62737. effect.setFloat("samplesFactor", 1 / _this.samples);
  62738. effect.setFloat("totalStrength", _this.totalStrength);
  62739. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  62740. effect.setFloat("radius", _this.radius);
  62741. effect.setFloat("maxZ", _this.maxZ);
  62742. effect.setFloat("minZAspect", _this.minZAspect);
  62743. effect.setFloat("base", _this.base);
  62744. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62745. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62746. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  62747. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  62748. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  62749. effect.setTexture("textureSampler", _this._depthTexture);
  62750. effect.setTexture("normalSampler", _this._normalTexture);
  62751. effect.setTexture("randomSampler", _this._randomTexture);
  62752. };
  62753. };
  62754. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  62755. var _this = this;
  62756. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62757. this._ssaoCombinePostProcess.onApply = function (effect) {
  62758. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  62759. };
  62760. };
  62761. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  62762. var size = 512;
  62763. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62764. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62765. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62766. var context = this._randomTexture.getContext();
  62767. var rand = function (min, max) {
  62768. return Math.random() * (max - min) + min;
  62769. };
  62770. var randVector = BABYLON.Vector3.Zero();
  62771. for (var x = 0; x < size; x++) {
  62772. for (var y = 0; y < size; y++) {
  62773. randVector.x = rand(0.0, 1.0);
  62774. randVector.y = rand(0.0, 1.0);
  62775. randVector.z = 0.0;
  62776. randVector.normalize();
  62777. randVector.scaleInPlace(255);
  62778. randVector.x = Math.floor(randVector.x);
  62779. randVector.y = Math.floor(randVector.y);
  62780. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62781. context.fillRect(x, y, 1, 1);
  62782. }
  62783. }
  62784. this._randomTexture.update(false);
  62785. };
  62786. __decorate([
  62787. BABYLON.serialize()
  62788. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  62789. __decorate([
  62790. BABYLON.serialize()
  62791. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  62792. __decorate([
  62793. BABYLON.serialize()
  62794. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  62795. __decorate([
  62796. BABYLON.serialize("samples")
  62797. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  62798. __decorate([
  62799. BABYLON.serialize("expensiveBlur")
  62800. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  62801. __decorate([
  62802. BABYLON.serialize()
  62803. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  62804. __decorate([
  62805. BABYLON.serialize()
  62806. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  62807. return SSAO2RenderingPipeline;
  62808. }(BABYLON.PostProcessRenderPipeline));
  62809. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  62810. })(BABYLON || (BABYLON = {}));
  62811. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  62812. // BABYLON.JS Chromatic Aberration GLSL Shader
  62813. // Author: Olivier Guyot
  62814. // Separates very slightly R, G and B colors on the edges of the screen
  62815. // Inspired by Francois Tarlier & Martins Upitis
  62816. var BABYLON;
  62817. (function (BABYLON) {
  62818. var LensRenderingPipeline = /** @class */ (function (_super) {
  62819. __extends(LensRenderingPipeline, _super);
  62820. /**
  62821. * @constructor
  62822. *
  62823. * Effect parameters are as follow:
  62824. * {
  62825. * chromatic_aberration: number; // from 0 to x (1 for realism)
  62826. * edge_blur: number; // from 0 to x (1 for realism)
  62827. * distortion: number; // from 0 to x (1 for realism)
  62828. * grain_amount: number; // from 0 to 1
  62829. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  62830. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  62831. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  62832. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  62833. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  62834. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  62835. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  62836. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  62837. * }
  62838. * Note: if an effect parameter is unset, effect is disabled
  62839. *
  62840. * @param {string} name - The rendering pipeline name
  62841. * @param {object} parameters - An object containing all parameters (see above)
  62842. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62843. * @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)
  62844. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62845. */
  62846. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  62847. if (ratio === void 0) { ratio = 1.0; }
  62848. var _this = _super.call(this, scene.getEngine(), name) || this;
  62849. // Lens effects can be of the following:
  62850. // - chromatic aberration (slight shift of RGB colors)
  62851. // - blur on the edge of the lens
  62852. // - lens distortion
  62853. // - depth-of-field blur & highlights enhancing
  62854. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  62855. // - grain effect (noise or custom texture)
  62856. // Two additional texture samplers are needed:
  62857. // - depth map (for depth-of-field)
  62858. // - grain texture
  62859. /**
  62860. * The chromatic aberration PostProcess id in the pipeline
  62861. * @type {string}
  62862. */
  62863. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  62864. /**
  62865. * The highlights enhancing PostProcess id in the pipeline
  62866. * @type {string}
  62867. */
  62868. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  62869. /**
  62870. * The depth-of-field PostProcess id in the pipeline
  62871. * @type {string}
  62872. */
  62873. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  62874. _this._scene = scene;
  62875. // Fetch texture samplers
  62876. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62877. if (parameters.grain_texture) {
  62878. _this._grainTexture = parameters.grain_texture;
  62879. }
  62880. else {
  62881. _this._createGrainTexture();
  62882. }
  62883. // save parameters
  62884. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  62885. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  62886. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  62887. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  62888. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  62889. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  62890. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  62891. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  62892. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  62893. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  62894. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  62895. // Create effects
  62896. _this._createChromaticAberrationPostProcess(ratio);
  62897. _this._createHighlightsPostProcess(ratio);
  62898. _this._createDepthOfFieldPostProcess(ratio / 4);
  62899. // Set up pipeline
  62900. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  62901. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  62902. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  62903. if (_this._highlightsGain === -1) {
  62904. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  62905. }
  62906. // Finish
  62907. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62908. if (cameras) {
  62909. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62910. }
  62911. return _this;
  62912. }
  62913. // public methods (self explanatory)
  62914. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  62915. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  62916. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  62917. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  62918. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  62919. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  62920. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  62921. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  62922. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  62923. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  62924. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  62925. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  62926. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  62927. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  62928. };
  62929. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  62930. this._highlightsPostProcess.updateEffect();
  62931. };
  62932. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  62933. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  62934. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  62935. this._highlightsGain = amount;
  62936. };
  62937. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  62938. if (this._highlightsGain === -1) {
  62939. this._highlightsGain = 1.0;
  62940. }
  62941. this._highlightsThreshold = amount;
  62942. };
  62943. LensRenderingPipeline.prototype.disableHighlights = function () {
  62944. this._highlightsGain = -1;
  62945. };
  62946. /**
  62947. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  62948. */
  62949. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62950. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62951. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62952. this._chromaticAberrationPostProcess = null;
  62953. this._highlightsPostProcess = null;
  62954. this._depthOfFieldPostProcess = null;
  62955. this._grainTexture.dispose();
  62956. if (disableDepthRender)
  62957. this._scene.disableDepthRenderer();
  62958. };
  62959. // colors shifting and distortion
  62960. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  62961. var _this = this;
  62962. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  62963. [], // samplers
  62964. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62965. this._chromaticAberrationPostProcess.onApply = function (effect) {
  62966. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  62967. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62968. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62969. };
  62970. };
  62971. // highlights enhancing
  62972. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  62973. var _this = this;
  62974. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  62975. [], // samplers
  62976. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  62977. this._highlightsPostProcess.onApply = function (effect) {
  62978. effect.setFloat('gain', _this._highlightsGain);
  62979. effect.setFloat('threshold', _this._highlightsThreshold);
  62980. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  62981. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62982. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62983. };
  62984. };
  62985. // colors shifting and distortion
  62986. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  62987. var _this = this;
  62988. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  62989. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  62990. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  62991. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62992. this._depthOfFieldPostProcess.onApply = function (effect) {
  62993. effect.setTexture("depthSampler", _this._depthTexture);
  62994. effect.setTexture("grainSampler", _this._grainTexture);
  62995. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  62996. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  62997. effect.setFloat('grain_amount', _this._grainAmount);
  62998. effect.setBool('blur_noise', _this._blurNoise);
  62999. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  63000. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  63001. effect.setFloat('distortion', _this._distortion);
  63002. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  63003. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  63004. effect.setFloat('aperture', _this._dofAperture);
  63005. effect.setFloat('darken', _this._dofDarken);
  63006. effect.setFloat('edge_blur', _this._edgeBlur);
  63007. effect.setBool('highlights', (_this._highlightsGain !== -1));
  63008. if (_this._scene.activeCamera) {
  63009. effect.setFloat('near', _this._scene.activeCamera.minZ);
  63010. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  63011. }
  63012. };
  63013. };
  63014. // creates a black and white random noise texture, 512x512
  63015. LensRenderingPipeline.prototype._createGrainTexture = function () {
  63016. var size = 512;
  63017. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63018. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63019. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63020. var context = this._grainTexture.getContext();
  63021. var rand = function (min, max) {
  63022. return Math.random() * (max - min) + min;
  63023. };
  63024. var value;
  63025. for (var x = 0; x < size; x++) {
  63026. for (var y = 0; y < size; y++) {
  63027. value = Math.floor(rand(0.42, 0.58) * 255);
  63028. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  63029. context.fillRect(x, y, 1, 1);
  63030. }
  63031. }
  63032. this._grainTexture.update(false);
  63033. };
  63034. return LensRenderingPipeline;
  63035. }(BABYLON.PostProcessRenderPipeline));
  63036. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  63037. })(BABYLON || (BABYLON = {}));
  63038. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  63039. var BABYLON;
  63040. (function (BABYLON) {
  63041. var StandardRenderingPipeline = /** @class */ (function (_super) {
  63042. __extends(StandardRenderingPipeline, _super);
  63043. /**
  63044. * @constructor
  63045. * @param {string} name - The rendering pipeline name
  63046. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63047. * @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)
  63048. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  63049. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63050. */
  63051. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  63052. if (originalPostProcess === void 0) { originalPostProcess = null; }
  63053. var _this = _super.call(this, scene.getEngine(), name) || this;
  63054. _this.downSampleX4PostProcess = null;
  63055. _this.brightPassPostProcess = null;
  63056. _this.blurHPostProcesses = [];
  63057. _this.blurVPostProcesses = [];
  63058. _this.textureAdderPostProcess = null;
  63059. _this.volumetricLightPostProcess = null;
  63060. _this.volumetricLightSmoothXPostProcess = null;
  63061. _this.volumetricLightSmoothYPostProcess = null;
  63062. _this.volumetricLightMergePostProces = null;
  63063. _this.volumetricLightFinalPostProcess = null;
  63064. _this.luminancePostProcess = null;
  63065. _this.luminanceDownSamplePostProcesses = [];
  63066. _this.hdrPostProcess = null;
  63067. _this.textureAdderFinalPostProcess = null;
  63068. _this.lensFlareFinalPostProcess = null;
  63069. _this.hdrFinalPostProcess = null;
  63070. _this.lensFlarePostProcess = null;
  63071. _this.lensFlareComposePostProcess = null;
  63072. _this.motionBlurPostProcess = null;
  63073. _this.depthOfFieldPostProcess = null;
  63074. // Values
  63075. _this.brightThreshold = 1.0;
  63076. _this.blurWidth = 512.0;
  63077. _this.horizontalBlur = false;
  63078. _this.exposure = 1.0;
  63079. _this.lensTexture = null;
  63080. _this.volumetricLightCoefficient = 0.2;
  63081. _this.volumetricLightPower = 4.0;
  63082. _this.volumetricLightBlurScale = 64.0;
  63083. _this.sourceLight = null;
  63084. _this.hdrMinimumLuminance = 1.0;
  63085. _this.hdrDecreaseRate = 0.5;
  63086. _this.hdrIncreaseRate = 0.5;
  63087. _this.lensColorTexture = null;
  63088. _this.lensFlareStrength = 20.0;
  63089. _this.lensFlareGhostDispersal = 1.4;
  63090. _this.lensFlareHaloWidth = 0.7;
  63091. _this.lensFlareDistortionStrength = 16.0;
  63092. _this.lensStarTexture = null;
  63093. _this.lensFlareDirtTexture = null;
  63094. _this.depthOfFieldDistance = 10.0;
  63095. _this.depthOfFieldBlurWidth = 64.0;
  63096. _this.motionStrength = 1.0;
  63097. // IAnimatable
  63098. _this.animations = [];
  63099. _this._currentDepthOfFieldSource = null;
  63100. _this._hdrCurrentLuminance = 1.0;
  63101. // Getters and setters
  63102. _this._bloomEnabled = true;
  63103. _this._depthOfFieldEnabled = false;
  63104. _this._vlsEnabled = false;
  63105. _this._lensFlareEnabled = false;
  63106. _this._hdrEnabled = false;
  63107. _this._motionBlurEnabled = false;
  63108. _this._motionBlurSamples = 64.0;
  63109. _this._volumetricLightStepsCount = 50.0;
  63110. _this._cameras = cameras || [];
  63111. // Initialize
  63112. _this._scene = scene;
  63113. _this._basePostProcess = originalPostProcess;
  63114. _this._ratio = ratio;
  63115. // Misc
  63116. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63117. // Finish
  63118. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63119. _this._buildPipeline();
  63120. return _this;
  63121. }
  63122. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  63123. get: function () {
  63124. return this._bloomEnabled;
  63125. },
  63126. set: function (enabled) {
  63127. if (this._bloomEnabled === enabled) {
  63128. return;
  63129. }
  63130. this._bloomEnabled = enabled;
  63131. this._buildPipeline();
  63132. },
  63133. enumerable: true,
  63134. configurable: true
  63135. });
  63136. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  63137. get: function () {
  63138. return this._depthOfFieldEnabled;
  63139. },
  63140. set: function (enabled) {
  63141. if (this._depthOfFieldEnabled === enabled) {
  63142. return;
  63143. }
  63144. this._depthOfFieldEnabled = enabled;
  63145. this._buildPipeline();
  63146. },
  63147. enumerable: true,
  63148. configurable: true
  63149. });
  63150. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  63151. get: function () {
  63152. return this._lensFlareEnabled;
  63153. },
  63154. set: function (enabled) {
  63155. if (this._lensFlareEnabled === enabled) {
  63156. return;
  63157. }
  63158. this._lensFlareEnabled = enabled;
  63159. this._buildPipeline();
  63160. },
  63161. enumerable: true,
  63162. configurable: true
  63163. });
  63164. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  63165. get: function () {
  63166. return this._hdrEnabled;
  63167. },
  63168. set: function (enabled) {
  63169. if (this._hdrEnabled === enabled) {
  63170. return;
  63171. }
  63172. this._hdrEnabled = enabled;
  63173. this._buildPipeline();
  63174. },
  63175. enumerable: true,
  63176. configurable: true
  63177. });
  63178. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  63179. get: function () {
  63180. return this._vlsEnabled;
  63181. },
  63182. set: function (enabled) {
  63183. if (this._vlsEnabled === enabled) {
  63184. return;
  63185. }
  63186. if (enabled) {
  63187. var geometry = this._scene.enableGeometryBufferRenderer();
  63188. if (!geometry) {
  63189. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  63190. return;
  63191. }
  63192. }
  63193. this._vlsEnabled = enabled;
  63194. this._buildPipeline();
  63195. },
  63196. enumerable: true,
  63197. configurable: true
  63198. });
  63199. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  63200. get: function () {
  63201. return this._motionBlurEnabled;
  63202. },
  63203. set: function (enabled) {
  63204. if (this._motionBlurEnabled === enabled) {
  63205. return;
  63206. }
  63207. this._motionBlurEnabled = enabled;
  63208. this._buildPipeline();
  63209. },
  63210. enumerable: true,
  63211. configurable: true
  63212. });
  63213. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  63214. get: function () {
  63215. return this._volumetricLightStepsCount;
  63216. },
  63217. set: function (count) {
  63218. if (this.volumetricLightPostProcess) {
  63219. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  63220. }
  63221. this._volumetricLightStepsCount = count;
  63222. },
  63223. enumerable: true,
  63224. configurable: true
  63225. });
  63226. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  63227. get: function () {
  63228. return this._motionBlurSamples;
  63229. },
  63230. set: function (samples) {
  63231. if (this.motionBlurPostProcess) {
  63232. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  63233. }
  63234. this._motionBlurSamples = samples;
  63235. },
  63236. enumerable: true,
  63237. configurable: true
  63238. });
  63239. StandardRenderingPipeline.prototype._buildPipeline = function () {
  63240. var _this = this;
  63241. var ratio = this._ratio;
  63242. var scene = this._scene;
  63243. this._disposePostProcesses();
  63244. this._reset();
  63245. // Create pass post-process
  63246. if (!this._basePostProcess) {
  63247. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  63248. this.originalPostProcess.onApply = function (effect) {
  63249. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  63250. };
  63251. }
  63252. else {
  63253. this.originalPostProcess = this._basePostProcess;
  63254. }
  63255. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  63256. this._currentDepthOfFieldSource = this.originalPostProcess;
  63257. if (this._vlsEnabled) {
  63258. // Create volumetric light
  63259. this._createVolumetricLightPostProcess(scene, ratio);
  63260. // Create volumetric light final post-process
  63261. 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);
  63262. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  63263. }
  63264. if (this._bloomEnabled) {
  63265. // Create down sample X4 post-process
  63266. this._createDownSampleX4PostProcess(scene, ratio / 2);
  63267. // Create bright pass post-process
  63268. this._createBrightPassPostProcess(scene, ratio / 2);
  63269. // Create gaussian blur post-processes (down sampling blurs)
  63270. this._createBlurPostProcesses(scene, ratio / 4, 1);
  63271. // Create texture adder post-process
  63272. this._createTextureAdderPostProcess(scene, ratio);
  63273. // Create depth-of-field source post-process
  63274. 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);
  63275. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  63276. }
  63277. if (this._lensFlareEnabled) {
  63278. // Create lens flare post-process
  63279. this._createLensFlarePostProcess(scene, ratio);
  63280. // Create depth-of-field source post-process post lens-flare and disable it now
  63281. 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);
  63282. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  63283. }
  63284. if (this._hdrEnabled) {
  63285. // Create luminance
  63286. this._createLuminancePostProcesses(scene, this._floatTextureType);
  63287. // Create HDR
  63288. this._createHdrPostProcess(scene, ratio);
  63289. // Create depth-of-field source post-process post hdr and disable it now
  63290. 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);
  63291. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  63292. }
  63293. if (this._depthOfFieldEnabled) {
  63294. // Create gaussian blur used by depth-of-field
  63295. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  63296. // Create depth-of-field post-process
  63297. this._createDepthOfFieldPostProcess(scene, ratio);
  63298. }
  63299. if (this._motionBlurEnabled) {
  63300. // Create motion blur post-process
  63301. this._createMotionBlurPostProcess(scene, ratio);
  63302. }
  63303. if (this._cameras !== null) {
  63304. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  63305. }
  63306. };
  63307. // Down Sample X4 Post-Processs
  63308. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  63309. var _this = this;
  63310. var downSampleX4Offsets = new Array(32);
  63311. 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);
  63312. this.downSampleX4PostProcess.onApply = function (effect) {
  63313. var id = 0;
  63314. var width = _this.downSampleX4PostProcess.width;
  63315. var height = _this.downSampleX4PostProcess.height;
  63316. for (var i = -2; i < 2; i++) {
  63317. for (var j = -2; j < 2; j++) {
  63318. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  63319. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  63320. id += 2;
  63321. }
  63322. }
  63323. effect.setArray2("dsOffsets", downSampleX4Offsets);
  63324. };
  63325. // Add to pipeline
  63326. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  63327. };
  63328. // Brightpass Post-Process
  63329. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  63330. var _this = this;
  63331. var brightOffsets = new Array(8);
  63332. 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);
  63333. this.brightPassPostProcess.onApply = function (effect) {
  63334. var sU = (1.0 / _this.brightPassPostProcess.width);
  63335. var sV = (1.0 / _this.brightPassPostProcess.height);
  63336. brightOffsets[0] = -0.5 * sU;
  63337. brightOffsets[1] = 0.5 * sV;
  63338. brightOffsets[2] = 0.5 * sU;
  63339. brightOffsets[3] = 0.5 * sV;
  63340. brightOffsets[4] = -0.5 * sU;
  63341. brightOffsets[5] = -0.5 * sV;
  63342. brightOffsets[6] = 0.5 * sU;
  63343. brightOffsets[7] = -0.5 * sV;
  63344. effect.setArray2("dsOffsets", brightOffsets);
  63345. effect.setFloat("brightThreshold", _this.brightThreshold);
  63346. };
  63347. // Add to pipeline
  63348. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  63349. };
  63350. // Create blur H&V post-processes
  63351. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  63352. var _this = this;
  63353. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  63354. var engine = scene.getEngine();
  63355. 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);
  63356. 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);
  63357. blurX.onActivateObservable.add(function () {
  63358. var dw = blurX.width / engine.getRenderWidth();
  63359. blurX.kernel = _this[blurWidthKey] * dw;
  63360. });
  63361. blurY.onActivateObservable.add(function () {
  63362. var dw = blurY.height / engine.getRenderHeight();
  63363. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  63364. });
  63365. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  63366. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  63367. this.blurHPostProcesses.push(blurX);
  63368. this.blurVPostProcesses.push(blurY);
  63369. };
  63370. // Create texture adder post-process
  63371. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  63372. var _this = this;
  63373. 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);
  63374. this.textureAdderPostProcess.onApply = function (effect) {
  63375. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  63376. effect.setTexture("lensSampler", _this.lensTexture);
  63377. effect.setFloat("exposure", _this.exposure);
  63378. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  63379. };
  63380. // Add to pipeline
  63381. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  63382. };
  63383. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  63384. var _this = this;
  63385. var geometryRenderer = scene.enableGeometryBufferRenderer();
  63386. geometryRenderer.enablePosition = true;
  63387. var geometry = geometryRenderer.getGBuffer();
  63388. // Base post-process
  63389. 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));
  63390. var depthValues = BABYLON.Vector2.Zero();
  63391. this.volumetricLightPostProcess.onApply = function (effect) {
  63392. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  63393. var generator = _this.sourceLight.getShadowGenerator();
  63394. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  63395. effect.setTexture("positionSampler", geometry.textures[2]);
  63396. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  63397. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  63398. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  63399. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  63400. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  63401. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  63402. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  63403. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  63404. effect.setVector2("depthValues", depthValues);
  63405. }
  63406. };
  63407. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  63408. // Smooth
  63409. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  63410. // Merge
  63411. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  63412. this.volumetricLightMergePostProces.onApply = function (effect) {
  63413. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  63414. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  63415. };
  63416. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  63417. };
  63418. // Create luminance
  63419. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  63420. var _this = this;
  63421. // Create luminance
  63422. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  63423. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  63424. var offsets = [];
  63425. this.luminancePostProcess.onApply = function (effect) {
  63426. var sU = (1.0 / _this.luminancePostProcess.width);
  63427. var sV = (1.0 / _this.luminancePostProcess.height);
  63428. offsets[0] = -0.5 * sU;
  63429. offsets[1] = 0.5 * sV;
  63430. offsets[2] = 0.5 * sU;
  63431. offsets[3] = 0.5 * sV;
  63432. offsets[4] = -0.5 * sU;
  63433. offsets[5] = -0.5 * sV;
  63434. offsets[6] = 0.5 * sU;
  63435. offsets[7] = -0.5 * sV;
  63436. effect.setArray2("lumOffsets", offsets);
  63437. };
  63438. // Add to pipeline
  63439. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  63440. // Create down sample luminance
  63441. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  63442. var size = Math.pow(3, i);
  63443. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  63444. if (i === 0) {
  63445. defines += "#define FINAL_DOWN_SAMPLER";
  63446. }
  63447. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  63448. this.luminanceDownSamplePostProcesses.push(postProcess);
  63449. }
  63450. // Create callbacks and add effects
  63451. var lastLuminance = this.luminancePostProcess;
  63452. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  63453. var downSampleOffsets = new Array(18);
  63454. pp.onApply = function (effect) {
  63455. if (!lastLuminance) {
  63456. return;
  63457. }
  63458. var id = 0;
  63459. for (var x = -1; x < 2; x++) {
  63460. for (var y = -1; y < 2; y++) {
  63461. downSampleOffsets[id] = x / lastLuminance.width;
  63462. downSampleOffsets[id + 1] = y / lastLuminance.height;
  63463. id += 2;
  63464. }
  63465. }
  63466. effect.setArray2("dsOffsets", downSampleOffsets);
  63467. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  63468. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  63469. lastLuminance = _this.luminancePostProcess;
  63470. }
  63471. else {
  63472. lastLuminance = pp;
  63473. }
  63474. };
  63475. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  63476. pp.onAfterRender = function (effect) {
  63477. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  63478. 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);
  63479. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  63480. };
  63481. }
  63482. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  63483. });
  63484. };
  63485. // Create HDR post-process
  63486. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  63487. var _this = this;
  63488. 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);
  63489. var outputLiminance = 1;
  63490. var time = 0;
  63491. var lastTime = 0;
  63492. this.hdrPostProcess.onApply = function (effect) {
  63493. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  63494. time += scene.getEngine().getDeltaTime();
  63495. if (outputLiminance < 0) {
  63496. outputLiminance = _this._hdrCurrentLuminance;
  63497. }
  63498. else {
  63499. var dt = (lastTime - time) / 1000.0;
  63500. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  63501. outputLiminance += _this.hdrDecreaseRate * dt;
  63502. }
  63503. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  63504. outputLiminance -= _this.hdrIncreaseRate * dt;
  63505. }
  63506. else {
  63507. outputLiminance = _this._hdrCurrentLuminance;
  63508. }
  63509. }
  63510. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  63511. effect.setFloat("averageLuminance", outputLiminance);
  63512. lastTime = time;
  63513. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  63514. };
  63515. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  63516. };
  63517. // Create lens flare post-process
  63518. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  63519. var _this = this;
  63520. 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);
  63521. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  63522. this._createBlurPostProcesses(scene, ratio / 4, 2);
  63523. 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);
  63524. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  63525. var resolution = new BABYLON.Vector2(0, 0);
  63526. // Lens flare
  63527. this.lensFlarePostProcess.onApply = function (effect) {
  63528. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  63529. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  63530. effect.setFloat("strength", _this.lensFlareStrength);
  63531. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  63532. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  63533. // Shift
  63534. resolution.x = _this.lensFlarePostProcess.width;
  63535. resolution.y = _this.lensFlarePostProcess.height;
  63536. effect.setVector2("resolution", resolution);
  63537. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  63538. };
  63539. // Compose
  63540. 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);
  63541. 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);
  63542. this.lensFlareComposePostProcess.onApply = function (effect) {
  63543. if (!_this._scene.activeCamera) {
  63544. return;
  63545. }
  63546. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  63547. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  63548. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  63549. // Lens start rotation matrix
  63550. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  63551. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  63552. 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));
  63553. camRot *= 4.0;
  63554. 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);
  63555. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  63556. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  63557. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  63558. };
  63559. };
  63560. // Create depth-of-field post-process
  63561. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  63562. var _this = this;
  63563. 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);
  63564. this.depthOfFieldPostProcess.onApply = function (effect) {
  63565. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  63566. effect.setTexture("depthSampler", _this._getDepthTexture());
  63567. effect.setFloat("distance", _this.depthOfFieldDistance);
  63568. };
  63569. // Add to pipeline
  63570. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  63571. };
  63572. // Create motion blur post-process
  63573. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  63574. var _this = this;
  63575. 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);
  63576. var motionScale = 0;
  63577. var prevViewProjection = BABYLON.Matrix.Identity();
  63578. var invViewProjection = BABYLON.Matrix.Identity();
  63579. var viewProjection = BABYLON.Matrix.Identity();
  63580. var screenSize = BABYLON.Vector2.Zero();
  63581. this.motionBlurPostProcess.onApply = function (effect) {
  63582. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  63583. viewProjection.invertToRef(invViewProjection);
  63584. effect.setMatrix("inverseViewProjection", invViewProjection);
  63585. effect.setMatrix("prevViewProjection", prevViewProjection);
  63586. prevViewProjection = viewProjection;
  63587. screenSize.x = _this.motionBlurPostProcess.width;
  63588. screenSize.y = _this.motionBlurPostProcess.height;
  63589. effect.setVector2("screenSize", screenSize);
  63590. motionScale = scene.getEngine().getFps() / 60.0;
  63591. effect.setFloat("motionScale", motionScale);
  63592. effect.setFloat("motionStrength", _this.motionStrength);
  63593. effect.setTexture("depthSampler", _this._getDepthTexture());
  63594. };
  63595. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  63596. };
  63597. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  63598. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  63599. var renderer = this._scene.enableGeometryBufferRenderer();
  63600. return renderer.getGBuffer().textures[0];
  63601. }
  63602. return this._scene.enableDepthRenderer().getDepthMap();
  63603. };
  63604. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  63605. for (var i = 0; i < this._cameras.length; i++) {
  63606. var camera = this._cameras[i];
  63607. if (this.originalPostProcess) {
  63608. this.originalPostProcess.dispose(camera);
  63609. }
  63610. if (this.downSampleX4PostProcess) {
  63611. this.downSampleX4PostProcess.dispose(camera);
  63612. }
  63613. if (this.brightPassPostProcess) {
  63614. this.brightPassPostProcess.dispose(camera);
  63615. }
  63616. if (this.textureAdderPostProcess) {
  63617. this.textureAdderPostProcess.dispose(camera);
  63618. }
  63619. if (this.textureAdderFinalPostProcess) {
  63620. this.textureAdderFinalPostProcess.dispose(camera);
  63621. }
  63622. if (this.volumetricLightPostProcess) {
  63623. this.volumetricLightPostProcess.dispose(camera);
  63624. }
  63625. if (this.volumetricLightSmoothXPostProcess) {
  63626. this.volumetricLightSmoothXPostProcess.dispose(camera);
  63627. }
  63628. if (this.volumetricLightSmoothYPostProcess) {
  63629. this.volumetricLightSmoothYPostProcess.dispose(camera);
  63630. }
  63631. if (this.volumetricLightMergePostProces) {
  63632. this.volumetricLightMergePostProces.dispose(camera);
  63633. }
  63634. if (this.volumetricLightFinalPostProcess) {
  63635. this.volumetricLightFinalPostProcess.dispose(camera);
  63636. }
  63637. if (this.lensFlarePostProcess) {
  63638. this.lensFlarePostProcess.dispose(camera);
  63639. }
  63640. if (this.lensFlareComposePostProcess) {
  63641. this.lensFlareComposePostProcess.dispose(camera);
  63642. }
  63643. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  63644. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  63645. }
  63646. if (this.luminancePostProcess) {
  63647. this.luminancePostProcess.dispose(camera);
  63648. }
  63649. if (this.hdrPostProcess) {
  63650. this.hdrPostProcess.dispose(camera);
  63651. }
  63652. if (this.hdrFinalPostProcess) {
  63653. this.hdrFinalPostProcess.dispose(camera);
  63654. }
  63655. if (this.depthOfFieldPostProcess) {
  63656. this.depthOfFieldPostProcess.dispose(camera);
  63657. }
  63658. if (this.motionBlurPostProcess) {
  63659. this.motionBlurPostProcess.dispose(camera);
  63660. }
  63661. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  63662. this.blurHPostProcesses[j].dispose(camera);
  63663. }
  63664. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  63665. this.blurVPostProcesses[j].dispose(camera);
  63666. }
  63667. }
  63668. this.originalPostProcess = null;
  63669. this.downSampleX4PostProcess = null;
  63670. this.brightPassPostProcess = null;
  63671. this.textureAdderPostProcess = null;
  63672. this.textureAdderFinalPostProcess = null;
  63673. this.volumetricLightPostProcess = null;
  63674. this.volumetricLightSmoothXPostProcess = null;
  63675. this.volumetricLightSmoothYPostProcess = null;
  63676. this.volumetricLightMergePostProces = null;
  63677. this.volumetricLightFinalPostProcess = null;
  63678. this.lensFlarePostProcess = null;
  63679. this.lensFlareComposePostProcess = null;
  63680. this.luminancePostProcess = null;
  63681. this.hdrPostProcess = null;
  63682. this.hdrFinalPostProcess = null;
  63683. this.depthOfFieldPostProcess = null;
  63684. this.motionBlurPostProcess = null;
  63685. this.luminanceDownSamplePostProcesses = [];
  63686. this.blurHPostProcesses = [];
  63687. this.blurVPostProcesses = [];
  63688. };
  63689. // Dispose
  63690. StandardRenderingPipeline.prototype.dispose = function () {
  63691. this._disposePostProcesses();
  63692. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  63693. _super.prototype.dispose.call(this);
  63694. };
  63695. // Serialize rendering pipeline
  63696. StandardRenderingPipeline.prototype.serialize = function () {
  63697. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63698. serializationObject.customType = "StandardRenderingPipeline";
  63699. return serializationObject;
  63700. };
  63701. /**
  63702. * Static members
  63703. */
  63704. // Parse serialized pipeline
  63705. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  63706. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  63707. };
  63708. // Luminance steps
  63709. StandardRenderingPipeline.LuminanceSteps = 6;
  63710. __decorate([
  63711. BABYLON.serialize()
  63712. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  63713. __decorate([
  63714. BABYLON.serialize()
  63715. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  63716. __decorate([
  63717. BABYLON.serialize()
  63718. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  63719. __decorate([
  63720. BABYLON.serialize()
  63721. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  63722. __decorate([
  63723. BABYLON.serializeAsTexture("lensTexture")
  63724. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  63725. __decorate([
  63726. BABYLON.serialize()
  63727. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  63728. __decorate([
  63729. BABYLON.serialize()
  63730. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  63731. __decorate([
  63732. BABYLON.serialize()
  63733. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  63734. __decorate([
  63735. BABYLON.serialize()
  63736. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  63737. __decorate([
  63738. BABYLON.serialize()
  63739. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  63740. __decorate([
  63741. BABYLON.serialize()
  63742. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  63743. __decorate([
  63744. BABYLON.serializeAsTexture("lensColorTexture")
  63745. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  63746. __decorate([
  63747. BABYLON.serialize()
  63748. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  63749. __decorate([
  63750. BABYLON.serialize()
  63751. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  63752. __decorate([
  63753. BABYLON.serialize()
  63754. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  63755. __decorate([
  63756. BABYLON.serialize()
  63757. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  63758. __decorate([
  63759. BABYLON.serializeAsTexture("lensStarTexture")
  63760. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  63761. __decorate([
  63762. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  63763. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  63764. __decorate([
  63765. BABYLON.serialize()
  63766. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  63767. __decorate([
  63768. BABYLON.serialize()
  63769. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  63770. __decorate([
  63771. BABYLON.serialize()
  63772. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  63773. __decorate([
  63774. BABYLON.serialize()
  63775. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  63776. __decorate([
  63777. BABYLON.serialize()
  63778. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  63779. __decorate([
  63780. BABYLON.serialize()
  63781. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  63782. __decorate([
  63783. BABYLON.serialize()
  63784. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  63785. __decorate([
  63786. BABYLON.serialize()
  63787. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  63788. __decorate([
  63789. BABYLON.serialize()
  63790. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  63791. __decorate([
  63792. BABYLON.serialize()
  63793. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  63794. __decorate([
  63795. BABYLON.serialize()
  63796. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  63797. __decorate([
  63798. BABYLON.serialize()
  63799. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  63800. return StandardRenderingPipeline;
  63801. }(BABYLON.PostProcessRenderPipeline));
  63802. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  63803. })(BABYLON || (BABYLON = {}));
  63804. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  63805. var BABYLON;
  63806. (function (BABYLON) {
  63807. var FxaaPostProcess = /** @class */ (function (_super) {
  63808. __extends(FxaaPostProcess, _super);
  63809. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  63810. if (camera === void 0) { camera = null; }
  63811. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63812. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  63813. _this.onApplyObservable.add(function (effect) {
  63814. var texelSize = _this.texelSize;
  63815. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  63816. });
  63817. return _this;
  63818. }
  63819. return FxaaPostProcess;
  63820. }(BABYLON.PostProcess));
  63821. BABYLON.FxaaPostProcess = FxaaPostProcess;
  63822. })(BABYLON || (BABYLON = {}));
  63823. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  63824. var BABYLON;
  63825. (function (BABYLON) {
  63826. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  63827. __extends(DefaultRenderingPipeline, _super);
  63828. /**
  63829. * @constructor
  63830. * @param {string} name - The rendering pipeline name
  63831. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63832. * @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)
  63833. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63834. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  63835. */
  63836. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  63837. if (automaticBuild === void 0) { automaticBuild = true; }
  63838. var _this = _super.call(this, scene.getEngine(), name) || this;
  63839. _this.PassPostProcessId = "PassPostProcessEffect";
  63840. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  63841. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  63842. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  63843. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  63844. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  63845. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  63846. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  63847. // IAnimatable
  63848. _this.animations = [];
  63849. // Values
  63850. _this._bloomEnabled = false;
  63851. _this._fxaaEnabled = false;
  63852. _this._imageProcessingEnabled = true;
  63853. _this._bloomScale = 0.6;
  63854. _this._buildAllowed = true;
  63855. /**
  63856. * Specifies the size of the bloom blur kernel, relative to the final output size
  63857. */
  63858. _this.bloomKernel = 64;
  63859. /**
  63860. * Specifies the weight of the bloom in the final rendering
  63861. */
  63862. _this._bloomWeight = 0.15;
  63863. _this._cameras = cameras || [];
  63864. _this._buildAllowed = automaticBuild;
  63865. // Initialize
  63866. _this._scene = scene;
  63867. var caps = _this._scene.getEngine().getCaps();
  63868. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  63869. // Misc
  63870. if (_this._hdr) {
  63871. if (caps.textureHalfFloatRender) {
  63872. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63873. }
  63874. else if (caps.textureFloatRender) {
  63875. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63876. }
  63877. }
  63878. else {
  63879. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63880. }
  63881. // Attach
  63882. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63883. _this._buildPipeline();
  63884. return _this;
  63885. }
  63886. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  63887. get: function () {
  63888. return this._bloomWeight;
  63889. },
  63890. set: function (value) {
  63891. if (this._bloomWeight === value) {
  63892. return;
  63893. }
  63894. this._bloomWeight = value;
  63895. if (this._hdr && this.copyBack) {
  63896. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  63897. }
  63898. },
  63899. enumerable: true,
  63900. configurable: true
  63901. });
  63902. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  63903. get: function () {
  63904. return this._bloomScale;
  63905. },
  63906. set: function (value) {
  63907. if (this._bloomScale === value) {
  63908. return;
  63909. }
  63910. this._bloomScale = value;
  63911. this._buildPipeline();
  63912. },
  63913. enumerable: true,
  63914. configurable: true
  63915. });
  63916. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  63917. get: function () {
  63918. return this._bloomEnabled;
  63919. },
  63920. set: function (enabled) {
  63921. if (this._bloomEnabled === enabled) {
  63922. return;
  63923. }
  63924. this._bloomEnabled = enabled;
  63925. this._buildPipeline();
  63926. },
  63927. enumerable: true,
  63928. configurable: true
  63929. });
  63930. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  63931. get: function () {
  63932. return this._fxaaEnabled;
  63933. },
  63934. set: function (enabled) {
  63935. if (this._fxaaEnabled === enabled) {
  63936. return;
  63937. }
  63938. this._fxaaEnabled = enabled;
  63939. this._buildPipeline();
  63940. },
  63941. enumerable: true,
  63942. configurable: true
  63943. });
  63944. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  63945. get: function () {
  63946. return this._imageProcessingEnabled;
  63947. },
  63948. set: function (enabled) {
  63949. if (this._imageProcessingEnabled === enabled) {
  63950. return;
  63951. }
  63952. this._imageProcessingEnabled = enabled;
  63953. this._buildPipeline();
  63954. },
  63955. enumerable: true,
  63956. configurable: true
  63957. });
  63958. /**
  63959. * Force the compilation of the entire pipeline.
  63960. */
  63961. DefaultRenderingPipeline.prototype.prepare = function () {
  63962. var previousState = this._buildAllowed;
  63963. this._buildAllowed = true;
  63964. this._buildPipeline();
  63965. this._buildAllowed = previousState;
  63966. };
  63967. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  63968. var _this = this;
  63969. if (!this._buildAllowed) {
  63970. return;
  63971. }
  63972. var engine = this._scene.getEngine();
  63973. this._disposePostProcesses();
  63974. this._reset();
  63975. if (this.bloomEnabled) {
  63976. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63977. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  63978. if (!this._hdr) {
  63979. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63980. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  63981. this.highlights.autoClear = false;
  63982. this.highlights.alwaysForcePOT = true;
  63983. }
  63984. 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);
  63985. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  63986. this.blurX.alwaysForcePOT = true;
  63987. this.blurX.autoClear = false;
  63988. this.blurX.onActivateObservable.add(function () {
  63989. var dw = _this.blurX.width / engine.getRenderWidth(true);
  63990. _this.blurX.kernel = _this.bloomKernel * dw;
  63991. });
  63992. 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);
  63993. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  63994. this.blurY.alwaysForcePOT = true;
  63995. this.blurY.autoClear = false;
  63996. this.blurY.onActivateObservable.add(function () {
  63997. var dh = _this.blurY.height / engine.getRenderHeight(true);
  63998. _this.blurY.kernel = _this.bloomKernel * dh;
  63999. });
  64000. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64001. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  64002. this.copyBack.alwaysForcePOT = true;
  64003. if (this._hdr) {
  64004. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  64005. var w = this.bloomWeight;
  64006. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  64007. }
  64008. else {
  64009. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  64010. }
  64011. this.copyBack.autoClear = false;
  64012. }
  64013. if (this._imageProcessingEnabled) {
  64014. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64015. if (this._hdr) {
  64016. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  64017. }
  64018. else {
  64019. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  64020. }
  64021. }
  64022. if (this.fxaaEnabled) {
  64023. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64024. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  64025. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  64026. }
  64027. else if (this._hdr && this.imageProcessing) {
  64028. this.finalMerge = this.imageProcessing;
  64029. }
  64030. else {
  64031. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  64032. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  64033. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  64034. }
  64035. if (this.bloomEnabled) {
  64036. if (this._hdr) {
  64037. this.copyBack.shareOutputWith(this.blurX);
  64038. if (this.imageProcessing) {
  64039. this.imageProcessing.shareOutputWith(this.pass);
  64040. this.imageProcessing.autoClear = false;
  64041. }
  64042. else if (this.fxaa) {
  64043. this.fxaa.shareOutputWith(this.pass);
  64044. }
  64045. else {
  64046. this.finalMerge.shareOutputWith(this.pass);
  64047. }
  64048. }
  64049. else {
  64050. if (this.fxaa) {
  64051. this.fxaa.shareOutputWith(this.pass);
  64052. }
  64053. else {
  64054. this.finalMerge.shareOutputWith(this.pass);
  64055. }
  64056. }
  64057. }
  64058. if (this._cameras !== null) {
  64059. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  64060. }
  64061. };
  64062. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  64063. for (var i = 0; i < this._cameras.length; i++) {
  64064. var camera = this._cameras[i];
  64065. if (this.pass) {
  64066. this.pass.dispose(camera);
  64067. }
  64068. if (this.highlights) {
  64069. this.highlights.dispose(camera);
  64070. }
  64071. if (this.blurX) {
  64072. this.blurX.dispose(camera);
  64073. }
  64074. if (this.blurY) {
  64075. this.blurY.dispose(camera);
  64076. }
  64077. if (this.copyBack) {
  64078. this.copyBack.dispose(camera);
  64079. }
  64080. if (this.imageProcessing) {
  64081. this.imageProcessing.dispose(camera);
  64082. }
  64083. if (this.fxaa) {
  64084. this.fxaa.dispose(camera);
  64085. }
  64086. if (this.finalMerge) {
  64087. this.finalMerge.dispose(camera);
  64088. }
  64089. }
  64090. this.pass = null;
  64091. this.highlights = null;
  64092. this.blurX = null;
  64093. this.blurY = null;
  64094. this.copyBack = null;
  64095. this.imageProcessing = null;
  64096. this.fxaa = null;
  64097. this.finalMerge = null;
  64098. };
  64099. // Dispose
  64100. DefaultRenderingPipeline.prototype.dispose = function () {
  64101. this._disposePostProcesses();
  64102. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  64103. _super.prototype.dispose.call(this);
  64104. };
  64105. // Serialize rendering pipeline
  64106. DefaultRenderingPipeline.prototype.serialize = function () {
  64107. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64108. serializationObject.customType = "DefaultRenderingPipeline";
  64109. return serializationObject;
  64110. };
  64111. // Parse serialized pipeline
  64112. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  64113. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  64114. };
  64115. __decorate([
  64116. BABYLON.serialize()
  64117. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  64118. __decorate([
  64119. BABYLON.serialize()
  64120. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  64121. __decorate([
  64122. BABYLON.serialize()
  64123. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  64124. __decorate([
  64125. BABYLON.serialize()
  64126. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  64127. __decorate([
  64128. BABYLON.serialize()
  64129. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  64130. __decorate([
  64131. BABYLON.serialize()
  64132. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  64133. __decorate([
  64134. BABYLON.serialize()
  64135. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  64136. __decorate([
  64137. BABYLON.serialize()
  64138. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  64139. return DefaultRenderingPipeline;
  64140. }(BABYLON.PostProcessRenderPipeline));
  64141. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  64142. })(BABYLON || (BABYLON = {}));
  64143. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  64144. var BABYLON;
  64145. (function (BABYLON) {
  64146. /**
  64147. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  64148. */
  64149. var GeometryBufferRenderer = /** @class */ (function () {
  64150. /**
  64151. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  64152. * @param scene The scene the buffer belongs to
  64153. * @param ratio How big is the buffer related to the main canvas.
  64154. */
  64155. function GeometryBufferRenderer(scene, ratio) {
  64156. if (ratio === void 0) { ratio = 1; }
  64157. this._enablePosition = false;
  64158. this._scene = scene;
  64159. this._ratio = ratio;
  64160. // Render target
  64161. this._createRenderTargets();
  64162. }
  64163. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  64164. /**
  64165. * Set the render list (meshes to be rendered) used in the G buffer.
  64166. */
  64167. set: function (meshes) {
  64168. this._multiRenderTarget.renderList = meshes;
  64169. },
  64170. enumerable: true,
  64171. configurable: true
  64172. });
  64173. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  64174. /**
  64175. * Gets wether or not G buffer are supported by the running hardware.
  64176. * This requires draw buffer supports
  64177. */
  64178. get: function () {
  64179. return this._multiRenderTarget.isSupported;
  64180. },
  64181. enumerable: true,
  64182. configurable: true
  64183. });
  64184. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  64185. /**
  64186. * Gets wether or not position are enabled for the G buffer.
  64187. */
  64188. get: function () {
  64189. return this._enablePosition;
  64190. },
  64191. /**
  64192. * Sets wether or not position are enabled for the G buffer.
  64193. */
  64194. set: function (enable) {
  64195. this._enablePosition = enable;
  64196. this.dispose();
  64197. this._createRenderTargets();
  64198. },
  64199. enumerable: true,
  64200. configurable: true
  64201. });
  64202. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  64203. /**
  64204. * Gets the scene associated with the buffer.
  64205. */
  64206. get: function () {
  64207. return this._scene;
  64208. },
  64209. enumerable: true,
  64210. configurable: true
  64211. });
  64212. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  64213. /**
  64214. * Gets the ratio used by the buffer during its creation.
  64215. * How big is the buffer related to the main canvas.
  64216. */
  64217. get: function () {
  64218. return this._ratio;
  64219. },
  64220. enumerable: true,
  64221. configurable: true
  64222. });
  64223. /**
  64224. * Checks wether everything is ready to render a submesh to the G buffer.
  64225. * @param subMesh the submesh to check readiness for
  64226. * @param useInstances is the mesh drawn using instance or not
  64227. * @returns true if ready otherwise false
  64228. */
  64229. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  64230. var material = subMesh.getMaterial();
  64231. if (material && material.disableDepthWrite) {
  64232. return false;
  64233. }
  64234. var defines = [];
  64235. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  64236. var mesh = subMesh.getMesh();
  64237. // Alpha test
  64238. if (material && material.needAlphaTesting()) {
  64239. defines.push("#define ALPHATEST");
  64240. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64241. attribs.push(BABYLON.VertexBuffer.UVKind);
  64242. defines.push("#define UV1");
  64243. }
  64244. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64245. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64246. defines.push("#define UV2");
  64247. }
  64248. }
  64249. // Buffers
  64250. if (this._enablePosition) {
  64251. defines.push("#define POSITION");
  64252. }
  64253. // Bones
  64254. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64255. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64256. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64257. if (mesh.numBoneInfluencers > 4) {
  64258. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64259. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64260. }
  64261. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64262. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64263. }
  64264. else {
  64265. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64266. }
  64267. // Instances
  64268. if (useInstances) {
  64269. defines.push("#define INSTANCES");
  64270. attribs.push("world0");
  64271. attribs.push("world1");
  64272. attribs.push("world2");
  64273. attribs.push("world3");
  64274. }
  64275. // Get correct effect
  64276. var join = defines.join("\n");
  64277. if (this._cachedDefines !== join) {
  64278. this._cachedDefines = join;
  64279. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  64280. }
  64281. return this._effect.isReady();
  64282. };
  64283. /**
  64284. * Gets the current underlying G Buffer.
  64285. * @returns the buffer
  64286. */
  64287. GeometryBufferRenderer.prototype.getGBuffer = function () {
  64288. return this._multiRenderTarget;
  64289. };
  64290. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  64291. /**
  64292. * Gets the number of samples used to render the buffer (anti aliasing).
  64293. */
  64294. get: function () {
  64295. return this._multiRenderTarget.samples;
  64296. },
  64297. /**
  64298. * Sets the number of samples used to render the buffer (anti aliasing).
  64299. */
  64300. set: function (value) {
  64301. this._multiRenderTarget.samples = value;
  64302. },
  64303. enumerable: true,
  64304. configurable: true
  64305. });
  64306. /**
  64307. * Disposes the renderer and frees up associated resources.
  64308. */
  64309. GeometryBufferRenderer.prototype.dispose = function () {
  64310. this.getGBuffer().dispose();
  64311. };
  64312. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  64313. var _this = this;
  64314. var engine = this._scene.getEngine();
  64315. var count = this._enablePosition ? 3 : 2;
  64316. 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 });
  64317. if (!this.isSupported) {
  64318. return;
  64319. }
  64320. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64321. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64322. this._multiRenderTarget.refreshRate = 1;
  64323. this._multiRenderTarget.renderParticles = false;
  64324. this._multiRenderTarget.renderList = null;
  64325. // set default depth value to 1.0 (far away)
  64326. this._multiRenderTarget.onClearObservable.add(function (engine) {
  64327. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  64328. });
  64329. // Custom render function
  64330. var renderSubMesh = function (subMesh) {
  64331. var mesh = subMesh.getRenderingMesh();
  64332. var scene = _this._scene;
  64333. var engine = scene.getEngine();
  64334. var material = subMesh.getMaterial();
  64335. if (!material) {
  64336. return;
  64337. }
  64338. // Culling
  64339. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64340. // Managing instances
  64341. var batch = mesh._getInstancesRenderList(subMesh._id);
  64342. if (batch.mustReturn) {
  64343. return;
  64344. }
  64345. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64346. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  64347. engine.enableEffect(_this._effect);
  64348. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64349. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64350. _this._effect.setMatrix("view", scene.getViewMatrix());
  64351. // Alpha test
  64352. if (material && material.needAlphaTesting()) {
  64353. var alphaTexture = material.getAlphaTestTexture();
  64354. if (alphaTexture) {
  64355. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64356. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64357. }
  64358. }
  64359. // Bones
  64360. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64361. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64362. }
  64363. // Draw
  64364. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64365. }
  64366. };
  64367. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64368. var index;
  64369. if (depthOnlySubMeshes.length) {
  64370. engine.setColorWrite(false);
  64371. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64372. renderSubMesh(depthOnlySubMeshes.data[index]);
  64373. }
  64374. engine.setColorWrite(true);
  64375. }
  64376. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64377. renderSubMesh(opaqueSubMeshes.data[index]);
  64378. }
  64379. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64380. renderSubMesh(alphaTestSubMeshes.data[index]);
  64381. }
  64382. };
  64383. };
  64384. return GeometryBufferRenderer;
  64385. }());
  64386. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  64387. })(BABYLON || (BABYLON = {}));
  64388. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  64389. var BABYLON;
  64390. (function (BABYLON) {
  64391. var RefractionPostProcess = /** @class */ (function (_super) {
  64392. __extends(RefractionPostProcess, _super);
  64393. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  64394. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  64395. _this.color = color;
  64396. _this.depth = depth;
  64397. _this.colorLevel = colorLevel;
  64398. _this.onActivateObservable.add(function (cam) {
  64399. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  64400. });
  64401. _this.onApplyObservable.add(function (effect) {
  64402. effect.setColor3("baseColor", _this.color);
  64403. effect.setFloat("depth", _this.depth);
  64404. effect.setFloat("colorLevel", _this.colorLevel);
  64405. effect.setTexture("refractionSampler", _this._refRexture);
  64406. });
  64407. return _this;
  64408. }
  64409. // Methods
  64410. RefractionPostProcess.prototype.dispose = function (camera) {
  64411. if (this._refRexture) {
  64412. this._refRexture.dispose();
  64413. }
  64414. _super.prototype.dispose.call(this, camera);
  64415. };
  64416. return RefractionPostProcess;
  64417. }(BABYLON.PostProcess));
  64418. BABYLON.RefractionPostProcess = RefractionPostProcess;
  64419. })(BABYLON || (BABYLON = {}));
  64420. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  64421. var BABYLON;
  64422. (function (BABYLON) {
  64423. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  64424. __extends(BlackAndWhitePostProcess, _super);
  64425. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  64426. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  64427. _this.degree = 1;
  64428. _this.onApplyObservable.add(function (effect) {
  64429. effect.setFloat("degree", _this.degree);
  64430. });
  64431. return _this;
  64432. }
  64433. return BlackAndWhitePostProcess;
  64434. }(BABYLON.PostProcess));
  64435. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  64436. })(BABYLON || (BABYLON = {}));
  64437. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  64438. var BABYLON;
  64439. (function (BABYLON) {
  64440. var ConvolutionPostProcess = /** @class */ (function (_super) {
  64441. __extends(ConvolutionPostProcess, _super);
  64442. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  64443. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  64444. _this.kernel = kernel;
  64445. _this.onApply = function (effect) {
  64446. effect.setFloat2("screenSize", _this.width, _this.height);
  64447. effect.setArray("kernel", _this.kernel);
  64448. };
  64449. return _this;
  64450. }
  64451. // Statics
  64452. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  64453. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  64454. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  64455. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  64456. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  64457. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  64458. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  64459. return ConvolutionPostProcess;
  64460. }(BABYLON.PostProcess));
  64461. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  64462. })(BABYLON || (BABYLON = {}));
  64463. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  64464. var BABYLON;
  64465. (function (BABYLON) {
  64466. var FilterPostProcess = /** @class */ (function (_super) {
  64467. __extends(FilterPostProcess, _super);
  64468. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  64469. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  64470. _this.kernelMatrix = kernelMatrix;
  64471. _this.onApply = function (effect) {
  64472. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  64473. };
  64474. return _this;
  64475. }
  64476. return FilterPostProcess;
  64477. }(BABYLON.PostProcess));
  64478. BABYLON.FilterPostProcess = FilterPostProcess;
  64479. })(BABYLON || (BABYLON = {}));
  64480. //# sourceMappingURL=babylon.filterPostProcess.js.map
  64481. var BABYLON;
  64482. (function (BABYLON) {
  64483. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  64484. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  64485. __extends(VolumetricLightScatteringPostProcess, _super);
  64486. /**
  64487. * @constructor
  64488. * @param {string} name - The post-process name
  64489. * @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)
  64490. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  64491. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  64492. * @param {number} samples - The post-process quality, default 100
  64493. * @param {number} samplingMode - The post-process filtering mode
  64494. * @param {BABYLON.Engine} engine - The babylon engine
  64495. * @param {boolean} reusable - If the post-process is reusable
  64496. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  64497. */
  64498. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  64499. if (samples === void 0) { samples = 100; }
  64500. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64501. 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;
  64502. _this._screenCoordinates = BABYLON.Vector2.Zero();
  64503. /**
  64504. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  64505. * @type {Vector3}
  64506. */
  64507. _this.customMeshPosition = BABYLON.Vector3.Zero();
  64508. /**
  64509. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  64510. * @type {boolean}
  64511. */
  64512. _this.useCustomMeshPosition = false;
  64513. /**
  64514. * If the post-process should inverse the light scattering direction
  64515. * @type {boolean}
  64516. */
  64517. _this.invert = true;
  64518. /**
  64519. * Array containing the excluded meshes not rendered in the internal pass
  64520. */
  64521. _this.excludedMeshes = new Array();
  64522. /**
  64523. * Controls the overall intensity of the post-process
  64524. * @type {number}
  64525. */
  64526. _this.exposure = 0.3;
  64527. /**
  64528. * Dissipates each sample's contribution in range [0, 1]
  64529. * @type {number}
  64530. */
  64531. _this.decay = 0.96815;
  64532. /**
  64533. * Controls the overall intensity of each sample
  64534. * @type {number}
  64535. */
  64536. _this.weight = 0.58767;
  64537. /**
  64538. * Controls the density of each sample
  64539. * @type {number}
  64540. */
  64541. _this.density = 0.926;
  64542. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  64543. engine = scene.getEngine();
  64544. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  64545. // Configure mesh
  64546. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  64547. // Configure
  64548. _this._createPass(scene, ratio.passRatio || ratio);
  64549. _this.onActivate = function (camera) {
  64550. if (!_this.isSupported) {
  64551. _this.dispose(camera);
  64552. }
  64553. _this.onActivate = null;
  64554. };
  64555. _this.onApplyObservable.add(function (effect) {
  64556. _this._updateMeshScreenCoordinates(scene);
  64557. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  64558. effect.setFloat("exposure", _this.exposure);
  64559. effect.setFloat("decay", _this.decay);
  64560. effect.setFloat("weight", _this.weight);
  64561. effect.setFloat("density", _this.density);
  64562. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  64563. });
  64564. return _this;
  64565. }
  64566. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  64567. get: function () {
  64568. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  64569. return false;
  64570. },
  64571. set: function (useDiffuseColor) {
  64572. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  64573. },
  64574. enumerable: true,
  64575. configurable: true
  64576. });
  64577. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  64578. return "VolumetricLightScatteringPostProcess";
  64579. };
  64580. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  64581. var mesh = subMesh.getMesh();
  64582. // Render this.mesh as default
  64583. if (mesh === this.mesh && mesh.material) {
  64584. return mesh.material.isReady(mesh);
  64585. }
  64586. var defines = [];
  64587. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64588. var material = subMesh.getMaterial();
  64589. // Alpha test
  64590. if (material) {
  64591. if (material.needAlphaTesting()) {
  64592. defines.push("#define ALPHATEST");
  64593. }
  64594. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64595. attribs.push(BABYLON.VertexBuffer.UVKind);
  64596. defines.push("#define UV1");
  64597. }
  64598. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64599. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64600. defines.push("#define UV2");
  64601. }
  64602. }
  64603. // Bones
  64604. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64605. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64606. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64607. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64608. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  64609. }
  64610. else {
  64611. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64612. }
  64613. // Instances
  64614. if (useInstances) {
  64615. defines.push("#define INSTANCES");
  64616. attribs.push("world0");
  64617. attribs.push("world1");
  64618. attribs.push("world2");
  64619. attribs.push("world3");
  64620. }
  64621. // Get correct effect
  64622. var join = defines.join("\n");
  64623. if (this._cachedDefines !== join) {
  64624. this._cachedDefines = join;
  64625. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  64626. }
  64627. return this._volumetricLightScatteringPass.isReady();
  64628. };
  64629. /**
  64630. * Sets the new light position for light scattering effect
  64631. * @param {BABYLON.Vector3} The new custom light position
  64632. */
  64633. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  64634. this.customMeshPosition = position;
  64635. };
  64636. /**
  64637. * Returns the light position for light scattering effect
  64638. * @return {BABYLON.Vector3} The custom light position
  64639. */
  64640. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  64641. return this.customMeshPosition;
  64642. };
  64643. /**
  64644. * Disposes the internal assets and detaches the post-process from the camera
  64645. */
  64646. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  64647. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  64648. if (rttIndex !== -1) {
  64649. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  64650. }
  64651. this._volumetricLightScatteringRTT.dispose();
  64652. _super.prototype.dispose.call(this, camera);
  64653. };
  64654. /**
  64655. * Returns the render target texture used by the post-process
  64656. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  64657. */
  64658. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  64659. return this._volumetricLightScatteringRTT;
  64660. };
  64661. // Private methods
  64662. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  64663. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  64664. return true;
  64665. }
  64666. return false;
  64667. };
  64668. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  64669. var _this = this;
  64670. var engine = scene.getEngine();
  64671. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64672. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64673. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64674. this._volumetricLightScatteringRTT.renderList = null;
  64675. this._volumetricLightScatteringRTT.renderParticles = false;
  64676. var camera = this.getCamera();
  64677. if (camera) {
  64678. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  64679. }
  64680. else {
  64681. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  64682. }
  64683. // Custom render function for submeshes
  64684. var renderSubMesh = function (subMesh) {
  64685. var mesh = subMesh.getRenderingMesh();
  64686. if (_this._meshExcluded(mesh)) {
  64687. return;
  64688. }
  64689. var material = subMesh.getMaterial();
  64690. if (!material) {
  64691. return;
  64692. }
  64693. var scene = mesh.getScene();
  64694. var engine = scene.getEngine();
  64695. // Culling
  64696. engine.setState(material.backFaceCulling);
  64697. // Managing instances
  64698. var batch = mesh._getInstancesRenderList(subMesh._id);
  64699. if (batch.mustReturn) {
  64700. return;
  64701. }
  64702. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64703. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  64704. var effect = _this._volumetricLightScatteringPass;
  64705. if (mesh === _this.mesh) {
  64706. if (subMesh.effect) {
  64707. effect = subMesh.effect;
  64708. }
  64709. else {
  64710. effect = material.getEffect();
  64711. }
  64712. }
  64713. engine.enableEffect(effect);
  64714. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  64715. if (mesh === _this.mesh) {
  64716. material.bind(mesh.getWorldMatrix(), mesh);
  64717. }
  64718. else {
  64719. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  64720. // Alpha test
  64721. if (material && material.needAlphaTesting()) {
  64722. var alphaTexture = material.getAlphaTestTexture();
  64723. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  64724. if (alphaTexture) {
  64725. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64726. }
  64727. }
  64728. // Bones
  64729. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64730. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64731. }
  64732. }
  64733. // Draw
  64734. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  64735. }
  64736. };
  64737. // Render target texture callbacks
  64738. var savedSceneClearColor;
  64739. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  64740. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  64741. savedSceneClearColor = scene.clearColor;
  64742. scene.clearColor = sceneClearColor;
  64743. });
  64744. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  64745. scene.clearColor = savedSceneClearColor;
  64746. });
  64747. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64748. var engine = scene.getEngine();
  64749. var index;
  64750. if (depthOnlySubMeshes.length) {
  64751. engine.setColorWrite(false);
  64752. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64753. renderSubMesh(depthOnlySubMeshes.data[index]);
  64754. }
  64755. engine.setColorWrite(true);
  64756. }
  64757. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64758. renderSubMesh(opaqueSubMeshes.data[index]);
  64759. }
  64760. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64761. renderSubMesh(alphaTestSubMeshes.data[index]);
  64762. }
  64763. if (transparentSubMeshes.length) {
  64764. // Sort sub meshes
  64765. for (index = 0; index < transparentSubMeshes.length; index++) {
  64766. var submesh = transparentSubMeshes.data[index];
  64767. var boundingInfo = submesh.getBoundingInfo();
  64768. if (boundingInfo && scene.activeCamera) {
  64769. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  64770. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  64771. }
  64772. }
  64773. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  64774. sortedArray.sort(function (a, b) {
  64775. // Alpha index first
  64776. if (a._alphaIndex > b._alphaIndex) {
  64777. return 1;
  64778. }
  64779. if (a._alphaIndex < b._alphaIndex) {
  64780. return -1;
  64781. }
  64782. // Then distance to camera
  64783. if (a._distanceToCamera < b._distanceToCamera) {
  64784. return 1;
  64785. }
  64786. if (a._distanceToCamera > b._distanceToCamera) {
  64787. return -1;
  64788. }
  64789. return 0;
  64790. });
  64791. // Render sub meshes
  64792. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  64793. for (index = 0; index < sortedArray.length; index++) {
  64794. renderSubMesh(sortedArray[index]);
  64795. }
  64796. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64797. }
  64798. };
  64799. };
  64800. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  64801. var transform = scene.getTransformMatrix();
  64802. var meshPosition;
  64803. if (this.useCustomMeshPosition) {
  64804. meshPosition = this.customMeshPosition;
  64805. }
  64806. else if (this.attachedNode) {
  64807. meshPosition = this.attachedNode.position;
  64808. }
  64809. else {
  64810. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  64811. }
  64812. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  64813. this._screenCoordinates.x = pos.x / this._viewPort.width;
  64814. this._screenCoordinates.y = pos.y / this._viewPort.height;
  64815. if (this.invert)
  64816. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  64817. };
  64818. // Static methods
  64819. /**
  64820. * Creates a default mesh for the Volumeric Light Scattering post-process
  64821. * @param {string} The mesh name
  64822. * @param {BABYLON.Scene} The scene where to create the mesh
  64823. * @return {BABYLON.Mesh} the default mesh
  64824. */
  64825. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  64826. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  64827. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  64828. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  64829. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  64830. mesh.material = material;
  64831. return mesh;
  64832. };
  64833. __decorate([
  64834. BABYLON.serializeAsVector3()
  64835. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  64836. __decorate([
  64837. BABYLON.serialize()
  64838. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  64839. __decorate([
  64840. BABYLON.serialize()
  64841. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  64842. __decorate([
  64843. BABYLON.serializeAsMeshReference()
  64844. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  64845. __decorate([
  64846. BABYLON.serialize()
  64847. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  64848. __decorate([
  64849. BABYLON.serialize()
  64850. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  64851. __decorate([
  64852. BABYLON.serialize()
  64853. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  64854. __decorate([
  64855. BABYLON.serialize()
  64856. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  64857. __decorate([
  64858. BABYLON.serialize()
  64859. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  64860. return VolumetricLightScatteringPostProcess;
  64861. }(BABYLON.PostProcess));
  64862. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  64863. })(BABYLON || (BABYLON = {}));
  64864. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  64865. //
  64866. // This post-process allows the modification of rendered colors by using
  64867. // a 'look-up table' (LUT). This effect is also called Color Grading.
  64868. //
  64869. // The object needs to be provided an url to a texture containing the color
  64870. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  64871. // Use an image editing software to tweak the LUT to match your needs.
  64872. //
  64873. // For an example of a color LUT, see here:
  64874. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  64875. // For explanations on color grading, see here:
  64876. // http://udn.epicgames.com/Three/ColorGrading.html
  64877. //
  64878. var BABYLON;
  64879. (function (BABYLON) {
  64880. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  64881. __extends(ColorCorrectionPostProcess, _super);
  64882. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  64883. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  64884. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64885. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  64886. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64887. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64888. _this.onApply = function (effect) {
  64889. effect.setTexture("colorTable", _this._colorTableTexture);
  64890. };
  64891. return _this;
  64892. }
  64893. return ColorCorrectionPostProcess;
  64894. }(BABYLON.PostProcess));
  64895. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  64896. })(BABYLON || (BABYLON = {}));
  64897. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  64898. var BABYLON;
  64899. (function (BABYLON) {
  64900. var TonemappingOperator;
  64901. (function (TonemappingOperator) {
  64902. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  64903. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  64904. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  64905. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  64906. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  64907. ;
  64908. var TonemapPostProcess = /** @class */ (function (_super) {
  64909. __extends(TonemapPostProcess, _super);
  64910. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  64911. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64912. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64913. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  64914. _this._operator = _operator;
  64915. _this.exposureAdjustment = exposureAdjustment;
  64916. var defines = "#define ";
  64917. if (_this._operator === TonemappingOperator.Hable)
  64918. defines += "HABLE_TONEMAPPING";
  64919. else if (_this._operator === TonemappingOperator.Reinhard)
  64920. defines += "REINHARD_TONEMAPPING";
  64921. else if (_this._operator === TonemappingOperator.HejiDawson)
  64922. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  64923. else if (_this._operator === TonemappingOperator.Photographic)
  64924. defines += "PHOTOGRAPHIC_TONEMAPPING";
  64925. //sadly a second call to create the effect.
  64926. _this.updateEffect(defines);
  64927. _this.onApply = function (effect) {
  64928. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  64929. };
  64930. return _this;
  64931. }
  64932. return TonemapPostProcess;
  64933. }(BABYLON.PostProcess));
  64934. BABYLON.TonemapPostProcess = TonemapPostProcess;
  64935. })(BABYLON || (BABYLON = {}));
  64936. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  64937. var BABYLON;
  64938. (function (BABYLON) {
  64939. var DisplayPassPostProcess = /** @class */ (function (_super) {
  64940. __extends(DisplayPassPostProcess, _super);
  64941. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  64942. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  64943. }
  64944. return DisplayPassPostProcess;
  64945. }(BABYLON.PostProcess));
  64946. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  64947. })(BABYLON || (BABYLON = {}));
  64948. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  64949. var BABYLON;
  64950. (function (BABYLON) {
  64951. var HighlightsPostProcess = /** @class */ (function (_super) {
  64952. __extends(HighlightsPostProcess, _super);
  64953. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64954. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64955. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64956. }
  64957. return HighlightsPostProcess;
  64958. }(BABYLON.PostProcess));
  64959. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  64960. })(BABYLON || (BABYLON = {}));
  64961. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  64962. var BABYLON;
  64963. (function (BABYLON) {
  64964. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  64965. __extends(ImageProcessingPostProcess, _super);
  64966. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  64967. if (camera === void 0) { camera = null; }
  64968. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64969. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  64970. _this._fromLinearSpace = true;
  64971. /**
  64972. * Defines cache preventing GC.
  64973. */
  64974. _this._defines = {
  64975. IMAGEPROCESSING: false,
  64976. VIGNETTE: false,
  64977. VIGNETTEBLENDMODEMULTIPLY: false,
  64978. VIGNETTEBLENDMODEOPAQUE: false,
  64979. TONEMAPPING: false,
  64980. CONTRAST: false,
  64981. COLORCURVES: false,
  64982. COLORGRADING: false,
  64983. COLORGRADING3D: false,
  64984. FROMLINEARSPACE: false,
  64985. SAMPLER3DGREENDEPTH: false,
  64986. SAMPLER3DBGRMAP: false,
  64987. IMAGEPROCESSINGPOSTPROCESS: false,
  64988. EXPOSURE: false,
  64989. };
  64990. // Setup the configuration as forced by the constructor. This would then not force the
  64991. // scene materials output in linear space and let untouched the default forward pass.
  64992. if (imageProcessingConfiguration) {
  64993. imageProcessingConfiguration.applyByPostProcess = true;
  64994. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  64995. // This will cause the shader to be compiled
  64996. _this.fromLinearSpace = false;
  64997. }
  64998. else {
  64999. _this._attachImageProcessingConfiguration(null, true);
  65000. _this.imageProcessingConfiguration.applyByPostProcess = true;
  65001. }
  65002. _this.onApply = function (effect) {
  65003. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  65004. };
  65005. return _this;
  65006. }
  65007. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  65008. /**
  65009. * Gets the image processing configuration used either in this material.
  65010. */
  65011. get: function () {
  65012. return this._imageProcessingConfiguration;
  65013. },
  65014. /**
  65015. * Sets the Default image processing configuration used either in the this material.
  65016. *
  65017. * If sets to null, the scene one is in use.
  65018. */
  65019. set: function (value) {
  65020. this._attachImageProcessingConfiguration(value);
  65021. },
  65022. enumerable: true,
  65023. configurable: true
  65024. });
  65025. /**
  65026. * Attaches a new image processing configuration to the PBR Material.
  65027. * @param configuration
  65028. */
  65029. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  65030. var _this = this;
  65031. if (doNotBuild === void 0) { doNotBuild = false; }
  65032. if (configuration === this._imageProcessingConfiguration) {
  65033. return;
  65034. }
  65035. // Detaches observer.
  65036. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  65037. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  65038. }
  65039. // Pick the scene configuration if needed.
  65040. if (!configuration) {
  65041. var scene = null;
  65042. var engine = this.getEngine();
  65043. var camera = this.getCamera();
  65044. if (camera) {
  65045. scene = camera.getScene();
  65046. }
  65047. else if (engine && engine.scenes) {
  65048. var scenes = engine.scenes;
  65049. scene = scenes[scenes.length - 1];
  65050. }
  65051. else {
  65052. scene = BABYLON.Engine.LastCreatedScene;
  65053. }
  65054. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  65055. }
  65056. else {
  65057. this._imageProcessingConfiguration = configuration;
  65058. }
  65059. // Attaches observer.
  65060. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  65061. _this._updateParameters();
  65062. });
  65063. // Ensure the effect will be rebuilt.
  65064. if (!doNotBuild) {
  65065. this._updateParameters();
  65066. }
  65067. };
  65068. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  65069. /**
  65070. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  65071. */
  65072. get: function () {
  65073. return this.imageProcessingConfiguration.colorCurves;
  65074. },
  65075. /**
  65076. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  65077. */
  65078. set: function (value) {
  65079. this.imageProcessingConfiguration.colorCurves = value;
  65080. },
  65081. enumerable: true,
  65082. configurable: true
  65083. });
  65084. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  65085. /**
  65086. * Gets wether the color curves effect is enabled.
  65087. */
  65088. get: function () {
  65089. return this.imageProcessingConfiguration.colorCurvesEnabled;
  65090. },
  65091. /**
  65092. * Sets wether the color curves effect is enabled.
  65093. */
  65094. set: function (value) {
  65095. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  65096. },
  65097. enumerable: true,
  65098. configurable: true
  65099. });
  65100. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  65101. /**
  65102. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  65103. */
  65104. get: function () {
  65105. return this.imageProcessingConfiguration.colorGradingTexture;
  65106. },
  65107. /**
  65108. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  65109. */
  65110. set: function (value) {
  65111. this.imageProcessingConfiguration.colorGradingTexture = value;
  65112. },
  65113. enumerable: true,
  65114. configurable: true
  65115. });
  65116. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  65117. /**
  65118. * Gets wether the color grading effect is enabled.
  65119. */
  65120. get: function () {
  65121. return this.imageProcessingConfiguration.colorGradingEnabled;
  65122. },
  65123. /**
  65124. * Gets wether the color grading effect is enabled.
  65125. */
  65126. set: function (value) {
  65127. this.imageProcessingConfiguration.colorGradingEnabled = value;
  65128. },
  65129. enumerable: true,
  65130. configurable: true
  65131. });
  65132. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  65133. /**
  65134. * Gets exposure used in the effect.
  65135. */
  65136. get: function () {
  65137. return this.imageProcessingConfiguration.exposure;
  65138. },
  65139. /**
  65140. * Sets exposure used in the effect.
  65141. */
  65142. set: function (value) {
  65143. this.imageProcessingConfiguration.exposure = value;
  65144. },
  65145. enumerable: true,
  65146. configurable: true
  65147. });
  65148. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  65149. /**
  65150. * Gets wether tonemapping is enabled or not.
  65151. */
  65152. get: function () {
  65153. return this._imageProcessingConfiguration.toneMappingEnabled;
  65154. },
  65155. /**
  65156. * Sets wether tonemapping is enabled or not
  65157. */
  65158. set: function (value) {
  65159. this._imageProcessingConfiguration.toneMappingEnabled = value;
  65160. },
  65161. enumerable: true,
  65162. configurable: true
  65163. });
  65164. ;
  65165. ;
  65166. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  65167. /**
  65168. * Gets contrast used in the effect.
  65169. */
  65170. get: function () {
  65171. return this.imageProcessingConfiguration.contrast;
  65172. },
  65173. /**
  65174. * Sets contrast used in the effect.
  65175. */
  65176. set: function (value) {
  65177. this.imageProcessingConfiguration.contrast = value;
  65178. },
  65179. enumerable: true,
  65180. configurable: true
  65181. });
  65182. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  65183. /**
  65184. * Gets Vignette stretch size.
  65185. */
  65186. get: function () {
  65187. return this.imageProcessingConfiguration.vignetteStretch;
  65188. },
  65189. /**
  65190. * Sets Vignette stretch size.
  65191. */
  65192. set: function (value) {
  65193. this.imageProcessingConfiguration.vignetteStretch = value;
  65194. },
  65195. enumerable: true,
  65196. configurable: true
  65197. });
  65198. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  65199. /**
  65200. * Gets Vignette centre X Offset.
  65201. */
  65202. get: function () {
  65203. return this.imageProcessingConfiguration.vignetteCentreX;
  65204. },
  65205. /**
  65206. * Sets Vignette centre X Offset.
  65207. */
  65208. set: function (value) {
  65209. this.imageProcessingConfiguration.vignetteCentreX = value;
  65210. },
  65211. enumerable: true,
  65212. configurable: true
  65213. });
  65214. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  65215. /**
  65216. * Gets Vignette centre Y Offset.
  65217. */
  65218. get: function () {
  65219. return this.imageProcessingConfiguration.vignetteCentreY;
  65220. },
  65221. /**
  65222. * Sets Vignette centre Y Offset.
  65223. */
  65224. set: function (value) {
  65225. this.imageProcessingConfiguration.vignetteCentreY = value;
  65226. },
  65227. enumerable: true,
  65228. configurable: true
  65229. });
  65230. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  65231. /**
  65232. * Gets Vignette weight or intensity of the vignette effect.
  65233. */
  65234. get: function () {
  65235. return this.imageProcessingConfiguration.vignetteWeight;
  65236. },
  65237. /**
  65238. * Sets Vignette weight or intensity of the vignette effect.
  65239. */
  65240. set: function (value) {
  65241. this.imageProcessingConfiguration.vignetteWeight = value;
  65242. },
  65243. enumerable: true,
  65244. configurable: true
  65245. });
  65246. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  65247. /**
  65248. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  65249. * if vignetteEnabled is set to true.
  65250. */
  65251. get: function () {
  65252. return this.imageProcessingConfiguration.vignetteColor;
  65253. },
  65254. /**
  65255. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  65256. * if vignetteEnabled is set to true.
  65257. */
  65258. set: function (value) {
  65259. this.imageProcessingConfiguration.vignetteColor = value;
  65260. },
  65261. enumerable: true,
  65262. configurable: true
  65263. });
  65264. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  65265. /**
  65266. * Gets Camera field of view used by the Vignette effect.
  65267. */
  65268. get: function () {
  65269. return this.imageProcessingConfiguration.vignetteCameraFov;
  65270. },
  65271. /**
  65272. * Sets Camera field of view used by the Vignette effect.
  65273. */
  65274. set: function (value) {
  65275. this.imageProcessingConfiguration.vignetteCameraFov = value;
  65276. },
  65277. enumerable: true,
  65278. configurable: true
  65279. });
  65280. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  65281. /**
  65282. * Gets the vignette blend mode allowing different kind of effect.
  65283. */
  65284. get: function () {
  65285. return this.imageProcessingConfiguration.vignetteBlendMode;
  65286. },
  65287. /**
  65288. * Sets the vignette blend mode allowing different kind of effect.
  65289. */
  65290. set: function (value) {
  65291. this.imageProcessingConfiguration.vignetteBlendMode = value;
  65292. },
  65293. enumerable: true,
  65294. configurable: true
  65295. });
  65296. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  65297. /**
  65298. * Gets wether the vignette effect is enabled.
  65299. */
  65300. get: function () {
  65301. return this.imageProcessingConfiguration.vignetteEnabled;
  65302. },
  65303. /**
  65304. * Sets wether the vignette effect is enabled.
  65305. */
  65306. set: function (value) {
  65307. this.imageProcessingConfiguration.vignetteEnabled = value;
  65308. },
  65309. enumerable: true,
  65310. configurable: true
  65311. });
  65312. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  65313. /**
  65314. * Gets wether the input of the processing is in Gamma or Linear Space.
  65315. */
  65316. get: function () {
  65317. return this._fromLinearSpace;
  65318. },
  65319. /**
  65320. * Sets wether the input of the processing is in Gamma or Linear Space.
  65321. */
  65322. set: function (value) {
  65323. if (this._fromLinearSpace === value) {
  65324. return;
  65325. }
  65326. this._fromLinearSpace = value;
  65327. this._updateParameters();
  65328. },
  65329. enumerable: true,
  65330. configurable: true
  65331. });
  65332. ImageProcessingPostProcess.prototype.getClassName = function () {
  65333. return "ImageProcessingPostProcess";
  65334. };
  65335. ImageProcessingPostProcess.prototype._updateParameters = function () {
  65336. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  65337. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  65338. var defines = "";
  65339. for (var define in this._defines) {
  65340. if (this._defines[define]) {
  65341. defines += "#define " + define + ";\r\n";
  65342. }
  65343. }
  65344. var samplers = ["textureSampler"];
  65345. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  65346. var uniforms = ["scale"];
  65347. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  65348. this.updateEffect(defines, uniforms, samplers);
  65349. };
  65350. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  65351. _super.prototype.dispose.call(this, camera);
  65352. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  65353. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  65354. }
  65355. this.imageProcessingConfiguration.applyByPostProcess = false;
  65356. };
  65357. __decorate([
  65358. BABYLON.serialize()
  65359. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  65360. return ImageProcessingPostProcess;
  65361. }(BABYLON.PostProcess));
  65362. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  65363. })(BABYLON || (BABYLON = {}));
  65364. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  65365. var BABYLON;
  65366. (function (BABYLON) {
  65367. var BlurPostProcess = /** @class */ (function (_super) {
  65368. __extends(BlurPostProcess, _super);
  65369. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  65370. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65371. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65372. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  65373. _this.direction = direction;
  65374. _this._packedFloat = false;
  65375. _this.onApplyObservable.add(function (effect) {
  65376. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  65377. });
  65378. _this.kernel = kernel;
  65379. return _this;
  65380. }
  65381. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  65382. /**
  65383. * Gets the length in pixels of the blur sample region
  65384. */
  65385. get: function () {
  65386. return this._idealKernel;
  65387. },
  65388. /**
  65389. * Sets the length in pixels of the blur sample region
  65390. */
  65391. set: function (v) {
  65392. if (this._idealKernel === v) {
  65393. return;
  65394. }
  65395. v = Math.max(v, 1);
  65396. this._idealKernel = v;
  65397. this._kernel = this._nearestBestKernel(v);
  65398. this._updateParameters();
  65399. },
  65400. enumerable: true,
  65401. configurable: true
  65402. });
  65403. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  65404. /**
  65405. * Gets wether or not the blur is unpacking/repacking floats
  65406. */
  65407. get: function () {
  65408. return this._packedFloat;
  65409. },
  65410. /**
  65411. * Sets wether or not the blur needs to unpack/repack floats
  65412. */
  65413. set: function (v) {
  65414. if (this._packedFloat === v) {
  65415. return;
  65416. }
  65417. this._packedFloat = v;
  65418. this._updateParameters();
  65419. },
  65420. enumerable: true,
  65421. configurable: true
  65422. });
  65423. BlurPostProcess.prototype._updateParameters = function () {
  65424. // Generate sampling offsets and weights
  65425. var N = this._kernel;
  65426. var centerIndex = (N - 1) / 2;
  65427. // Generate Gaussian sampling weights over kernel
  65428. var offsets = [];
  65429. var weights = [];
  65430. var totalWeight = 0;
  65431. for (var i = 0; i < N; i++) {
  65432. var u = i / (N - 1);
  65433. var w = this._gaussianWeight(u * 2.0 - 1);
  65434. offsets[i] = (i - centerIndex);
  65435. weights[i] = w;
  65436. totalWeight += w;
  65437. }
  65438. // Normalize weights
  65439. for (var i = 0; i < weights.length; i++) {
  65440. weights[i] /= totalWeight;
  65441. }
  65442. // Optimize: combine samples to take advantage of hardware linear sampling
  65443. // Walk from left to center, combining pairs (symmetrically)
  65444. var linearSamplingWeights = [];
  65445. var linearSamplingOffsets = [];
  65446. var linearSamplingMap = [];
  65447. for (var i = 0; i <= centerIndex; i += 2) {
  65448. var j = Math.min(i + 1, Math.floor(centerIndex));
  65449. var singleCenterSample = i === j;
  65450. if (singleCenterSample) {
  65451. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  65452. }
  65453. else {
  65454. var sharedCell = j === centerIndex;
  65455. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  65456. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  65457. if (offsetLinear === 0) {
  65458. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  65459. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  65460. }
  65461. else {
  65462. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  65463. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  65464. }
  65465. }
  65466. }
  65467. for (var i = 0; i < linearSamplingMap.length; i++) {
  65468. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  65469. linearSamplingWeights[i] = linearSamplingMap[i].w;
  65470. }
  65471. // Replace with optimized
  65472. offsets = linearSamplingOffsets;
  65473. weights = linearSamplingWeights;
  65474. // Generate shaders
  65475. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  65476. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  65477. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  65478. var defines = "";
  65479. for (var i = 0; i < varyingCount; i++) {
  65480. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  65481. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  65482. }
  65483. var depCount = 0;
  65484. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  65485. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  65486. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  65487. depCount++;
  65488. }
  65489. if (this.packedFloat) {
  65490. defines += "#define PACKEDFLOAT 1";
  65491. }
  65492. this.updateEffect(defines, null, null, {
  65493. varyingCount: varyingCount,
  65494. depCount: depCount
  65495. });
  65496. };
  65497. /**
  65498. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  65499. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  65500. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  65501. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  65502. * The gaps between physical kernels are compensated for in the weighting of the samples
  65503. * @param idealKernel Ideal blur kernel.
  65504. * @return Nearest best kernel.
  65505. */
  65506. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  65507. var v = Math.round(idealKernel);
  65508. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  65509. var k = _a[_i];
  65510. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  65511. return Math.max(k, 3);
  65512. }
  65513. }
  65514. return Math.max(v, 3);
  65515. };
  65516. /**
  65517. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  65518. * @param x The point on the Gaussian distribution to sample.
  65519. * @return the value of the Gaussian function at x.
  65520. */
  65521. BlurPostProcess.prototype._gaussianWeight = function (x) {
  65522. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  65523. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  65524. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  65525. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  65526. // truncated at around 1.3% of peak strength.
  65527. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  65528. var sigma = (1 / 3);
  65529. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  65530. var exponent = -((x * x) / (2.0 * sigma * sigma));
  65531. var weight = (1.0 / denominator) * Math.exp(exponent);
  65532. return weight;
  65533. };
  65534. /**
  65535. * Generates a string that can be used as a floating point number in GLSL.
  65536. * @param x Value to print.
  65537. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  65538. * @return GLSL float string.
  65539. */
  65540. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  65541. if (decimalFigures === void 0) { decimalFigures = 8; }
  65542. return x.toFixed(decimalFigures).replace(/0+$/, '');
  65543. };
  65544. return BlurPostProcess;
  65545. }(BABYLON.PostProcess));
  65546. BABYLON.BlurPostProcess = BlurPostProcess;
  65547. })(BABYLON || (BABYLON = {}));
  65548. //# sourceMappingURL=babylon.blurPostProcess.js.map
  65549. var BABYLON;
  65550. (function (BABYLON) {
  65551. var Bone = /** @class */ (function (_super) {
  65552. __extends(Bone, _super);
  65553. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  65554. if (parentBone === void 0) { parentBone = null; }
  65555. if (localMatrix === void 0) { localMatrix = null; }
  65556. if (restPose === void 0) { restPose = null; }
  65557. if (baseMatrix === void 0) { baseMatrix = null; }
  65558. if (index === void 0) { index = null; }
  65559. var _this = _super.call(this, name, skeleton.getScene()) || this;
  65560. _this.name = name;
  65561. _this.children = new Array();
  65562. _this.animations = new Array();
  65563. // Set this value to map this bone to a different index in the transform matrices.
  65564. // Set this value to -1 to exclude the bone from the transform matrices.
  65565. _this._index = null;
  65566. _this._worldTransform = new BABYLON.Matrix();
  65567. _this._absoluteTransform = new BABYLON.Matrix();
  65568. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  65569. _this._scaleMatrix = BABYLON.Matrix.Identity();
  65570. _this._scaleVector = BABYLON.Vector3.One();
  65571. _this._negateScaleChildren = BABYLON.Vector3.One();
  65572. _this._scalingDeterminant = 1;
  65573. _this._skeleton = skeleton;
  65574. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  65575. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  65576. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  65577. _this._index = index;
  65578. skeleton.bones.push(_this);
  65579. _this.setParent(parentBone, false);
  65580. _this._updateDifferenceMatrix();
  65581. return _this;
  65582. }
  65583. Object.defineProperty(Bone.prototype, "_matrix", {
  65584. get: function () {
  65585. return this._localMatrix;
  65586. },
  65587. set: function (val) {
  65588. if (this._localMatrix) {
  65589. this._localMatrix.copyFrom(val);
  65590. }
  65591. else {
  65592. this._localMatrix = val;
  65593. }
  65594. },
  65595. enumerable: true,
  65596. configurable: true
  65597. });
  65598. // Members
  65599. Bone.prototype.getSkeleton = function () {
  65600. return this._skeleton;
  65601. };
  65602. Bone.prototype.getParent = function () {
  65603. return this._parent;
  65604. };
  65605. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  65606. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  65607. if (this._parent === parent) {
  65608. return;
  65609. }
  65610. if (this._parent) {
  65611. var index = this._parent.children.indexOf(this);
  65612. if (index !== -1) {
  65613. this._parent.children.splice(index, 1);
  65614. }
  65615. }
  65616. this._parent = parent;
  65617. if (this._parent) {
  65618. this._parent.children.push(this);
  65619. }
  65620. if (updateDifferenceMatrix) {
  65621. this._updateDifferenceMatrix();
  65622. }
  65623. };
  65624. Bone.prototype.getLocalMatrix = function () {
  65625. return this._localMatrix;
  65626. };
  65627. Bone.prototype.getBaseMatrix = function () {
  65628. return this._baseMatrix;
  65629. };
  65630. Bone.prototype.getRestPose = function () {
  65631. return this._restPose;
  65632. };
  65633. Bone.prototype.returnToRest = function () {
  65634. this.updateMatrix(this._restPose.clone());
  65635. };
  65636. Bone.prototype.getWorldMatrix = function () {
  65637. return this._worldTransform;
  65638. };
  65639. Bone.prototype.getInvertedAbsoluteTransform = function () {
  65640. return this._invertedAbsoluteTransform;
  65641. };
  65642. Bone.prototype.getAbsoluteTransform = function () {
  65643. return this._absoluteTransform;
  65644. };
  65645. Object.defineProperty(Bone.prototype, "position", {
  65646. // Properties (matches AbstractMesh properties)
  65647. get: function () {
  65648. return this.getPosition();
  65649. },
  65650. set: function (newPosition) {
  65651. this.setPosition(newPosition);
  65652. },
  65653. enumerable: true,
  65654. configurable: true
  65655. });
  65656. Object.defineProperty(Bone.prototype, "rotation", {
  65657. get: function () {
  65658. return this.getRotation();
  65659. },
  65660. set: function (newRotation) {
  65661. this.setRotation(newRotation);
  65662. },
  65663. enumerable: true,
  65664. configurable: true
  65665. });
  65666. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  65667. get: function () {
  65668. return this.getRotationQuaternion();
  65669. },
  65670. set: function (newRotation) {
  65671. this.setRotationQuaternion(newRotation);
  65672. },
  65673. enumerable: true,
  65674. configurable: true
  65675. });
  65676. Object.defineProperty(Bone.prototype, "scaling", {
  65677. get: function () {
  65678. return this.getScale();
  65679. },
  65680. set: function (newScaling) {
  65681. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  65682. },
  65683. enumerable: true,
  65684. configurable: true
  65685. });
  65686. // Methods
  65687. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  65688. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  65689. this._baseMatrix = matrix.clone();
  65690. this._localMatrix = matrix.clone();
  65691. this._skeleton._markAsDirty();
  65692. if (updateDifferenceMatrix) {
  65693. this._updateDifferenceMatrix();
  65694. }
  65695. };
  65696. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  65697. if (!rootMatrix) {
  65698. rootMatrix = this._baseMatrix;
  65699. }
  65700. if (this._parent) {
  65701. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  65702. }
  65703. else {
  65704. this._absoluteTransform.copyFrom(rootMatrix);
  65705. }
  65706. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  65707. for (var index = 0; index < this.children.length; index++) {
  65708. this.children[index]._updateDifferenceMatrix();
  65709. }
  65710. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  65711. };
  65712. Bone.prototype.markAsDirty = function () {
  65713. this._currentRenderId++;
  65714. this._skeleton._markAsDirty();
  65715. };
  65716. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  65717. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  65718. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  65719. // all animation may be coming from a library skeleton, so may need to create animation
  65720. if (this.animations.length === 0) {
  65721. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  65722. this.animations[0].setKeys([]);
  65723. }
  65724. // get animation info / verify there is such a range from the source bone
  65725. var sourceRange = source.animations[0].getRange(rangeName);
  65726. if (!sourceRange) {
  65727. return false;
  65728. }
  65729. var from = sourceRange.from;
  65730. var to = sourceRange.to;
  65731. var sourceKeys = source.animations[0].getKeys();
  65732. // rescaling prep
  65733. var sourceBoneLength = source.length;
  65734. var sourceParent = source.getParent();
  65735. var parent = this.getParent();
  65736. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  65737. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  65738. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  65739. var destKeys = this.animations[0].getKeys();
  65740. // loop vars declaration
  65741. var orig;
  65742. var origTranslation;
  65743. var mat;
  65744. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  65745. orig = sourceKeys[key];
  65746. if (orig.frame >= from && orig.frame <= to) {
  65747. if (rescaleAsRequired) {
  65748. mat = orig.value.clone();
  65749. // scale based on parent ratio, when bone has parent
  65750. if (parentScalingReqd) {
  65751. origTranslation = mat.getTranslation();
  65752. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  65753. // scale based on skeleton dimension ratio when root bone, and value is passed
  65754. }
  65755. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  65756. origTranslation = mat.getTranslation();
  65757. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  65758. // use original when root bone, and no data for skelDimensionsRatio
  65759. }
  65760. else {
  65761. mat = orig.value;
  65762. }
  65763. }
  65764. else {
  65765. mat = orig.value;
  65766. }
  65767. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  65768. }
  65769. }
  65770. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  65771. return true;
  65772. };
  65773. /**
  65774. * Translate the bone in local or world space.
  65775. * @param vec The amount to translate the bone.
  65776. * @param space The space that the translation is in.
  65777. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65778. */
  65779. Bone.prototype.translate = function (vec, space, mesh) {
  65780. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65781. var lm = this.getLocalMatrix();
  65782. if (space == BABYLON.Space.LOCAL) {
  65783. lm.m[12] += vec.x;
  65784. lm.m[13] += vec.y;
  65785. lm.m[14] += vec.z;
  65786. }
  65787. else {
  65788. var wm = null;
  65789. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65790. if (mesh) {
  65791. wm = mesh.getWorldMatrix();
  65792. }
  65793. this._skeleton.computeAbsoluteTransforms();
  65794. var tmat = Bone._tmpMats[0];
  65795. var tvec = Bone._tmpVecs[0];
  65796. if (this._parent) {
  65797. if (mesh && wm) {
  65798. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65799. tmat.multiplyToRef(wm, tmat);
  65800. }
  65801. else {
  65802. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65803. }
  65804. }
  65805. tmat.m[12] = 0;
  65806. tmat.m[13] = 0;
  65807. tmat.m[14] = 0;
  65808. tmat.invert();
  65809. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  65810. lm.m[12] += tvec.x;
  65811. lm.m[13] += tvec.y;
  65812. lm.m[14] += tvec.z;
  65813. }
  65814. this.markAsDirty();
  65815. };
  65816. /**
  65817. * Set the postion of the bone in local or world space.
  65818. * @param position The position to set the bone.
  65819. * @param space The space that the position is in.
  65820. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65821. */
  65822. Bone.prototype.setPosition = function (position, space, mesh) {
  65823. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65824. var lm = this.getLocalMatrix();
  65825. if (space == BABYLON.Space.LOCAL) {
  65826. lm.m[12] = position.x;
  65827. lm.m[13] = position.y;
  65828. lm.m[14] = position.z;
  65829. }
  65830. else {
  65831. var wm = null;
  65832. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65833. if (mesh) {
  65834. wm = mesh.getWorldMatrix();
  65835. }
  65836. this._skeleton.computeAbsoluteTransforms();
  65837. var tmat = Bone._tmpMats[0];
  65838. var vec = Bone._tmpVecs[0];
  65839. if (this._parent) {
  65840. if (mesh && wm) {
  65841. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65842. tmat.multiplyToRef(wm, tmat);
  65843. }
  65844. else {
  65845. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65846. }
  65847. }
  65848. tmat.invert();
  65849. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  65850. lm.m[12] = vec.x;
  65851. lm.m[13] = vec.y;
  65852. lm.m[14] = vec.z;
  65853. }
  65854. this.markAsDirty();
  65855. };
  65856. /**
  65857. * Set the absolute postion of the bone (world space).
  65858. * @param position The position to set the bone.
  65859. * @param mesh The mesh that this bone is attached to.
  65860. */
  65861. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  65862. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  65863. };
  65864. /**
  65865. * Set the scale of the bone on the x, y and z axes.
  65866. * @param x The scale of the bone on the x axis.
  65867. * @param x The scale of the bone on the y axis.
  65868. * @param z The scale of the bone on the z axis.
  65869. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65870. */
  65871. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  65872. if (scaleChildren === void 0) { scaleChildren = false; }
  65873. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  65874. if (!scaleChildren) {
  65875. this._negateScaleChildren.x = 1 / x;
  65876. this._negateScaleChildren.y = 1 / y;
  65877. this._negateScaleChildren.z = 1 / z;
  65878. }
  65879. this._syncScaleVector();
  65880. }
  65881. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  65882. };
  65883. /**
  65884. * Scale the bone on the x, y and z axes.
  65885. * @param x The amount to scale the bone on the x axis.
  65886. * @param x The amount to scale the bone on the y axis.
  65887. * @param z The amount to scale the bone on the z axis.
  65888. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65889. */
  65890. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  65891. if (scaleChildren === void 0) { scaleChildren = false; }
  65892. var locMat = this.getLocalMatrix();
  65893. var origLocMat = Bone._tmpMats[0];
  65894. origLocMat.copyFrom(locMat);
  65895. var origLocMatInv = Bone._tmpMats[1];
  65896. origLocMatInv.copyFrom(origLocMat);
  65897. origLocMatInv.invert();
  65898. var scaleMat = Bone._tmpMats[2];
  65899. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  65900. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  65901. this._scaleVector.x *= x;
  65902. this._scaleVector.y *= y;
  65903. this._scaleVector.z *= z;
  65904. locMat.multiplyToRef(origLocMatInv, locMat);
  65905. locMat.multiplyToRef(scaleMat, locMat);
  65906. locMat.multiplyToRef(origLocMat, locMat);
  65907. var parent = this.getParent();
  65908. if (parent) {
  65909. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  65910. }
  65911. else {
  65912. this.getAbsoluteTransform().copyFrom(locMat);
  65913. }
  65914. var len = this.children.length;
  65915. scaleMat.invert();
  65916. for (var i = 0; i < len; i++) {
  65917. var child = this.children[i];
  65918. var cm = child.getLocalMatrix();
  65919. cm.multiplyToRef(scaleMat, cm);
  65920. var lm = child.getLocalMatrix();
  65921. lm.m[12] *= x;
  65922. lm.m[13] *= y;
  65923. lm.m[14] *= z;
  65924. }
  65925. this.computeAbsoluteTransforms();
  65926. if (scaleChildren) {
  65927. for (var i = 0; i < len; i++) {
  65928. this.children[i].scale(x, y, z, scaleChildren);
  65929. }
  65930. }
  65931. this.markAsDirty();
  65932. };
  65933. /**
  65934. * Set the yaw, pitch, and roll of the bone in local or world space.
  65935. * @param yaw The rotation of the bone on the y axis.
  65936. * @param pitch The rotation of the bone on the x axis.
  65937. * @param roll The rotation of the bone on the z axis.
  65938. * @param space The space that the axes of rotation are in.
  65939. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65940. */
  65941. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  65942. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65943. var rotMat = Bone._tmpMats[0];
  65944. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  65945. var rotMatInv = Bone._tmpMats[1];
  65946. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65947. rotMatInv.multiplyToRef(rotMat, rotMat);
  65948. this._rotateWithMatrix(rotMat, space, mesh);
  65949. };
  65950. /**
  65951. * Rotate the bone on an axis in local or world space.
  65952. * @param axis The axis to rotate the bone on.
  65953. * @param amount The amount to rotate the bone.
  65954. * @param space The space that the axis is in.
  65955. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65956. */
  65957. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  65958. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65959. var rmat = Bone._tmpMats[0];
  65960. rmat.m[12] = 0;
  65961. rmat.m[13] = 0;
  65962. rmat.m[14] = 0;
  65963. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  65964. this._rotateWithMatrix(rmat, space, mesh);
  65965. };
  65966. /**
  65967. * Set the rotation of the bone to a particular axis angle in local or world space.
  65968. * @param axis The axis to rotate the bone on.
  65969. * @param angle The angle that the bone should be rotated to.
  65970. * @param space The space that the axis is in.
  65971. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65972. */
  65973. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  65974. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65975. var rotMat = Bone._tmpMats[0];
  65976. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  65977. var rotMatInv = Bone._tmpMats[1];
  65978. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65979. rotMatInv.multiplyToRef(rotMat, rotMat);
  65980. this._rotateWithMatrix(rotMat, space, mesh);
  65981. };
  65982. /**
  65983. * Set the euler rotation of the bone in local of world space.
  65984. * @param rotation The euler rotation that the bone should be set to.
  65985. * @param space The space that the rotation is in.
  65986. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65987. */
  65988. Bone.prototype.setRotation = function (rotation, space, mesh) {
  65989. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65990. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  65991. };
  65992. /**
  65993. * Set the quaternion rotation of the bone in local of world space.
  65994. * @param quat The quaternion rotation that the bone should be set to.
  65995. * @param space The space that the rotation is in.
  65996. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65997. */
  65998. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  65999. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66000. var rotMatInv = Bone._tmpMats[0];
  66001. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66002. var rotMat = Bone._tmpMats[1];
  66003. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  66004. rotMatInv.multiplyToRef(rotMat, rotMat);
  66005. this._rotateWithMatrix(rotMat, space, mesh);
  66006. };
  66007. /**
  66008. * Set the rotation matrix of the bone in local of world space.
  66009. * @param rotMat The rotation matrix that the bone should be set to.
  66010. * @param space The space that the rotation is in.
  66011. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66012. */
  66013. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  66014. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66015. var rotMatInv = Bone._tmpMats[0];
  66016. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  66017. var rotMat2 = Bone._tmpMats[1];
  66018. rotMat2.copyFrom(rotMat);
  66019. rotMatInv.multiplyToRef(rotMat, rotMat2);
  66020. this._rotateWithMatrix(rotMat2, space, mesh);
  66021. };
  66022. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  66023. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66024. var lmat = this.getLocalMatrix();
  66025. var lx = lmat.m[12];
  66026. var ly = lmat.m[13];
  66027. var lz = lmat.m[14];
  66028. var parent = this.getParent();
  66029. var parentScale = Bone._tmpMats[3];
  66030. var parentScaleInv = Bone._tmpMats[4];
  66031. if (parent) {
  66032. if (space == BABYLON.Space.WORLD) {
  66033. if (mesh) {
  66034. parentScale.copyFrom(mesh.getWorldMatrix());
  66035. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  66036. }
  66037. else {
  66038. parentScale.copyFrom(parent.getAbsoluteTransform());
  66039. }
  66040. }
  66041. else {
  66042. parentScale = parent._scaleMatrix;
  66043. }
  66044. parentScaleInv.copyFrom(parentScale);
  66045. parentScaleInv.invert();
  66046. lmat.multiplyToRef(parentScale, lmat);
  66047. lmat.multiplyToRef(rmat, lmat);
  66048. lmat.multiplyToRef(parentScaleInv, lmat);
  66049. }
  66050. else {
  66051. if (space == BABYLON.Space.WORLD && mesh) {
  66052. parentScale.copyFrom(mesh.getWorldMatrix());
  66053. parentScaleInv.copyFrom(parentScale);
  66054. parentScaleInv.invert();
  66055. lmat.multiplyToRef(parentScale, lmat);
  66056. lmat.multiplyToRef(rmat, lmat);
  66057. lmat.multiplyToRef(parentScaleInv, lmat);
  66058. }
  66059. else {
  66060. lmat.multiplyToRef(rmat, lmat);
  66061. }
  66062. }
  66063. lmat.m[12] = lx;
  66064. lmat.m[13] = ly;
  66065. lmat.m[14] = lz;
  66066. this.computeAbsoluteTransforms();
  66067. this.markAsDirty();
  66068. };
  66069. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  66070. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66071. if (space == BABYLON.Space.WORLD) {
  66072. var scaleMatrix = Bone._tmpMats[2];
  66073. scaleMatrix.copyFrom(this._scaleMatrix);
  66074. rotMatInv.copyFrom(this.getAbsoluteTransform());
  66075. if (mesh) {
  66076. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  66077. var meshScale = Bone._tmpMats[3];
  66078. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  66079. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  66080. }
  66081. rotMatInv.invert();
  66082. scaleMatrix.m[0] *= this._scalingDeterminant;
  66083. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  66084. }
  66085. else {
  66086. rotMatInv.copyFrom(this.getLocalMatrix());
  66087. rotMatInv.invert();
  66088. var scaleMatrix = Bone._tmpMats[2];
  66089. scaleMatrix.copyFrom(this._scaleMatrix);
  66090. if (this._parent) {
  66091. var pscaleMatrix = Bone._tmpMats[3];
  66092. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  66093. pscaleMatrix.invert();
  66094. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  66095. }
  66096. else {
  66097. scaleMatrix.m[0] *= this._scalingDeterminant;
  66098. }
  66099. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  66100. }
  66101. };
  66102. /**
  66103. * Get the scale of the bone
  66104. * @returns the scale of the bone
  66105. */
  66106. Bone.prototype.getScale = function () {
  66107. return this._scaleVector.clone();
  66108. };
  66109. /**
  66110. * Copy the scale of the bone to a vector3.
  66111. * @param result The vector3 to copy the scale to
  66112. */
  66113. Bone.prototype.getScaleToRef = function (result) {
  66114. result.copyFrom(this._scaleVector);
  66115. };
  66116. /**
  66117. * Get the position of the bone in local or world space.
  66118. * @param space The space that the returned position is in.
  66119. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66120. * @returns The position of the bone
  66121. */
  66122. Bone.prototype.getPosition = function (space, mesh) {
  66123. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66124. if (mesh === void 0) { mesh = null; }
  66125. var pos = BABYLON.Vector3.Zero();
  66126. this.getPositionToRef(space, mesh, pos);
  66127. return pos;
  66128. };
  66129. /**
  66130. * Copy the position of the bone to a vector3 in local or world space.
  66131. * @param space The space that the returned position is in.
  66132. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66133. * @param result The vector3 to copy the position to.
  66134. */
  66135. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  66136. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66137. if (space == BABYLON.Space.LOCAL) {
  66138. var lm = this.getLocalMatrix();
  66139. result.x = lm.m[12];
  66140. result.y = lm.m[13];
  66141. result.z = lm.m[14];
  66142. }
  66143. else {
  66144. var wm = null;
  66145. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66146. if (mesh) {
  66147. wm = mesh.getWorldMatrix();
  66148. }
  66149. this._skeleton.computeAbsoluteTransforms();
  66150. var tmat = Bone._tmpMats[0];
  66151. if (mesh && wm) {
  66152. tmat.copyFrom(this.getAbsoluteTransform());
  66153. tmat.multiplyToRef(wm, tmat);
  66154. }
  66155. else {
  66156. tmat = this.getAbsoluteTransform();
  66157. }
  66158. result.x = tmat.m[12];
  66159. result.y = tmat.m[13];
  66160. result.z = tmat.m[14];
  66161. }
  66162. };
  66163. /**
  66164. * Get the absolute position of the bone (world space).
  66165. * @param mesh The mesh that this bone is attached to.
  66166. * @returns The absolute position of the bone
  66167. */
  66168. Bone.prototype.getAbsolutePosition = function (mesh) {
  66169. if (mesh === void 0) { mesh = null; }
  66170. var pos = BABYLON.Vector3.Zero();
  66171. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  66172. return pos;
  66173. };
  66174. /**
  66175. * Copy the absolute position of the bone (world space) to the result param.
  66176. * @param mesh The mesh that this bone is attached to.
  66177. * @param result The vector3 to copy the absolute position to.
  66178. */
  66179. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  66180. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  66181. };
  66182. /**
  66183. * Compute the absolute transforms of this bone and its children.
  66184. */
  66185. Bone.prototype.computeAbsoluteTransforms = function () {
  66186. if (this._parent) {
  66187. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  66188. }
  66189. else {
  66190. this._absoluteTransform.copyFrom(this._localMatrix);
  66191. var poseMatrix = this._skeleton.getPoseMatrix();
  66192. if (poseMatrix) {
  66193. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  66194. }
  66195. }
  66196. var children = this.children;
  66197. var len = children.length;
  66198. for (var i = 0; i < len; i++) {
  66199. children[i].computeAbsoluteTransforms();
  66200. }
  66201. };
  66202. Bone.prototype._syncScaleVector = function () {
  66203. var lm = this.getLocalMatrix();
  66204. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  66205. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  66206. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  66207. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  66208. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  66209. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  66210. this._scaleVector.x = xs * Math.sqrt(xsq);
  66211. this._scaleVector.y = ys * Math.sqrt(ysq);
  66212. this._scaleVector.z = zs * Math.sqrt(zsq);
  66213. if (this._parent) {
  66214. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  66215. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  66216. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  66217. }
  66218. 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);
  66219. };
  66220. /**
  66221. * Get the world direction from an axis that is in the local space of the bone.
  66222. * @param localAxis The local direction that is used to compute the world direction.
  66223. * @param mesh The mesh that this bone is attached to.
  66224. * @returns The world direction
  66225. */
  66226. Bone.prototype.getDirection = function (localAxis, mesh) {
  66227. if (mesh === void 0) { mesh = null; }
  66228. var result = BABYLON.Vector3.Zero();
  66229. this.getDirectionToRef(localAxis, mesh, result);
  66230. return result;
  66231. };
  66232. /**
  66233. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  66234. * @param localAxis The local direction that is used to compute the world direction.
  66235. * @param mesh The mesh that this bone is attached to.
  66236. * @param result The vector3 that the world direction will be copied to.
  66237. */
  66238. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  66239. if (mesh === void 0) { mesh = null; }
  66240. var wm = null;
  66241. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66242. if (mesh) {
  66243. wm = mesh.getWorldMatrix();
  66244. }
  66245. this._skeleton.computeAbsoluteTransforms();
  66246. var mat = Bone._tmpMats[0];
  66247. mat.copyFrom(this.getAbsoluteTransform());
  66248. if (mesh && wm) {
  66249. mat.multiplyToRef(wm, mat);
  66250. }
  66251. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  66252. result.normalize();
  66253. };
  66254. /**
  66255. * Get the euler rotation of the bone in local or world space.
  66256. * @param space The space that the rotation should be in.
  66257. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66258. * @returns The euler rotation
  66259. */
  66260. Bone.prototype.getRotation = function (space, mesh) {
  66261. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66262. if (mesh === void 0) { mesh = null; }
  66263. var result = BABYLON.Vector3.Zero();
  66264. this.getRotationToRef(space, mesh, result);
  66265. return result;
  66266. };
  66267. /**
  66268. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  66269. * @param space The space that the rotation should be in.
  66270. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66271. * @param result The vector3 that the rotation should be copied to.
  66272. */
  66273. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  66274. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66275. if (mesh === void 0) { mesh = null; }
  66276. var quat = Bone._tmpQuat;
  66277. this.getRotationQuaternionToRef(space, mesh, quat);
  66278. quat.toEulerAnglesToRef(result);
  66279. };
  66280. /**
  66281. * Get the quaternion rotation of the bone in either local or world space.
  66282. * @param space The space that the rotation should be in.
  66283. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66284. * @returns The quaternion rotation
  66285. */
  66286. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  66287. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66288. if (mesh === void 0) { mesh = null; }
  66289. var result = BABYLON.Quaternion.Identity();
  66290. this.getRotationQuaternionToRef(space, mesh, result);
  66291. return result;
  66292. };
  66293. /**
  66294. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  66295. * @param space The space that the rotation should be in.
  66296. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66297. * @param result The quaternion that the rotation should be copied to.
  66298. */
  66299. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  66300. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66301. if (mesh === void 0) { mesh = null; }
  66302. if (space == BABYLON.Space.LOCAL) {
  66303. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  66304. }
  66305. else {
  66306. var mat = Bone._tmpMats[0];
  66307. var amat = this.getAbsoluteTransform();
  66308. if (mesh) {
  66309. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  66310. }
  66311. else {
  66312. mat.copyFrom(amat);
  66313. }
  66314. mat.m[0] *= this._scalingDeterminant;
  66315. mat.m[1] *= this._scalingDeterminant;
  66316. mat.m[2] *= this._scalingDeterminant;
  66317. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  66318. }
  66319. };
  66320. /**
  66321. * Get the rotation matrix of the bone in local or world space.
  66322. * @param space The space that the rotation should be in.
  66323. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66324. * @returns The rotation matrix
  66325. */
  66326. Bone.prototype.getRotationMatrix = function (space, mesh) {
  66327. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66328. var result = BABYLON.Matrix.Identity();
  66329. this.getRotationMatrixToRef(space, mesh, result);
  66330. return result;
  66331. };
  66332. /**
  66333. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  66334. * @param space The space that the rotation should be in.
  66335. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66336. * @param result The quaternion that the rotation should be copied to.
  66337. */
  66338. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  66339. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66340. if (space == BABYLON.Space.LOCAL) {
  66341. this.getLocalMatrix().getRotationMatrixToRef(result);
  66342. }
  66343. else {
  66344. var mat = Bone._tmpMats[0];
  66345. var amat = this.getAbsoluteTransform();
  66346. if (mesh) {
  66347. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  66348. }
  66349. else {
  66350. mat.copyFrom(amat);
  66351. }
  66352. mat.m[0] *= this._scalingDeterminant;
  66353. mat.m[1] *= this._scalingDeterminant;
  66354. mat.m[2] *= this._scalingDeterminant;
  66355. mat.getRotationMatrixToRef(result);
  66356. }
  66357. };
  66358. /**
  66359. * Get the world position of a point that is in the local space of the bone.
  66360. * @param position The local position
  66361. * @param mesh The mesh that this bone is attached to.
  66362. * @returns The world position
  66363. */
  66364. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  66365. if (mesh === void 0) { mesh = null; }
  66366. var result = BABYLON.Vector3.Zero();
  66367. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  66368. return result;
  66369. };
  66370. /**
  66371. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  66372. * @param position The local position
  66373. * @param mesh The mesh that this bone is attached to.
  66374. * @param result The vector3 that the world position should be copied to.
  66375. */
  66376. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  66377. if (mesh === void 0) { mesh = null; }
  66378. var wm = null;
  66379. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66380. if (mesh) {
  66381. wm = mesh.getWorldMatrix();
  66382. }
  66383. this._skeleton.computeAbsoluteTransforms();
  66384. var tmat = Bone._tmpMats[0];
  66385. if (mesh && wm) {
  66386. tmat.copyFrom(this.getAbsoluteTransform());
  66387. tmat.multiplyToRef(wm, tmat);
  66388. }
  66389. else {
  66390. tmat = this.getAbsoluteTransform();
  66391. }
  66392. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  66393. };
  66394. /**
  66395. * Get the local position of a point that is in world space.
  66396. * @param position The world position
  66397. * @param mesh The mesh that this bone is attached to.
  66398. * @returns The local position
  66399. */
  66400. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  66401. if (mesh === void 0) { mesh = null; }
  66402. var result = BABYLON.Vector3.Zero();
  66403. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  66404. return result;
  66405. };
  66406. /**
  66407. * Get the local position of a point that is in world space and copy it to the result param.
  66408. * @param position The world position
  66409. * @param mesh The mesh that this bone is attached to.
  66410. * @param result The vector3 that the local position should be copied to.
  66411. */
  66412. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  66413. if (mesh === void 0) { mesh = null; }
  66414. var wm = null;
  66415. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66416. if (mesh) {
  66417. wm = mesh.getWorldMatrix();
  66418. }
  66419. this._skeleton.computeAbsoluteTransforms();
  66420. var tmat = Bone._tmpMats[0];
  66421. tmat.copyFrom(this.getAbsoluteTransform());
  66422. if (mesh && wm) {
  66423. tmat.multiplyToRef(wm, tmat);
  66424. }
  66425. tmat.invert();
  66426. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  66427. };
  66428. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66429. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  66430. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66431. return Bone;
  66432. }(BABYLON.Node));
  66433. BABYLON.Bone = Bone;
  66434. })(BABYLON || (BABYLON = {}));
  66435. //# sourceMappingURL=babylon.bone.js.map
  66436. var BABYLON;
  66437. (function (BABYLON) {
  66438. var BoneIKController = /** @class */ (function () {
  66439. function BoneIKController(mesh, bone, options) {
  66440. this.targetPosition = BABYLON.Vector3.Zero();
  66441. this.poleTargetPosition = BABYLON.Vector3.Zero();
  66442. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  66443. this.poleAngle = 0;
  66444. this.slerpAmount = 1;
  66445. this._bone1Quat = BABYLON.Quaternion.Identity();
  66446. this._bone1Mat = BABYLON.Matrix.Identity();
  66447. this._bone2Ang = Math.PI;
  66448. this._maxAngle = Math.PI;
  66449. this._rightHandedSystem = false;
  66450. this._bendAxis = BABYLON.Vector3.Right();
  66451. this._slerping = false;
  66452. this._adjustRoll = 0;
  66453. this._bone2 = bone;
  66454. this._bone1 = bone.getParent();
  66455. if (!this._bone1) {
  66456. return;
  66457. }
  66458. this.mesh = mesh;
  66459. var bonePos = bone.getPosition();
  66460. if (bone.getAbsoluteTransform().determinant() > 0) {
  66461. this._rightHandedSystem = true;
  66462. this._bendAxis.x = 0;
  66463. this._bendAxis.y = 0;
  66464. this._bendAxis.z = -1;
  66465. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  66466. this._adjustRoll = Math.PI * .5;
  66467. this._bendAxis.z = 1;
  66468. }
  66469. }
  66470. if (this._bone1.length) {
  66471. var boneScale1 = this._bone1.getScale();
  66472. var boneScale2 = this._bone2.getScale();
  66473. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  66474. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  66475. }
  66476. else if (this._bone1.children[0]) {
  66477. mesh.computeWorldMatrix(true);
  66478. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  66479. var pos2 = this._bone2.getAbsolutePosition(mesh);
  66480. var pos3 = this._bone1.getAbsolutePosition(mesh);
  66481. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  66482. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  66483. }
  66484. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  66485. this.maxAngle = Math.PI;
  66486. if (options) {
  66487. if (options.targetMesh) {
  66488. this.targetMesh = options.targetMesh;
  66489. this.targetMesh.computeWorldMatrix(true);
  66490. }
  66491. if (options.poleTargetMesh) {
  66492. this.poleTargetMesh = options.poleTargetMesh;
  66493. this.poleTargetMesh.computeWorldMatrix(true);
  66494. }
  66495. else if (options.poleTargetBone) {
  66496. this.poleTargetBone = options.poleTargetBone;
  66497. }
  66498. else if (this._bone1.getParent()) {
  66499. this.poleTargetBone = this._bone1.getParent();
  66500. }
  66501. if (options.poleTargetLocalOffset) {
  66502. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  66503. }
  66504. if (options.poleAngle) {
  66505. this.poleAngle = options.poleAngle;
  66506. }
  66507. if (options.bendAxis) {
  66508. this._bendAxis.copyFrom(options.bendAxis);
  66509. }
  66510. if (options.maxAngle) {
  66511. this.maxAngle = options.maxAngle;
  66512. }
  66513. if (options.slerpAmount) {
  66514. this.slerpAmount = options.slerpAmount;
  66515. }
  66516. }
  66517. }
  66518. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  66519. get: function () {
  66520. return this._maxAngle;
  66521. },
  66522. set: function (value) {
  66523. this._setMaxAngle(value);
  66524. },
  66525. enumerable: true,
  66526. configurable: true
  66527. });
  66528. BoneIKController.prototype._setMaxAngle = function (ang) {
  66529. if (ang < 0) {
  66530. ang = 0;
  66531. }
  66532. if (ang > Math.PI || ang == undefined) {
  66533. ang = Math.PI;
  66534. }
  66535. this._maxAngle = ang;
  66536. var a = this._bone1Length;
  66537. var b = this._bone2Length;
  66538. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  66539. };
  66540. BoneIKController.prototype.update = function () {
  66541. var bone1 = this._bone1;
  66542. if (!bone1) {
  66543. return;
  66544. }
  66545. var target = this.targetPosition;
  66546. var poleTarget = this.poleTargetPosition;
  66547. var mat1 = BoneIKController._tmpMats[0];
  66548. var mat2 = BoneIKController._tmpMats[1];
  66549. if (this.targetMesh) {
  66550. target.copyFrom(this.targetMesh.getAbsolutePosition());
  66551. }
  66552. if (this.poleTargetBone) {
  66553. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  66554. }
  66555. else if (this.poleTargetMesh) {
  66556. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  66557. }
  66558. var bonePos = BoneIKController._tmpVecs[0];
  66559. var zaxis = BoneIKController._tmpVecs[1];
  66560. var xaxis = BoneIKController._tmpVecs[2];
  66561. var yaxis = BoneIKController._tmpVecs[3];
  66562. var upAxis = BoneIKController._tmpVecs[4];
  66563. var _tmpQuat = BoneIKController._tmpQuat;
  66564. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  66565. poleTarget.subtractToRef(bonePos, upAxis);
  66566. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  66567. upAxis.y = 1;
  66568. }
  66569. else {
  66570. upAxis.normalize();
  66571. }
  66572. target.subtractToRef(bonePos, yaxis);
  66573. yaxis.normalize();
  66574. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  66575. zaxis.normalize();
  66576. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  66577. xaxis.normalize();
  66578. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  66579. var a = this._bone1Length;
  66580. var b = this._bone2Length;
  66581. var c = BABYLON.Vector3.Distance(bonePos, target);
  66582. if (this._maxReach > 0) {
  66583. c = Math.min(this._maxReach, c);
  66584. }
  66585. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  66586. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  66587. if (acosa > 1) {
  66588. acosa = 1;
  66589. }
  66590. if (acosb > 1) {
  66591. acosb = 1;
  66592. }
  66593. if (acosa < -1) {
  66594. acosa = -1;
  66595. }
  66596. if (acosb < -1) {
  66597. acosb = -1;
  66598. }
  66599. var angA = Math.acos(acosa);
  66600. var angB = Math.acos(acosb);
  66601. var angC = -angA - angB;
  66602. if (this._rightHandedSystem) {
  66603. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  66604. mat2.multiplyToRef(mat1, mat1);
  66605. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  66606. mat2.multiplyToRef(mat1, mat1);
  66607. }
  66608. else {
  66609. var _tmpVec = BoneIKController._tmpVecs[5];
  66610. _tmpVec.copyFrom(this._bendAxis);
  66611. _tmpVec.x *= -1;
  66612. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  66613. mat2.multiplyToRef(mat1, mat1);
  66614. }
  66615. if (this.poleAngle) {
  66616. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  66617. mat1.multiplyToRef(mat2, mat1);
  66618. }
  66619. if (this._bone1) {
  66620. if (this.slerpAmount < 1) {
  66621. if (!this._slerping) {
  66622. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  66623. }
  66624. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  66625. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  66626. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  66627. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  66628. this._slerping = true;
  66629. }
  66630. else {
  66631. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  66632. this._bone1Mat.copyFrom(mat1);
  66633. this._slerping = false;
  66634. }
  66635. }
  66636. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  66637. this._bone2Ang = angC;
  66638. };
  66639. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66640. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  66641. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66642. return BoneIKController;
  66643. }());
  66644. BABYLON.BoneIKController = BoneIKController;
  66645. })(BABYLON || (BABYLON = {}));
  66646. //# sourceMappingURL=babylon.boneIKController.js.map
  66647. var BABYLON;
  66648. (function (BABYLON) {
  66649. var BoneLookController = /** @class */ (function () {
  66650. /**
  66651. * Create a BoneLookController
  66652. * @param mesh the mesh that the bone belongs to
  66653. * @param bone the bone that will be looking to the target
  66654. * @param target the target Vector3 to look at
  66655. * @param settings optional settings:
  66656. * - maxYaw: the maximum angle the bone will yaw to
  66657. * - minYaw: the minimum angle the bone will yaw to
  66658. * - maxPitch: the maximum angle the bone will pitch to
  66659. * - minPitch: the minimum angle the bone will yaw to
  66660. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  66661. * - upAxis: the up axis of the coordinate system
  66662. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  66663. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  66664. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  66665. * - adjustYaw: used to make an adjustment to the yaw of the bone
  66666. * - adjustPitch: used to make an adjustment to the pitch of the bone
  66667. * - adjustRoll: used to make an adjustment to the roll of the bone
  66668. **/
  66669. function BoneLookController(mesh, bone, target, options) {
  66670. /**
  66671. * The up axis of the coordinate system that is used when the bone is rotated.
  66672. */
  66673. this.upAxis = BABYLON.Vector3.Up();
  66674. /**
  66675. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  66676. */
  66677. this.upAxisSpace = BABYLON.Space.LOCAL;
  66678. /**
  66679. * Used to make an adjustment to the yaw of the bone.
  66680. */
  66681. this.adjustYaw = 0;
  66682. /**
  66683. * Used to make an adjustment to the pitch of the bone.
  66684. */
  66685. this.adjustPitch = 0;
  66686. /**
  66687. * Used to make an adjustment to the roll of the bone.
  66688. */
  66689. this.adjustRoll = 0;
  66690. /**
  66691. * 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).
  66692. */
  66693. this.slerpAmount = 1;
  66694. this._boneQuat = BABYLON.Quaternion.Identity();
  66695. this._slerping = false;
  66696. this._firstFrameSkipped = false;
  66697. this._fowardAxis = BABYLON.Vector3.Forward();
  66698. this.mesh = mesh;
  66699. this.bone = bone;
  66700. this.target = target;
  66701. if (options) {
  66702. if (options.adjustYaw) {
  66703. this.adjustYaw = options.adjustYaw;
  66704. }
  66705. if (options.adjustPitch) {
  66706. this.adjustPitch = options.adjustPitch;
  66707. }
  66708. if (options.adjustRoll) {
  66709. this.adjustRoll = options.adjustRoll;
  66710. }
  66711. if (options.maxYaw != null) {
  66712. this.maxYaw = options.maxYaw;
  66713. }
  66714. else {
  66715. this.maxYaw = Math.PI;
  66716. }
  66717. if (options.minYaw != null) {
  66718. this.minYaw = options.minYaw;
  66719. }
  66720. else {
  66721. this.minYaw = -Math.PI;
  66722. }
  66723. if (options.maxPitch != null) {
  66724. this.maxPitch = options.maxPitch;
  66725. }
  66726. else {
  66727. this.maxPitch = Math.PI;
  66728. }
  66729. if (options.minPitch != null) {
  66730. this.minPitch = options.minPitch;
  66731. }
  66732. else {
  66733. this.minPitch = -Math.PI;
  66734. }
  66735. if (options.slerpAmount != null) {
  66736. this.slerpAmount = options.slerpAmount;
  66737. }
  66738. if (options.upAxis != null) {
  66739. this.upAxis = options.upAxis;
  66740. }
  66741. if (options.upAxisSpace != null) {
  66742. this.upAxisSpace = options.upAxisSpace;
  66743. }
  66744. if (options.yawAxis != null || options.pitchAxis != null) {
  66745. var newYawAxis = BABYLON.Axis.Y;
  66746. var newPitchAxis = BABYLON.Axis.X;
  66747. if (options.yawAxis != null) {
  66748. newYawAxis = options.yawAxis.clone();
  66749. newYawAxis.normalize();
  66750. }
  66751. if (options.pitchAxis != null) {
  66752. newPitchAxis = options.pitchAxis.clone();
  66753. newPitchAxis.normalize();
  66754. }
  66755. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  66756. this._transformYawPitch = BABYLON.Matrix.Identity();
  66757. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  66758. this._transformYawPitchInv = this._transformYawPitch.clone();
  66759. this._transformYawPitch.invert();
  66760. }
  66761. }
  66762. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  66763. this.upAxisSpace = BABYLON.Space.LOCAL;
  66764. }
  66765. }
  66766. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  66767. /**
  66768. * Get/set the minimum yaw angle that the bone can look to.
  66769. */
  66770. get: function () {
  66771. return this._minYaw;
  66772. },
  66773. set: function (value) {
  66774. this._minYaw = value;
  66775. this._minYawSin = Math.sin(value);
  66776. this._minYawCos = Math.cos(value);
  66777. if (this._maxYaw != null) {
  66778. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66779. this._yawRange = this._maxYaw - this._minYaw;
  66780. }
  66781. },
  66782. enumerable: true,
  66783. configurable: true
  66784. });
  66785. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  66786. /**
  66787. * Get/set the maximum yaw angle that the bone can look to.
  66788. */
  66789. get: function () {
  66790. return this._maxYaw;
  66791. },
  66792. set: function (value) {
  66793. this._maxYaw = value;
  66794. this._maxYawSin = Math.sin(value);
  66795. this._maxYawCos = Math.cos(value);
  66796. if (this._minYaw != null) {
  66797. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66798. this._yawRange = this._maxYaw - this._minYaw;
  66799. }
  66800. },
  66801. enumerable: true,
  66802. configurable: true
  66803. });
  66804. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  66805. /**
  66806. * Get/set the minimum pitch angle that the bone can look to.
  66807. */
  66808. get: function () {
  66809. return this._minPitch;
  66810. },
  66811. set: function (value) {
  66812. this._minPitch = value;
  66813. this._minPitchTan = Math.tan(value);
  66814. },
  66815. enumerable: true,
  66816. configurable: true
  66817. });
  66818. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  66819. /**
  66820. * Get/set the maximum pitch angle that the bone can look to.
  66821. */
  66822. get: function () {
  66823. return this._maxPitch;
  66824. },
  66825. set: function (value) {
  66826. this._maxPitch = value;
  66827. this._maxPitchTan = Math.tan(value);
  66828. },
  66829. enumerable: true,
  66830. configurable: true
  66831. });
  66832. /**
  66833. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  66834. */
  66835. BoneLookController.prototype.update = function () {
  66836. //skip the first frame when slerping so that the mesh rotation is correct
  66837. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  66838. this._firstFrameSkipped = true;
  66839. return;
  66840. }
  66841. var bone = this.bone;
  66842. var bonePos = BoneLookController._tmpVecs[0];
  66843. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  66844. var target = this.target;
  66845. var _tmpMat1 = BoneLookController._tmpMats[0];
  66846. var _tmpMat2 = BoneLookController._tmpMats[1];
  66847. var mesh = this.mesh;
  66848. var parentBone = bone.getParent();
  66849. var upAxis = BoneLookController._tmpVecs[1];
  66850. upAxis.copyFrom(this.upAxis);
  66851. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  66852. if (this._transformYawPitch) {
  66853. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  66854. }
  66855. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  66856. }
  66857. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  66858. mesh.getDirectionToRef(upAxis, upAxis);
  66859. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  66860. upAxis.normalize();
  66861. }
  66862. }
  66863. var checkYaw = false;
  66864. var checkPitch = false;
  66865. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  66866. checkYaw = true;
  66867. }
  66868. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  66869. checkPitch = true;
  66870. }
  66871. if (checkYaw || checkPitch) {
  66872. var spaceMat = BoneLookController._tmpMats[2];
  66873. var spaceMatInv = BoneLookController._tmpMats[3];
  66874. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  66875. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  66876. }
  66877. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  66878. spaceMat.copyFrom(mesh.getWorldMatrix());
  66879. }
  66880. else {
  66881. var forwardAxis = BoneLookController._tmpVecs[2];
  66882. forwardAxis.copyFrom(this._fowardAxis);
  66883. if (this._transformYawPitch) {
  66884. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  66885. }
  66886. if (parentBone) {
  66887. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  66888. }
  66889. else {
  66890. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  66891. }
  66892. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  66893. rightAxis.normalize();
  66894. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  66895. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  66896. }
  66897. spaceMat.invertToRef(spaceMatInv);
  66898. var xzlen = null;
  66899. if (checkPitch) {
  66900. var localTarget = BoneLookController._tmpVecs[3];
  66901. target.subtractToRef(bonePos, localTarget);
  66902. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66903. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66904. var pitch = Math.atan2(localTarget.y, xzlen);
  66905. var newPitch = pitch;
  66906. if (pitch > this._maxPitch) {
  66907. localTarget.y = this._maxPitchTan * xzlen;
  66908. newPitch = this._maxPitch;
  66909. }
  66910. else if (pitch < this._minPitch) {
  66911. localTarget.y = this._minPitchTan * xzlen;
  66912. newPitch = this._minPitch;
  66913. }
  66914. if (pitch != newPitch) {
  66915. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66916. localTarget.addInPlace(bonePos);
  66917. target = localTarget;
  66918. }
  66919. }
  66920. if (checkYaw) {
  66921. var localTarget = BoneLookController._tmpVecs[4];
  66922. target.subtractToRef(bonePos, localTarget);
  66923. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66924. var yaw = Math.atan2(localTarget.x, localTarget.z);
  66925. var newYaw = yaw;
  66926. if (yaw > this._maxYaw || yaw < this._minYaw) {
  66927. if (xzlen == null) {
  66928. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66929. }
  66930. if (this._yawRange > Math.PI) {
  66931. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  66932. localTarget.z = this._maxYawCos * xzlen;
  66933. localTarget.x = this._maxYawSin * xzlen;
  66934. newYaw = this._maxYaw;
  66935. }
  66936. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  66937. localTarget.z = this._minYawCos * xzlen;
  66938. localTarget.x = this._minYawSin * xzlen;
  66939. newYaw = this._minYaw;
  66940. }
  66941. }
  66942. else {
  66943. if (yaw > this._maxYaw) {
  66944. localTarget.z = this._maxYawCos * xzlen;
  66945. localTarget.x = this._maxYawSin * xzlen;
  66946. newYaw = this._maxYaw;
  66947. }
  66948. else if (yaw < this._minYaw) {
  66949. localTarget.z = this._minYawCos * xzlen;
  66950. localTarget.x = this._minYawSin * xzlen;
  66951. newYaw = this._minYaw;
  66952. }
  66953. }
  66954. }
  66955. if (this._slerping && this._yawRange > Math.PI) {
  66956. //are we going to be crossing into the min/max region?
  66957. var boneFwd = BoneLookController._tmpVecs[8];
  66958. boneFwd.copyFrom(BABYLON.Axis.Z);
  66959. if (this._transformYawPitch) {
  66960. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  66961. }
  66962. var boneRotMat = BoneLookController._tmpMats[4];
  66963. this._boneQuat.toRotationMatrix(boneRotMat);
  66964. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  66965. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  66966. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  66967. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  66968. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  66969. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  66970. if (angBtwTar > angBtwMidYaw) {
  66971. if (xzlen == null) {
  66972. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66973. }
  66974. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  66975. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  66976. if (angBtwMin < angBtwMax) {
  66977. newYaw = boneYaw + Math.PI * .75;
  66978. localTarget.z = Math.cos(newYaw) * xzlen;
  66979. localTarget.x = Math.sin(newYaw) * xzlen;
  66980. }
  66981. else {
  66982. newYaw = boneYaw - Math.PI * .75;
  66983. localTarget.z = Math.cos(newYaw) * xzlen;
  66984. localTarget.x = Math.sin(newYaw) * xzlen;
  66985. }
  66986. }
  66987. }
  66988. if (yaw != newYaw) {
  66989. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66990. localTarget.addInPlace(bonePos);
  66991. target = localTarget;
  66992. }
  66993. }
  66994. }
  66995. var zaxis = BoneLookController._tmpVecs[5];
  66996. var xaxis = BoneLookController._tmpVecs[6];
  66997. var yaxis = BoneLookController._tmpVecs[7];
  66998. var _tmpQuat = BoneLookController._tmpQuat;
  66999. target.subtractToRef(bonePos, zaxis);
  67000. zaxis.normalize();
  67001. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  67002. xaxis.normalize();
  67003. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  67004. yaxis.normalize();
  67005. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  67006. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  67007. return;
  67008. }
  67009. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  67010. return;
  67011. }
  67012. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  67013. return;
  67014. }
  67015. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  67016. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  67017. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  67018. }
  67019. if (this.slerpAmount < 1) {
  67020. if (!this._slerping) {
  67021. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  67022. }
  67023. if (this._transformYawPitch) {
  67024. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  67025. }
  67026. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  67027. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  67028. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  67029. this._slerping = true;
  67030. }
  67031. else {
  67032. if (this._transformYawPitch) {
  67033. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  67034. }
  67035. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  67036. this._slerping = false;
  67037. }
  67038. };
  67039. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  67040. var angDiff = ang2 - ang1;
  67041. angDiff %= Math.PI * 2;
  67042. if (angDiff > Math.PI) {
  67043. angDiff -= Math.PI * 2;
  67044. }
  67045. else if (angDiff < -Math.PI) {
  67046. angDiff += Math.PI * 2;
  67047. }
  67048. return angDiff;
  67049. };
  67050. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  67051. ang1 %= (2 * Math.PI);
  67052. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  67053. ang2 %= (2 * Math.PI);
  67054. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  67055. var ab = 0;
  67056. if (ang1 < ang2) {
  67057. ab = ang2 - ang1;
  67058. }
  67059. else {
  67060. ab = ang1 - ang2;
  67061. }
  67062. if (ab > Math.PI) {
  67063. ab = Math.PI * 2 - ab;
  67064. }
  67065. return ab;
  67066. };
  67067. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  67068. ang %= (2 * Math.PI);
  67069. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  67070. ang1 %= (2 * Math.PI);
  67071. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  67072. ang2 %= (2 * Math.PI);
  67073. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  67074. if (ang1 < ang2) {
  67075. if (ang > ang1 && ang < ang2) {
  67076. return true;
  67077. }
  67078. }
  67079. else {
  67080. if (ang > ang2 && ang < ang1) {
  67081. return true;
  67082. }
  67083. }
  67084. return false;
  67085. };
  67086. 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()];
  67087. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  67088. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  67089. return BoneLookController;
  67090. }());
  67091. BABYLON.BoneLookController = BoneLookController;
  67092. })(BABYLON || (BABYLON = {}));
  67093. //# sourceMappingURL=babylon.boneLookController.js.map
  67094. var BABYLON;
  67095. (function (BABYLON) {
  67096. var Skeleton = /** @class */ (function () {
  67097. function Skeleton(name, id, scene) {
  67098. this.name = name;
  67099. this.id = id;
  67100. this.bones = new Array();
  67101. this.needInitialSkinMatrix = false;
  67102. this._isDirty = true;
  67103. this._meshesWithPoseMatrix = new Array();
  67104. this._identity = BABYLON.Matrix.Identity();
  67105. this._ranges = {};
  67106. this._lastAbsoluteTransformsUpdateId = -1;
  67107. // Events
  67108. /**
  67109. * An event triggered before computing the skeleton's matrices
  67110. * @type {BABYLON.Observable}
  67111. */
  67112. this.onBeforeComputeObservable = new BABYLON.Observable();
  67113. this.bones = [];
  67114. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67115. scene.skeletons.push(this);
  67116. //make sure it will recalculate the matrix next time prepare is called.
  67117. this._isDirty = true;
  67118. }
  67119. // Members
  67120. Skeleton.prototype.getTransformMatrices = function (mesh) {
  67121. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  67122. return mesh._bonesTransformMatrices;
  67123. }
  67124. if (!this._transformMatrices) {
  67125. this.prepare();
  67126. }
  67127. return this._transformMatrices;
  67128. };
  67129. Skeleton.prototype.getScene = function () {
  67130. return this._scene;
  67131. };
  67132. // Methods
  67133. /**
  67134. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  67135. */
  67136. Skeleton.prototype.toString = function (fullDetails) {
  67137. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  67138. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  67139. if (fullDetails) {
  67140. ret += ", Ranges: {";
  67141. var first = true;
  67142. for (var name_1 in this._ranges) {
  67143. if (first) {
  67144. ret += ", ";
  67145. first = false;
  67146. }
  67147. ret += name_1;
  67148. }
  67149. ret += "}";
  67150. }
  67151. return ret;
  67152. };
  67153. /**
  67154. * Get bone's index searching by name
  67155. * @param {string} name is bone's name to search for
  67156. * @return {number} Indice of the bone. Returns -1 if not found
  67157. */
  67158. Skeleton.prototype.getBoneIndexByName = function (name) {
  67159. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  67160. if (this.bones[boneIndex].name === name) {
  67161. return boneIndex;
  67162. }
  67163. }
  67164. return -1;
  67165. };
  67166. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  67167. // check name not already in use
  67168. if (!this._ranges[name]) {
  67169. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  67170. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  67171. if (this.bones[i].animations[0]) {
  67172. this.bones[i].animations[0].createRange(name, from, to);
  67173. }
  67174. }
  67175. }
  67176. };
  67177. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  67178. if (deleteFrames === void 0) { deleteFrames = true; }
  67179. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  67180. if (this.bones[i].animations[0]) {
  67181. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  67182. }
  67183. }
  67184. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  67185. };
  67186. Skeleton.prototype.getAnimationRange = function (name) {
  67187. return this._ranges[name];
  67188. };
  67189. /**
  67190. * Returns as an Array, all AnimationRanges defined on this skeleton
  67191. */
  67192. Skeleton.prototype.getAnimationRanges = function () {
  67193. var animationRanges = [];
  67194. var name;
  67195. var i = 0;
  67196. for (name in this._ranges) {
  67197. animationRanges[i] = this._ranges[name];
  67198. i++;
  67199. }
  67200. return animationRanges;
  67201. };
  67202. /**
  67203. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  67204. */
  67205. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  67206. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  67207. if (this._ranges[name] || !source.getAnimationRange(name)) {
  67208. return false;
  67209. }
  67210. var ret = true;
  67211. var frameOffset = this._getHighestAnimationFrame() + 1;
  67212. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  67213. var boneDict = {};
  67214. var sourceBones = source.bones;
  67215. var nBones;
  67216. var i;
  67217. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  67218. boneDict[sourceBones[i].name] = sourceBones[i];
  67219. }
  67220. if (this.bones.length !== sourceBones.length) {
  67221. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  67222. ret = false;
  67223. }
  67224. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  67225. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  67226. var boneName = this.bones[i].name;
  67227. var sourceBone = boneDict[boneName];
  67228. if (sourceBone) {
  67229. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  67230. }
  67231. else {
  67232. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  67233. ret = false;
  67234. }
  67235. }
  67236. // do not call createAnimationRange(), since it also is done to bones, which was already done
  67237. var range = source.getAnimationRange(name);
  67238. if (range) {
  67239. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  67240. }
  67241. return ret;
  67242. };
  67243. Skeleton.prototype.returnToRest = function () {
  67244. for (var index = 0; index < this.bones.length; index++) {
  67245. this.bones[index].returnToRest();
  67246. }
  67247. };
  67248. Skeleton.prototype._getHighestAnimationFrame = function () {
  67249. var ret = 0;
  67250. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  67251. if (this.bones[i].animations[0]) {
  67252. var highest = this.bones[i].animations[0].getHighestFrame();
  67253. if (ret < highest) {
  67254. ret = highest;
  67255. }
  67256. }
  67257. }
  67258. return ret;
  67259. };
  67260. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  67261. var range = this.getAnimationRange(name);
  67262. if (!range) {
  67263. return null;
  67264. }
  67265. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  67266. };
  67267. Skeleton.prototype._markAsDirty = function () {
  67268. this._isDirty = true;
  67269. };
  67270. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  67271. this._meshesWithPoseMatrix.push(mesh);
  67272. };
  67273. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  67274. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  67275. if (index > -1) {
  67276. this._meshesWithPoseMatrix.splice(index, 1);
  67277. }
  67278. };
  67279. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  67280. this.onBeforeComputeObservable.notifyObservers(this);
  67281. for (var index = 0; index < this.bones.length; index++) {
  67282. var bone = this.bones[index];
  67283. var parentBone = bone.getParent();
  67284. if (parentBone) {
  67285. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  67286. }
  67287. else {
  67288. if (initialSkinMatrix) {
  67289. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  67290. }
  67291. else {
  67292. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  67293. }
  67294. }
  67295. if (bone._index !== -1) {
  67296. var mappedIndex = bone._index === null ? index : bone._index;
  67297. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  67298. }
  67299. }
  67300. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  67301. };
  67302. Skeleton.prototype.prepare = function () {
  67303. if (!this._isDirty) {
  67304. return;
  67305. }
  67306. if (this.needInitialSkinMatrix) {
  67307. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  67308. var mesh = this._meshesWithPoseMatrix[index];
  67309. var poseMatrix = mesh.getPoseMatrix();
  67310. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  67311. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  67312. }
  67313. if (this._synchronizedWithMesh !== mesh) {
  67314. this._synchronizedWithMesh = mesh;
  67315. // Prepare bones
  67316. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  67317. var bone = this.bones[boneIndex];
  67318. if (!bone.getParent()) {
  67319. var matrix = bone.getBaseMatrix();
  67320. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  67321. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  67322. }
  67323. }
  67324. }
  67325. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  67326. }
  67327. }
  67328. else {
  67329. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  67330. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  67331. }
  67332. this._computeTransformMatrices(this._transformMatrices, null);
  67333. }
  67334. this._isDirty = false;
  67335. this._scene._activeBones.addCount(this.bones.length, false);
  67336. };
  67337. Skeleton.prototype.getAnimatables = function () {
  67338. if (!this._animatables || this._animatables.length !== this.bones.length) {
  67339. this._animatables = [];
  67340. for (var index = 0; index < this.bones.length; index++) {
  67341. this._animatables.push(this.bones[index]);
  67342. }
  67343. }
  67344. return this._animatables;
  67345. };
  67346. Skeleton.prototype.clone = function (name, id) {
  67347. var result = new Skeleton(name, id || name, this._scene);
  67348. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  67349. for (var index = 0; index < this.bones.length; index++) {
  67350. var source = this.bones[index];
  67351. var parentBone = null;
  67352. var parent_1 = source.getParent();
  67353. if (parent_1) {
  67354. var parentIndex = this.bones.indexOf(parent_1);
  67355. parentBone = result.bones[parentIndex];
  67356. }
  67357. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  67358. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  67359. }
  67360. if (this._ranges) {
  67361. result._ranges = {};
  67362. for (var rangeName in this._ranges) {
  67363. var range = this._ranges[rangeName];
  67364. if (range) {
  67365. result._ranges[rangeName] = range.clone();
  67366. }
  67367. }
  67368. }
  67369. this._isDirty = true;
  67370. return result;
  67371. };
  67372. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  67373. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  67374. this.bones.forEach(function (bone) {
  67375. bone.animations.forEach(function (animation) {
  67376. animation.enableBlending = true;
  67377. animation.blendingSpeed = blendingSpeed;
  67378. });
  67379. });
  67380. };
  67381. Skeleton.prototype.dispose = function () {
  67382. this._meshesWithPoseMatrix = [];
  67383. // Animations
  67384. this.getScene().stopAnimation(this);
  67385. // Remove from scene
  67386. this.getScene().removeSkeleton(this);
  67387. };
  67388. Skeleton.prototype.serialize = function () {
  67389. var serializationObject = {};
  67390. serializationObject.name = this.name;
  67391. serializationObject.id = this.id;
  67392. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  67393. serializationObject.bones = [];
  67394. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  67395. for (var index = 0; index < this.bones.length; index++) {
  67396. var bone = this.bones[index];
  67397. var parent_2 = bone.getParent();
  67398. var serializedBone = {
  67399. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  67400. name: bone.name,
  67401. matrix: bone.getBaseMatrix().toArray(),
  67402. rest: bone.getRestPose().toArray()
  67403. };
  67404. serializationObject.bones.push(serializedBone);
  67405. if (bone.length) {
  67406. serializedBone.length = bone.length;
  67407. }
  67408. if (bone.animations && bone.animations.length > 0) {
  67409. serializedBone.animation = bone.animations[0].serialize();
  67410. }
  67411. serializationObject.ranges = [];
  67412. for (var name in this._ranges) {
  67413. var source = this._ranges[name];
  67414. if (!source) {
  67415. continue;
  67416. }
  67417. var range = {};
  67418. range.name = name;
  67419. range.from = source.from;
  67420. range.to = source.to;
  67421. serializationObject.ranges.push(range);
  67422. }
  67423. }
  67424. return serializationObject;
  67425. };
  67426. Skeleton.Parse = function (parsedSkeleton, scene) {
  67427. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  67428. if (parsedSkeleton.dimensionsAtRest) {
  67429. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  67430. }
  67431. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  67432. var index;
  67433. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  67434. var parsedBone = parsedSkeleton.bones[index];
  67435. var parentBone = null;
  67436. if (parsedBone.parentBoneIndex > -1) {
  67437. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  67438. }
  67439. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  67440. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  67441. if (parsedBone.length) {
  67442. bone.length = parsedBone.length;
  67443. }
  67444. if (parsedBone.animation) {
  67445. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  67446. }
  67447. }
  67448. // placed after bones, so createAnimationRange can cascade down
  67449. if (parsedSkeleton.ranges) {
  67450. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  67451. var data = parsedSkeleton.ranges[index];
  67452. skeleton.createAnimationRange(data.name, data.from, data.to);
  67453. }
  67454. }
  67455. return skeleton;
  67456. };
  67457. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  67458. if (forceUpdate === void 0) { forceUpdate = false; }
  67459. var renderId = this._scene.getRenderId();
  67460. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  67461. this.bones[0].computeAbsoluteTransforms();
  67462. this._lastAbsoluteTransformsUpdateId = renderId;
  67463. }
  67464. };
  67465. Skeleton.prototype.getPoseMatrix = function () {
  67466. var poseMatrix = null;
  67467. if (this._meshesWithPoseMatrix.length > 0) {
  67468. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  67469. }
  67470. return poseMatrix;
  67471. };
  67472. Skeleton.prototype.sortBones = function () {
  67473. var bones = new Array();
  67474. var visited = new Array(this.bones.length);
  67475. for (var index = 0; index < this.bones.length; index++) {
  67476. this._sortBones(index, bones, visited);
  67477. }
  67478. this.bones = bones;
  67479. };
  67480. Skeleton.prototype._sortBones = function (index, bones, visited) {
  67481. if (visited[index]) {
  67482. return;
  67483. }
  67484. visited[index] = true;
  67485. var bone = this.bones[index];
  67486. if (bone._index === undefined) {
  67487. bone._index = index;
  67488. }
  67489. var parentBone = bone.getParent();
  67490. if (parentBone) {
  67491. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  67492. }
  67493. bones.push(bone);
  67494. };
  67495. return Skeleton;
  67496. }());
  67497. BABYLON.Skeleton = Skeleton;
  67498. })(BABYLON || (BABYLON = {}));
  67499. //# sourceMappingURL=babylon.skeleton.js.map
  67500. var BABYLON;
  67501. (function (BABYLON) {
  67502. var SphericalPolynomial = /** @class */ (function () {
  67503. function SphericalPolynomial() {
  67504. this.x = BABYLON.Vector3.Zero();
  67505. this.y = BABYLON.Vector3.Zero();
  67506. this.z = BABYLON.Vector3.Zero();
  67507. this.xx = BABYLON.Vector3.Zero();
  67508. this.yy = BABYLON.Vector3.Zero();
  67509. this.zz = BABYLON.Vector3.Zero();
  67510. this.xy = BABYLON.Vector3.Zero();
  67511. this.yz = BABYLON.Vector3.Zero();
  67512. this.zx = BABYLON.Vector3.Zero();
  67513. }
  67514. SphericalPolynomial.prototype.addAmbient = function (color) {
  67515. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  67516. this.xx = this.xx.add(colorVector);
  67517. this.yy = this.yy.add(colorVector);
  67518. this.zz = this.zz.add(colorVector);
  67519. };
  67520. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  67521. var result = new SphericalPolynomial();
  67522. result.x = harmonics.L11.scale(1.02333);
  67523. result.y = harmonics.L1_1.scale(1.02333);
  67524. result.z = harmonics.L10.scale(1.02333);
  67525. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  67526. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  67527. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  67528. result.yz = harmonics.L2_1.scale(0.858086);
  67529. result.zx = harmonics.L21.scale(0.858086);
  67530. result.xy = harmonics.L2_2.scale(0.858086);
  67531. result.scale(1.0 / Math.PI);
  67532. return result;
  67533. };
  67534. SphericalPolynomial.prototype.scale = function (scale) {
  67535. this.x = this.x.scale(scale);
  67536. this.y = this.y.scale(scale);
  67537. this.z = this.z.scale(scale);
  67538. this.xx = this.xx.scale(scale);
  67539. this.yy = this.yy.scale(scale);
  67540. this.zz = this.zz.scale(scale);
  67541. this.yz = this.yz.scale(scale);
  67542. this.zx = this.zx.scale(scale);
  67543. this.xy = this.xy.scale(scale);
  67544. };
  67545. return SphericalPolynomial;
  67546. }());
  67547. BABYLON.SphericalPolynomial = SphericalPolynomial;
  67548. var SphericalHarmonics = /** @class */ (function () {
  67549. function SphericalHarmonics() {
  67550. this.L00 = BABYLON.Vector3.Zero();
  67551. this.L1_1 = BABYLON.Vector3.Zero();
  67552. this.L10 = BABYLON.Vector3.Zero();
  67553. this.L11 = BABYLON.Vector3.Zero();
  67554. this.L2_2 = BABYLON.Vector3.Zero();
  67555. this.L2_1 = BABYLON.Vector3.Zero();
  67556. this.L20 = BABYLON.Vector3.Zero();
  67557. this.L21 = BABYLON.Vector3.Zero();
  67558. this.L22 = BABYLON.Vector3.Zero();
  67559. }
  67560. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  67561. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  67562. var c = colorVector.scale(deltaSolidAngle);
  67563. this.L00 = this.L00.add(c.scale(0.282095));
  67564. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  67565. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  67566. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  67567. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  67568. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  67569. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  67570. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  67571. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  67572. };
  67573. SphericalHarmonics.prototype.scale = function (scale) {
  67574. this.L00 = this.L00.scale(scale);
  67575. this.L1_1 = this.L1_1.scale(scale);
  67576. this.L10 = this.L10.scale(scale);
  67577. this.L11 = this.L11.scale(scale);
  67578. this.L2_2 = this.L2_2.scale(scale);
  67579. this.L2_1 = this.L2_1.scale(scale);
  67580. this.L20 = this.L20.scale(scale);
  67581. this.L21 = this.L21.scale(scale);
  67582. this.L22 = this.L22.scale(scale);
  67583. };
  67584. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  67585. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  67586. //
  67587. // E_lm = A_l * L_lm
  67588. //
  67589. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  67590. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  67591. // the scaling factors are given in equation 9.
  67592. // Constant (Band 0)
  67593. this.L00 = this.L00.scale(3.141593);
  67594. // Linear (Band 1)
  67595. this.L1_1 = this.L1_1.scale(2.094395);
  67596. this.L10 = this.L10.scale(2.094395);
  67597. this.L11 = this.L11.scale(2.094395);
  67598. // Quadratic (Band 2)
  67599. this.L2_2 = this.L2_2.scale(0.785398);
  67600. this.L2_1 = this.L2_1.scale(0.785398);
  67601. this.L20 = this.L20.scale(0.785398);
  67602. this.L21 = this.L21.scale(0.785398);
  67603. this.L22 = this.L22.scale(0.785398);
  67604. };
  67605. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  67606. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  67607. // L = (1/pi) * E * rho
  67608. //
  67609. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  67610. this.scale(1.0 / Math.PI);
  67611. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  67612. // (The pixel shader must apply albedo after texture fetches, etc).
  67613. };
  67614. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  67615. var result = new SphericalHarmonics();
  67616. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  67617. result.L1_1 = polynomial.y.scale(0.977204);
  67618. result.L10 = polynomial.z.scale(0.977204);
  67619. result.L11 = polynomial.x.scale(0.977204);
  67620. result.L2_2 = polynomial.xy.scale(1.16538);
  67621. result.L2_1 = polynomial.yz.scale(1.16538);
  67622. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  67623. result.L21 = polynomial.zx.scale(1.16538);
  67624. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  67625. result.scale(Math.PI);
  67626. return result;
  67627. };
  67628. return SphericalHarmonics;
  67629. }());
  67630. BABYLON.SphericalHarmonics = SphericalHarmonics;
  67631. })(BABYLON || (BABYLON = {}));
  67632. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  67633. var BABYLON;
  67634. (function (BABYLON) {
  67635. var FileFaceOrientation = /** @class */ (function () {
  67636. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  67637. this.name = name;
  67638. this.worldAxisForNormal = worldAxisForNormal;
  67639. this.worldAxisForFileX = worldAxisForFileX;
  67640. this.worldAxisForFileY = worldAxisForFileY;
  67641. }
  67642. return FileFaceOrientation;
  67643. }());
  67644. ;
  67645. /**
  67646. * Helper class dealing with the extraction of spherical polynomial dataArray
  67647. * from a cube map.
  67648. */
  67649. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  67650. function CubeMapToSphericalPolynomialTools() {
  67651. }
  67652. /**
  67653. * Converts a texture to the according Spherical Polynomial data.
  67654. * This extracts the first 3 orders only as they are the only one used in the lighting.
  67655. *
  67656. * @param texture The texture to extract the information from.
  67657. * @return The Spherical Polynomial data.
  67658. */
  67659. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  67660. if (!texture.isCube) {
  67661. // Only supports cube Textures currently.
  67662. return null;
  67663. }
  67664. var size = texture.getSize().width;
  67665. var right = texture.readPixels(0);
  67666. var left = texture.readPixels(1);
  67667. var up;
  67668. var down;
  67669. if (texture.isRenderTarget) {
  67670. up = texture.readPixels(3);
  67671. down = texture.readPixels(2);
  67672. }
  67673. else {
  67674. up = texture.readPixels(2);
  67675. down = texture.readPixels(3);
  67676. }
  67677. var front = texture.readPixels(4);
  67678. var back = texture.readPixels(5);
  67679. var gammaSpace = texture.gammaSpace;
  67680. // Always read as RGBA.
  67681. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  67682. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67683. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67684. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67685. }
  67686. var cubeInfo = {
  67687. size: size,
  67688. right: right,
  67689. left: left,
  67690. up: up,
  67691. down: down,
  67692. front: front,
  67693. back: back,
  67694. format: format,
  67695. type: type,
  67696. gammaSpace: gammaSpace,
  67697. };
  67698. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  67699. };
  67700. /**
  67701. * Converts a cubemap to the according Spherical Polynomial data.
  67702. * This extracts the first 3 orders only as they are the only one used in the lighting.
  67703. *
  67704. * @param cubeInfo The Cube map to extract the information from.
  67705. * @return The Spherical Polynomial data.
  67706. */
  67707. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  67708. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  67709. var totalSolidAngle = 0.0;
  67710. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  67711. var du = 2.0 / cubeInfo.size;
  67712. var dv = du;
  67713. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  67714. var minUV = du * 0.5 - 1.0;
  67715. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67716. var fileFace = this.FileFaces[faceIndex];
  67717. var dataArray = cubeInfo[fileFace.name];
  67718. var v = minUV;
  67719. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  67720. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  67721. // Because SP is still linear, so summation is fine in that basis.
  67722. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  67723. for (var y = 0; y < cubeInfo.size; y++) {
  67724. var u = minUV;
  67725. for (var x = 0; x < cubeInfo.size; x++) {
  67726. // World direction (not normalised)
  67727. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  67728. worldDirection.normalize();
  67729. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  67730. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  67731. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  67732. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  67733. // Handle Integer types.
  67734. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67735. r /= 255;
  67736. g /= 255;
  67737. b /= 255;
  67738. }
  67739. // Handle Gamma space textures.
  67740. if (cubeInfo.gammaSpace) {
  67741. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  67742. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  67743. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  67744. }
  67745. var color = new BABYLON.Color3(r, g, b);
  67746. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  67747. totalSolidAngle += deltaSolidAngle;
  67748. u += du;
  67749. }
  67750. v += dv;
  67751. }
  67752. }
  67753. // Solid angle for entire sphere is 4*pi
  67754. var sphereSolidAngle = 4.0 * Math.PI;
  67755. // Adjust the solid angle to allow for how many faces we processed.
  67756. var facesProcessed = 6.0;
  67757. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  67758. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  67759. // This is needed because the numerical integration over the cube uses a
  67760. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  67761. // and also to compensate for accumulative error due to float precision in the summation.
  67762. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  67763. sphericalHarmonics.scale(correctionFactor);
  67764. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  67765. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  67766. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  67767. };
  67768. CubeMapToSphericalPolynomialTools.FileFaces = [
  67769. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  67770. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  67771. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  67772. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  67773. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  67774. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  67775. ];
  67776. return CubeMapToSphericalPolynomialTools;
  67777. }());
  67778. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  67779. })(BABYLON || (BABYLON = {}));
  67780. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  67781. var BABYLON;
  67782. (function (BABYLON) {
  67783. /**
  67784. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  67785. */
  67786. var PanoramaToCubeMapTools = /** @class */ (function () {
  67787. function PanoramaToCubeMapTools() {
  67788. }
  67789. /**
  67790. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  67791. *
  67792. * @param float32Array The source data.
  67793. * @param inputWidth The width of the input panorama.
  67794. * @param inputhHeight The height of the input panorama.
  67795. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  67796. * @return The cubemap data
  67797. */
  67798. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  67799. if (!float32Array) {
  67800. throw "ConvertPanoramaToCubemap: input cannot be null";
  67801. }
  67802. if (float32Array.length != inputWidth * inputHeight * 3) {
  67803. throw "ConvertPanoramaToCubemap: input size is wrong";
  67804. }
  67805. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  67806. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  67807. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  67808. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  67809. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  67810. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  67811. return {
  67812. front: textureFront,
  67813. back: textureBack,
  67814. left: textureLeft,
  67815. right: textureRight,
  67816. up: textureUp,
  67817. down: textureDown,
  67818. size: size,
  67819. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  67820. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  67821. gammaSpace: false,
  67822. };
  67823. };
  67824. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  67825. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  67826. var textureArray = new Float32Array(buffer);
  67827. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  67828. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  67829. var dy = 1 / texSize;
  67830. var fy = 0;
  67831. for (var y = 0; y < texSize; y++) {
  67832. var xv1 = faceData[0];
  67833. var xv2 = faceData[2];
  67834. for (var x = 0; x < texSize; x++) {
  67835. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  67836. v.normalize();
  67837. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  67838. // 3 channels per pixels
  67839. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  67840. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  67841. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  67842. xv1 = xv1.add(rotDX1);
  67843. xv2 = xv2.add(rotDX2);
  67844. }
  67845. fy += dy;
  67846. }
  67847. return textureArray;
  67848. };
  67849. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  67850. var theta = Math.atan2(vDir.z, vDir.x);
  67851. var phi = Math.acos(vDir.y);
  67852. while (theta < -Math.PI)
  67853. theta += 2 * Math.PI;
  67854. while (theta > Math.PI)
  67855. theta -= 2 * Math.PI;
  67856. var dx = theta / Math.PI;
  67857. var dy = phi / Math.PI;
  67858. // recenter.
  67859. dx = dx * 0.5 + 0.5;
  67860. var px = Math.round(dx * inputWidth);
  67861. if (px < 0)
  67862. px = 0;
  67863. else if (px >= inputWidth)
  67864. px = inputWidth - 1;
  67865. var py = Math.round(dy * inputHeight);
  67866. if (py < 0)
  67867. py = 0;
  67868. else if (py >= inputHeight)
  67869. py = inputHeight - 1;
  67870. var inputY = (inputHeight - py - 1);
  67871. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  67872. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  67873. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  67874. return {
  67875. r: r,
  67876. g: g,
  67877. b: b
  67878. };
  67879. };
  67880. PanoramaToCubeMapTools.FACE_FRONT = [
  67881. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67882. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67883. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67884. new BABYLON.Vector3(1.0, 1.0, -1.0)
  67885. ];
  67886. PanoramaToCubeMapTools.FACE_BACK = [
  67887. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67888. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67889. new BABYLON.Vector3(1.0, 1.0, 1.0),
  67890. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  67891. ];
  67892. PanoramaToCubeMapTools.FACE_RIGHT = [
  67893. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67894. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67895. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67896. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67897. ];
  67898. PanoramaToCubeMapTools.FACE_LEFT = [
  67899. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67900. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67901. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67902. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  67903. ];
  67904. PanoramaToCubeMapTools.FACE_DOWN = [
  67905. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67906. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67907. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67908. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67909. ];
  67910. PanoramaToCubeMapTools.FACE_UP = [
  67911. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67912. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67913. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67914. new BABYLON.Vector3(1.0, -1.0, -1.0)
  67915. ];
  67916. return PanoramaToCubeMapTools;
  67917. }());
  67918. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  67919. })(BABYLON || (BABYLON = {}));
  67920. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  67921. var BABYLON;
  67922. (function (BABYLON) {
  67923. ;
  67924. /**
  67925. * This groups tools to convert HDR texture to native colors array.
  67926. */
  67927. var HDRTools = /** @class */ (function () {
  67928. function HDRTools() {
  67929. }
  67930. HDRTools.Ldexp = function (mantissa, exponent) {
  67931. if (exponent > 1023) {
  67932. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  67933. }
  67934. if (exponent < -1074) {
  67935. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  67936. }
  67937. return mantissa * Math.pow(2, exponent);
  67938. };
  67939. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  67940. if (exponent > 0) {
  67941. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  67942. float32array[index + 0] = red * exponent;
  67943. float32array[index + 1] = green * exponent;
  67944. float32array[index + 2] = blue * exponent;
  67945. }
  67946. else {
  67947. float32array[index + 0] = 0;
  67948. float32array[index + 1] = 0;
  67949. float32array[index + 2] = 0;
  67950. }
  67951. };
  67952. HDRTools.readStringLine = function (uint8array, startIndex) {
  67953. var line = "";
  67954. var character = "";
  67955. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  67956. character = String.fromCharCode(uint8array[i]);
  67957. if (character == "\n") {
  67958. break;
  67959. }
  67960. line += character;
  67961. }
  67962. return line;
  67963. };
  67964. /**
  67965. * Reads header information from an RGBE texture stored in a native array.
  67966. * More information on this format are available here:
  67967. * https://en.wikipedia.org/wiki/RGBE_image_format
  67968. *
  67969. * @param uint8array The binary file stored in native array.
  67970. * @return The header information.
  67971. */
  67972. HDRTools.RGBE_ReadHeader = function (uint8array) {
  67973. var height = 0;
  67974. var width = 0;
  67975. var line = this.readStringLine(uint8array, 0);
  67976. if (line[0] != '#' || line[1] != '?') {
  67977. throw "Bad HDR Format.";
  67978. }
  67979. var endOfHeader = false;
  67980. var findFormat = false;
  67981. var lineIndex = 0;
  67982. do {
  67983. lineIndex += (line.length + 1);
  67984. line = this.readStringLine(uint8array, lineIndex);
  67985. if (line == "FORMAT=32-bit_rle_rgbe") {
  67986. findFormat = true;
  67987. }
  67988. else if (line.length == 0) {
  67989. endOfHeader = true;
  67990. }
  67991. } while (!endOfHeader);
  67992. if (!findFormat) {
  67993. throw "HDR Bad header format, unsupported FORMAT";
  67994. }
  67995. lineIndex += (line.length + 1);
  67996. line = this.readStringLine(uint8array, lineIndex);
  67997. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  67998. var match = sizeRegexp.exec(line);
  67999. // TODO. Support +Y and -X if needed.
  68000. if (!match || match.length < 3) {
  68001. throw "HDR Bad header format, no size";
  68002. }
  68003. width = parseInt(match[2]);
  68004. height = parseInt(match[1]);
  68005. if (width < 8 || width > 0x7fff) {
  68006. throw "HDR Bad header format, unsupported size";
  68007. }
  68008. lineIndex += (line.length + 1);
  68009. return {
  68010. height: height,
  68011. width: width,
  68012. dataPosition: lineIndex
  68013. };
  68014. };
  68015. /**
  68016. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  68017. * This RGBE texture needs to store the information as a panorama.
  68018. *
  68019. * More information on this format are available here:
  68020. * https://en.wikipedia.org/wiki/RGBE_image_format
  68021. *
  68022. * @param buffer The binary file stored in an array buffer.
  68023. * @param size The expected size of the extracted cubemap.
  68024. * @return The Cube Map information.
  68025. */
  68026. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  68027. var uint8array = new Uint8Array(buffer);
  68028. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  68029. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  68030. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  68031. return cubeMapData;
  68032. };
  68033. /**
  68034. * Returns the pixels data extracted from an RGBE texture.
  68035. * This pixels will be stored left to right up to down in the R G B order in one array.
  68036. *
  68037. * More information on this format are available here:
  68038. * https://en.wikipedia.org/wiki/RGBE_image_format
  68039. *
  68040. * @param uint8array The binary file stored in an array buffer.
  68041. * @param hdrInfo The header information of the file.
  68042. * @return The pixels data in RGB right to left up to down order.
  68043. */
  68044. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  68045. // Keep for multi format supports.
  68046. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  68047. };
  68048. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  68049. var num_scanlines = hdrInfo.height;
  68050. var scanline_width = hdrInfo.width;
  68051. var a, b, c, d, count;
  68052. var dataIndex = hdrInfo.dataPosition;
  68053. var index = 0, endIndex = 0, i = 0;
  68054. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  68055. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  68056. // 3 channels of 4 bytes per pixel in float.
  68057. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  68058. var resultArray = new Float32Array(resultBuffer);
  68059. // read in each successive scanline
  68060. while (num_scanlines > 0) {
  68061. a = uint8array[dataIndex++];
  68062. b = uint8array[dataIndex++];
  68063. c = uint8array[dataIndex++];
  68064. d = uint8array[dataIndex++];
  68065. if (a != 2 || b != 2 || (c & 0x80)) {
  68066. // this file is not run length encoded
  68067. throw "HDR Bad header format, not RLE";
  68068. }
  68069. if (((c << 8) | d) != scanline_width) {
  68070. throw "HDR Bad header format, wrong scan line width";
  68071. }
  68072. index = 0;
  68073. // read each of the four channels for the scanline into the buffer
  68074. for (i = 0; i < 4; i++) {
  68075. endIndex = (i + 1) * scanline_width;
  68076. while (index < endIndex) {
  68077. a = uint8array[dataIndex++];
  68078. b = uint8array[dataIndex++];
  68079. if (a > 128) {
  68080. // a run of the same value
  68081. count = a - 128;
  68082. if ((count == 0) || (count > endIndex - index)) {
  68083. throw "HDR Bad Format, bad scanline data (run)";
  68084. }
  68085. while (count-- > 0) {
  68086. scanLineArray[index++] = b;
  68087. }
  68088. }
  68089. else {
  68090. // a non-run
  68091. count = a;
  68092. if ((count == 0) || (count > endIndex - index)) {
  68093. throw "HDR Bad Format, bad scanline data (non-run)";
  68094. }
  68095. scanLineArray[index++] = b;
  68096. if (--count > 0) {
  68097. for (var j = 0; j < count; j++) {
  68098. scanLineArray[index++] = uint8array[dataIndex++];
  68099. }
  68100. }
  68101. }
  68102. }
  68103. }
  68104. // now convert data from buffer into floats
  68105. for (i = 0; i < scanline_width; i++) {
  68106. a = scanLineArray[i];
  68107. b = scanLineArray[i + scanline_width];
  68108. c = scanLineArray[i + 2 * scanline_width];
  68109. d = scanLineArray[i + 3 * scanline_width];
  68110. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  68111. }
  68112. num_scanlines--;
  68113. }
  68114. return resultArray;
  68115. };
  68116. return HDRTools;
  68117. }());
  68118. BABYLON.HDRTools = HDRTools;
  68119. })(BABYLON || (BABYLON = {}));
  68120. //# sourceMappingURL=babylon.hdr.js.map
  68121. var BABYLON;
  68122. (function (BABYLON) {
  68123. /**
  68124. * This represents a texture coming from an HDR input.
  68125. *
  68126. * The only supported format is currently panorama picture stored in RGBE format.
  68127. * Example of such files can be found on HDRLib: http://hdrlib.com/
  68128. */
  68129. var HDRCubeTexture = /** @class */ (function (_super) {
  68130. __extends(HDRCubeTexture, _super);
  68131. /**
  68132. * Instantiates an HDRTexture from the following parameters.
  68133. *
  68134. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  68135. * @param scene The scene the texture will be used in
  68136. * @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.
  68137. * @param noMipmap Forces to not generate the mipmap if true
  68138. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  68139. * @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)
  68140. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  68141. */
  68142. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  68143. if (noMipmap === void 0) { noMipmap = false; }
  68144. if (generateHarmonics === void 0) { generateHarmonics = true; }
  68145. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  68146. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  68147. if (onLoad === void 0) { onLoad = null; }
  68148. if (onError === void 0) { onError = null; }
  68149. var _this = _super.call(this, scene) || this;
  68150. _this._useInGammaSpace = false;
  68151. _this._generateHarmonics = true;
  68152. _this._isBABYLONPreprocessed = false;
  68153. _this._onLoad = null;
  68154. _this._onError = null;
  68155. /**
  68156. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  68157. */
  68158. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  68159. /**
  68160. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  68161. * This is usefull at run time to apply the good shader.
  68162. */
  68163. _this.isPMREM = false;
  68164. _this._isBlocking = true;
  68165. if (!url) {
  68166. return _this;
  68167. }
  68168. _this.name = url;
  68169. _this.url = url;
  68170. _this.hasAlpha = false;
  68171. _this.isCube = true;
  68172. _this._textureMatrix = BABYLON.Matrix.Identity();
  68173. _this._onLoad = onLoad;
  68174. _this._onError = onError;
  68175. _this.gammaSpace = false;
  68176. var caps = scene.getEngine().getCaps();
  68177. if (size) {
  68178. _this._isBABYLONPreprocessed = false;
  68179. _this._noMipmap = noMipmap;
  68180. _this._size = size;
  68181. _this._useInGammaSpace = useInGammaSpace;
  68182. _this._usePMREMGenerator = usePMREMGenerator &&
  68183. caps.textureLOD &&
  68184. caps.textureFloat &&
  68185. !_this._useInGammaSpace;
  68186. }
  68187. else {
  68188. _this._isBABYLONPreprocessed = true;
  68189. _this._noMipmap = false;
  68190. _this._useInGammaSpace = false;
  68191. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  68192. !_this._useInGammaSpace;
  68193. }
  68194. _this.isPMREM = _this._usePMREMGenerator;
  68195. _this._texture = _this._getFromCache(url, _this._noMipmap);
  68196. if (!_this._texture) {
  68197. if (!scene.useDelayedTextureLoading) {
  68198. _this.loadTexture();
  68199. }
  68200. else {
  68201. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  68202. }
  68203. }
  68204. return _this;
  68205. }
  68206. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  68207. /**
  68208. * Gets wether or not the texture is blocking during loading.
  68209. */
  68210. get: function () {
  68211. return this._isBlocking;
  68212. },
  68213. /**
  68214. * Sets wether or not the texture is blocking during loading.
  68215. */
  68216. set: function (value) {
  68217. this._isBlocking = value;
  68218. },
  68219. enumerable: true,
  68220. configurable: true
  68221. });
  68222. /**
  68223. * Occurs when the file is a preprocessed .babylon.hdr file.
  68224. */
  68225. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  68226. var _this = this;
  68227. var mipLevels = 0;
  68228. var floatArrayView = null;
  68229. var scene = this.getScene();
  68230. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  68231. var mips = new Array();
  68232. if (!floatArrayView) {
  68233. return mips;
  68234. }
  68235. var startIndex = 30;
  68236. for (var level = 0; level < mipLevels; level++) {
  68237. mips.push([]);
  68238. // Fill each pixel of the mip level.
  68239. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  68240. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68241. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  68242. mips[level].push(faceData);
  68243. startIndex += faceSize;
  68244. }
  68245. }
  68246. return mips;
  68247. } : null;
  68248. var callback = function (buffer) {
  68249. var scene = _this.getScene();
  68250. if (!scene) {
  68251. return null;
  68252. }
  68253. // Create Native Array Views
  68254. var intArrayView = new Int32Array(buffer);
  68255. floatArrayView = new Float32Array(buffer);
  68256. // Fill header.
  68257. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  68258. _this._size = intArrayView[1]; // CubeMap max mip face size.
  68259. // Update Texture Information.
  68260. if (!_this._texture) {
  68261. return null;
  68262. }
  68263. _this._texture.updateSize(_this._size, _this._size);
  68264. // Fill polynomial information.
  68265. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  68266. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  68267. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  68268. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  68269. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  68270. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  68271. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  68272. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  68273. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  68274. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  68275. _this.sphericalPolynomial = sphericalPolynomial;
  68276. // Fill pixel data.
  68277. mipLevels = intArrayView[29]; // Number of mip levels.
  68278. var startIndex = 30;
  68279. var data = [];
  68280. var faceSize = Math.pow(_this._size, 2) * 3;
  68281. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68282. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  68283. startIndex += faceSize;
  68284. }
  68285. var results = [];
  68286. var byteArray = null;
  68287. // Push each faces.
  68288. for (var k = 0; k < 6; k++) {
  68289. var dataFace = null;
  68290. // To be deprecated.
  68291. if (version === 1) {
  68292. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  68293. dataFace = data[j];
  68294. }
  68295. // If special cases.
  68296. if (!mipmapGenerator && dataFace) {
  68297. if (!scene.getEngine().getCaps().textureFloat) {
  68298. // 3 channels of 1 bytes per pixel in bytes.
  68299. var byteBuffer = new ArrayBuffer(faceSize);
  68300. byteArray = new Uint8Array(byteBuffer);
  68301. }
  68302. for (var i = 0; i < _this._size * _this._size; i++) {
  68303. // Put in gamma space if requested.
  68304. if (_this._useInGammaSpace) {
  68305. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  68306. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  68307. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  68308. }
  68309. // Convert to int texture for fallback.
  68310. if (byteArray) {
  68311. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  68312. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  68313. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  68314. // May use luminance instead if the result is not accurate.
  68315. var max = Math.max(Math.max(r, g), b);
  68316. if (max > 255) {
  68317. var scale = 255 / max;
  68318. r *= scale;
  68319. g *= scale;
  68320. b *= scale;
  68321. }
  68322. byteArray[(i * 3) + 0] = r;
  68323. byteArray[(i * 3) + 1] = g;
  68324. byteArray[(i * 3) + 2] = b;
  68325. }
  68326. }
  68327. }
  68328. // Fill the array accordingly.
  68329. if (byteArray) {
  68330. results.push(byteArray);
  68331. }
  68332. else {
  68333. results.push(dataFace);
  68334. }
  68335. }
  68336. return results;
  68337. };
  68338. if (scene) {
  68339. 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);
  68340. }
  68341. };
  68342. /**
  68343. * Occurs when the file is raw .hdr file.
  68344. */
  68345. HDRCubeTexture.prototype.loadHDRTexture = function () {
  68346. var _this = this;
  68347. var callback = function (buffer) {
  68348. var scene = _this.getScene();
  68349. if (!scene) {
  68350. return null;
  68351. }
  68352. // Extract the raw linear data.
  68353. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  68354. // Generate harmonics if needed.
  68355. if (_this._generateHarmonics) {
  68356. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  68357. _this.sphericalPolynomial = sphericalPolynomial;
  68358. }
  68359. var results = [];
  68360. var byteArray = null;
  68361. // Push each faces.
  68362. for (var j = 0; j < 6; j++) {
  68363. // Create uintarray fallback.
  68364. if (!scene.getEngine().getCaps().textureFloat) {
  68365. // 3 channels of 1 bytes per pixel in bytes.
  68366. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  68367. byteArray = new Uint8Array(byteBuffer);
  68368. }
  68369. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  68370. // If special cases.
  68371. if (_this._useInGammaSpace || byteArray) {
  68372. for (var i = 0; i < _this._size * _this._size; i++) {
  68373. // Put in gamma space if requested.
  68374. if (_this._useInGammaSpace) {
  68375. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  68376. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  68377. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  68378. }
  68379. // Convert to int texture for fallback.
  68380. if (byteArray) {
  68381. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  68382. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  68383. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  68384. // May use luminance instead if the result is not accurate.
  68385. var max = Math.max(Math.max(r, g), b);
  68386. if (max > 255) {
  68387. var scale = 255 / max;
  68388. r *= scale;
  68389. g *= scale;
  68390. b *= scale;
  68391. }
  68392. byteArray[(i * 3) + 0] = r;
  68393. byteArray[(i * 3) + 1] = g;
  68394. byteArray[(i * 3) + 2] = b;
  68395. }
  68396. }
  68397. }
  68398. if (byteArray) {
  68399. results.push(byteArray);
  68400. }
  68401. else {
  68402. results.push(dataFace);
  68403. }
  68404. }
  68405. return results;
  68406. };
  68407. var mipmapGenerator = null;
  68408. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  68409. // if (!this._noMipmap &&
  68410. // this._usePMREMGenerator) {
  68411. // mipmapGenerator = (data: ArrayBufferView[]) => {
  68412. // // Custom setup of the generator matching with the PBR shader values.
  68413. // var generator = new BABYLON.PMREMGenerator(data,
  68414. // this._size,
  68415. // this._size,
  68416. // 0,
  68417. // 3,
  68418. // this.getScene().getEngine().getCaps().textureFloat,
  68419. // 2048,
  68420. // 0.25,
  68421. // false,
  68422. // true);
  68423. // return generator.filterCubeMap();
  68424. // };
  68425. // }
  68426. var scene = this.getScene();
  68427. if (scene) {
  68428. 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);
  68429. }
  68430. };
  68431. /**
  68432. * Starts the loading process of the texture.
  68433. */
  68434. HDRCubeTexture.prototype.loadTexture = function () {
  68435. if (this._isBABYLONPreprocessed) {
  68436. this.loadBabylonTexture();
  68437. }
  68438. else {
  68439. this.loadHDRTexture();
  68440. }
  68441. };
  68442. HDRCubeTexture.prototype.clone = function () {
  68443. var scene = this.getScene();
  68444. if (!scene) {
  68445. return this;
  68446. }
  68447. var size = (this._isBABYLONPreprocessed ? null : this._size);
  68448. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  68449. // Base texture
  68450. newTexture.level = this.level;
  68451. newTexture.wrapU = this.wrapU;
  68452. newTexture.wrapV = this.wrapV;
  68453. newTexture.coordinatesIndex = this.coordinatesIndex;
  68454. newTexture.coordinatesMode = this.coordinatesMode;
  68455. return newTexture;
  68456. };
  68457. // Methods
  68458. HDRCubeTexture.prototype.delayLoad = function () {
  68459. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  68460. return;
  68461. }
  68462. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  68463. this._texture = this._getFromCache(this.url, this._noMipmap);
  68464. if (!this._texture) {
  68465. this.loadTexture();
  68466. }
  68467. };
  68468. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  68469. return this._textureMatrix;
  68470. };
  68471. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  68472. this._textureMatrix = value;
  68473. };
  68474. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  68475. var texture = null;
  68476. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  68477. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  68478. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  68479. texture.name = parsedTexture.name;
  68480. texture.hasAlpha = parsedTexture.hasAlpha;
  68481. texture.level = parsedTexture.level;
  68482. texture.coordinatesMode = parsedTexture.coordinatesMode;
  68483. texture.isBlocking = parsedTexture.isBlocking;
  68484. }
  68485. return texture;
  68486. };
  68487. HDRCubeTexture.prototype.serialize = function () {
  68488. if (!this.name) {
  68489. return null;
  68490. }
  68491. var serializationObject = {};
  68492. serializationObject.name = this.name;
  68493. serializationObject.hasAlpha = this.hasAlpha;
  68494. serializationObject.isCube = true;
  68495. serializationObject.level = this.level;
  68496. serializationObject.size = this._size;
  68497. serializationObject.coordinatesMode = this.coordinatesMode;
  68498. serializationObject.useInGammaSpace = this._useInGammaSpace;
  68499. serializationObject.generateHarmonics = this._generateHarmonics;
  68500. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  68501. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  68502. serializationObject.customType = "BABYLON.HDRCubeTexture";
  68503. serializationObject.noMipmap = this._noMipmap;
  68504. serializationObject.isBlocking = this._isBlocking;
  68505. return serializationObject;
  68506. };
  68507. /**
  68508. * Saves as a file the data contained in the texture in a binary format.
  68509. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  68510. * as the spherical used in the lighting.
  68511. * @param url The HDR file url.
  68512. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  68513. * @param onError Method called if any error happens during download.
  68514. * @return The packed binary data.
  68515. */
  68516. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  68517. if (onError === void 0) { onError = null; }
  68518. var callback = function (buffer) {
  68519. var data = new Blob([buffer], { type: 'application/octet-stream' });
  68520. // Returns a URL you can use as a href.
  68521. var objUrl = window.URL.createObjectURL(data);
  68522. // Simulates a link to it and click to dowload.
  68523. var a = document.createElement("a");
  68524. document.body.appendChild(a);
  68525. a.style.display = "none";
  68526. a.href = objUrl;
  68527. a.download = "envmap.babylon.hdr";
  68528. a.click();
  68529. };
  68530. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  68531. };
  68532. /**
  68533. * Serializes the data contained in the texture in a binary format.
  68534. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  68535. * as the spherical used in the lighting.
  68536. * @param url The HDR file url.
  68537. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  68538. * @param onError Method called if any error happens during download.
  68539. * @return The packed binary data.
  68540. */
  68541. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  68542. if (onError === void 0) { onError = null; }
  68543. // Needs the url tho create the texture.
  68544. if (!url) {
  68545. return;
  68546. }
  68547. // Check Power of two size.
  68548. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  68549. return;
  68550. }
  68551. // Coming Back in 3.x.
  68552. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  68553. };
  68554. HDRCubeTexture._facesMapping = [
  68555. "right",
  68556. "left",
  68557. "up",
  68558. "down",
  68559. "front",
  68560. "back"
  68561. ];
  68562. return HDRCubeTexture;
  68563. }(BABYLON.BaseTexture));
  68564. BABYLON.HDRCubeTexture = HDRCubeTexture;
  68565. })(BABYLON || (BABYLON = {}));
  68566. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  68567. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  68568. // Huge respect for a such great lib.
  68569. // Earcut license:
  68570. // Copyright (c) 2016, Mapbox
  68571. //
  68572. // Permission to use, copy, modify, and/or distribute this software for any purpose
  68573. // with or without fee is hereby granted, provided that the above copyright notice
  68574. // and this permission notice appear in all copies.
  68575. //
  68576. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  68577. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  68578. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  68579. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  68580. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  68581. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  68582. // THIS SOFTWARE.
  68583. var Earcut;
  68584. (function (Earcut) {
  68585. /**
  68586. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  68587. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  68588. * @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).
  68589. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  68590. */
  68591. function earcut(data, holeIndices, dim) {
  68592. dim = dim || 2;
  68593. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  68594. if (!outerNode)
  68595. return triangles;
  68596. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  68597. if (hasHoles)
  68598. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  68599. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  68600. if (data.length > 80 * dim) {
  68601. minX = maxX = data[0];
  68602. minY = maxY = data[1];
  68603. for (var i = dim; i < outerLen; i += dim) {
  68604. x = data[i];
  68605. y = data[i + 1];
  68606. if (x < minX)
  68607. minX = x;
  68608. if (y < minY)
  68609. minY = y;
  68610. if (x > maxX)
  68611. maxX = x;
  68612. if (y > maxY)
  68613. maxY = y;
  68614. }
  68615. // minX, minY and size are later used to transform coords into integers for z-order calculation
  68616. size = Math.max(maxX - minX, maxY - minY);
  68617. }
  68618. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  68619. return triangles;
  68620. }
  68621. Earcut.earcut = earcut;
  68622. var Node = /** @class */ (function () {
  68623. function Node(i, x, y) {
  68624. this.i = i;
  68625. this.x = x;
  68626. this.y = y;
  68627. this.prev = null;
  68628. this.next = null;
  68629. this.z = null;
  68630. this.prevZ = null;
  68631. this.nextZ = null;
  68632. this.steiner = false;
  68633. }
  68634. return Node;
  68635. }());
  68636. // create a circular doubly linked list from polygon points in the specified winding order
  68637. function linkedList(data, start, end, dim, clockwise) {
  68638. var i, last = null;
  68639. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  68640. for (i = start; i < end; i += dim)
  68641. last = insertNode(i, data[i], data[i + 1], last);
  68642. }
  68643. else {
  68644. for (i = end - dim; i >= start; i -= dim)
  68645. last = insertNode(i, data[i], data[i + 1], last);
  68646. }
  68647. if (last && equals(last, last.next)) {
  68648. removeNode(last);
  68649. last = last.next;
  68650. }
  68651. return last;
  68652. }
  68653. // eliminate colinear or duplicate points
  68654. function filterPoints(start, end) {
  68655. if (!start)
  68656. return start;
  68657. if (!end)
  68658. end = start;
  68659. var p = start, again;
  68660. do {
  68661. again = false;
  68662. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  68663. removeNode(p);
  68664. p = end = p.prev;
  68665. if (p === p.next)
  68666. return undefined;
  68667. again = true;
  68668. }
  68669. else {
  68670. p = p.next;
  68671. }
  68672. } while (again || p !== end);
  68673. return end;
  68674. }
  68675. // main ear slicing loop which triangulates a polygon (given as a linked list)
  68676. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  68677. if (!ear)
  68678. return;
  68679. // interlink polygon nodes in z-order
  68680. if (!pass && size)
  68681. indexCurve(ear, minX, minY, size);
  68682. var stop = ear, prev, next;
  68683. // iterate through ears, slicing them one by one
  68684. while (ear.prev !== ear.next) {
  68685. prev = ear.prev;
  68686. next = ear.next;
  68687. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  68688. // cut off the triangle
  68689. triangles.push(prev.i / dim);
  68690. triangles.push(ear.i / dim);
  68691. triangles.push(next.i / dim);
  68692. removeNode(ear);
  68693. // skipping the next vertice leads to less sliver triangles
  68694. ear = next.next;
  68695. stop = next.next;
  68696. continue;
  68697. }
  68698. ear = next;
  68699. // if we looped through the whole remaining polygon and can't find any more ears
  68700. if (ear === stop) {
  68701. // try filtering points and slicing again
  68702. if (!pass) {
  68703. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  68704. // if this didn't work, try curing all small self-intersections locally
  68705. }
  68706. else if (pass === 1) {
  68707. ear = cureLocalIntersections(ear, triangles, dim);
  68708. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  68709. // as a last resort, try splitting the remaining polygon into two
  68710. }
  68711. else if (pass === 2) {
  68712. splitEarcut(ear, triangles, dim, minX, minY, size);
  68713. }
  68714. break;
  68715. }
  68716. }
  68717. }
  68718. // check whether a polygon node forms a valid ear with adjacent nodes
  68719. function isEar(ear) {
  68720. var a = ear.prev, b = ear, c = ear.next;
  68721. if (area(a, b, c) >= 0)
  68722. return false; // reflex, can't be an ear
  68723. // now make sure we don't have other points inside the potential ear
  68724. var p = ear.next.next;
  68725. while (p !== ear.prev) {
  68726. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68727. area(p.prev, p, p.next) >= 0)
  68728. return false;
  68729. p = p.next;
  68730. }
  68731. return true;
  68732. }
  68733. function isEarHashed(ear, minX, minY, size) {
  68734. var a = ear.prev, b = ear, c = ear.next;
  68735. if (area(a, b, c) >= 0)
  68736. return false; // reflex, can't be an ear
  68737. // triangle bbox; min & max are calculated like this for speed
  68738. 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);
  68739. // z-order range for the current triangle bbox;
  68740. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  68741. // first look for points inside the triangle in increasing z-order
  68742. var p = ear.nextZ;
  68743. while (p && p.z <= maxZ) {
  68744. if (p !== ear.prev &&
  68745. p !== ear.next &&
  68746. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68747. area(p.prev, p, p.next) >= 0)
  68748. return false;
  68749. p = p.nextZ;
  68750. }
  68751. // then look for points in decreasing z-order
  68752. p = ear.prevZ;
  68753. while (p && p.z >= minZ) {
  68754. if (p !== ear.prev &&
  68755. p !== ear.next &&
  68756. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68757. area(p.prev, p, p.next) >= 0)
  68758. return false;
  68759. p = p.prevZ;
  68760. }
  68761. return true;
  68762. }
  68763. // go through all polygon nodes and cure small local self-intersections
  68764. function cureLocalIntersections(start, triangles, dim) {
  68765. var p = start;
  68766. do {
  68767. var a = p.prev, b = p.next.next;
  68768. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  68769. triangles.push(a.i / dim);
  68770. triangles.push(p.i / dim);
  68771. triangles.push(b.i / dim);
  68772. // remove two nodes involved
  68773. removeNode(p);
  68774. removeNode(p.next);
  68775. p = start = b;
  68776. }
  68777. p = p.next;
  68778. } while (p !== start);
  68779. return p;
  68780. }
  68781. // try splitting polygon into two and triangulate them independently
  68782. function splitEarcut(start, triangles, dim, minX, minY, size) {
  68783. // look for a valid diagonal that divides the polygon into two
  68784. var a = start;
  68785. do {
  68786. var b = a.next.next;
  68787. while (b !== a.prev) {
  68788. if (a.i !== b.i && isValidDiagonal(a, b)) {
  68789. // split the polygon in two by the diagonal
  68790. var c = splitPolygon(a, b);
  68791. // filter colinear points around the cuts
  68792. a = filterPoints(a, a.next);
  68793. c = filterPoints(c, c.next);
  68794. // run earcut on each half
  68795. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  68796. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  68797. return;
  68798. }
  68799. b = b.next;
  68800. }
  68801. a = a.next;
  68802. } while (a !== start);
  68803. }
  68804. // link every hole into the outer loop, producing a single-ring polygon without holes
  68805. function eliminateHoles(data, holeIndices, outerNode, dim) {
  68806. var queue = [], i, len, start, end, list;
  68807. for (i = 0, len = holeIndices.length; i < len; i++) {
  68808. start = holeIndices[i] * dim;
  68809. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68810. list = linkedList(data, start, end, dim, false);
  68811. if (list === list.next)
  68812. list.steiner = true;
  68813. queue.push(getLeftmost(list));
  68814. }
  68815. queue.sort(compareX);
  68816. // process holes from left to right
  68817. for (i = 0; i < queue.length; i++) {
  68818. eliminateHole(queue[i], outerNode);
  68819. outerNode = filterPoints(outerNode, outerNode.next);
  68820. }
  68821. return outerNode;
  68822. }
  68823. function compareX(a, b) {
  68824. return a.x - b.x;
  68825. }
  68826. // find a bridge between vertices that connects hole with an outer ring and and link it
  68827. function eliminateHole(hole, outerNode) {
  68828. outerNode = findHoleBridge(hole, outerNode);
  68829. if (outerNode) {
  68830. var b = splitPolygon(outerNode, hole);
  68831. filterPoints(b, b.next);
  68832. }
  68833. }
  68834. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  68835. function findHoleBridge(hole, outerNode) {
  68836. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  68837. // find a segment intersected by a ray from the hole's leftmost point to the left;
  68838. // segment's endpoint with lesser x will be potential connection point
  68839. do {
  68840. if (hy <= p.y && hy >= p.next.y) {
  68841. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  68842. if (x <= hx && x > qx) {
  68843. qx = x;
  68844. if (x === hx) {
  68845. if (hy === p.y)
  68846. return p;
  68847. if (hy === p.next.y)
  68848. return p.next;
  68849. }
  68850. m = p.x < p.next.x ? p : p.next;
  68851. }
  68852. }
  68853. p = p.next;
  68854. } while (p !== outerNode);
  68855. if (!m)
  68856. return null;
  68857. if (hx === qx)
  68858. return m.prev; // hole touches outer segment; pick lower endpoint
  68859. // look for points inside the triangle of hole point, segment intersection and endpoint;
  68860. // if there are no points found, we have a valid connection;
  68861. // otherwise choose the point of the minimum angle with the ray as connection point
  68862. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  68863. p = m.next;
  68864. while (p !== stop) {
  68865. if (hx >= p.x &&
  68866. p.x >= mx &&
  68867. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  68868. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  68869. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  68870. m = p;
  68871. tanMin = tan;
  68872. }
  68873. }
  68874. p = p.next;
  68875. }
  68876. return m;
  68877. }
  68878. // interlink polygon nodes in z-order
  68879. function indexCurve(start, minX, minY, size) {
  68880. var p = start;
  68881. do {
  68882. if (p.z === null)
  68883. p.z = zOrder(p.x, p.y, minX, minY, size);
  68884. p.prevZ = p.prev;
  68885. p.nextZ = p.next;
  68886. p = p.next;
  68887. } while (p !== start);
  68888. p.prevZ.nextZ = null;
  68889. p.prevZ = null;
  68890. sortLinked(p);
  68891. }
  68892. // Simon Tatham's linked list merge sort algorithm
  68893. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  68894. function sortLinked(list) {
  68895. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  68896. do {
  68897. p = list;
  68898. list = null;
  68899. tail = null;
  68900. numMerges = 0;
  68901. while (p) {
  68902. numMerges++;
  68903. q = p;
  68904. pSize = 0;
  68905. for (i = 0; i < inSize; i++) {
  68906. pSize++;
  68907. q = q.nextZ;
  68908. if (!q)
  68909. break;
  68910. }
  68911. qSize = inSize;
  68912. while (pSize > 0 || (qSize > 0 && q)) {
  68913. if (pSize === 0) {
  68914. e = q;
  68915. q = q.nextZ;
  68916. qSize--;
  68917. }
  68918. else if (qSize === 0 || !q) {
  68919. e = p;
  68920. p = p.nextZ;
  68921. pSize--;
  68922. }
  68923. else if (p.z <= q.z) {
  68924. e = p;
  68925. p = p.nextZ;
  68926. pSize--;
  68927. }
  68928. else {
  68929. e = q;
  68930. q = q.nextZ;
  68931. qSize--;
  68932. }
  68933. if (tail)
  68934. tail.nextZ = e;
  68935. else
  68936. list = e;
  68937. e.prevZ = tail;
  68938. tail = e;
  68939. }
  68940. p = q;
  68941. }
  68942. tail.nextZ = null;
  68943. inSize *= 2;
  68944. } while (numMerges > 1);
  68945. return list;
  68946. }
  68947. // z-order of a point given coords and size of the data bounding box
  68948. function zOrder(x, y, minX, minY, size) {
  68949. // coords are transformed into non-negative 15-bit integer range
  68950. x = 32767 * (x - minX) / size;
  68951. y = 32767 * (y - minY) / size;
  68952. x = (x | (x << 8)) & 0x00FF00FF;
  68953. x = (x | (x << 4)) & 0x0F0F0F0F;
  68954. x = (x | (x << 2)) & 0x33333333;
  68955. x = (x | (x << 1)) & 0x55555555;
  68956. y = (y | (y << 8)) & 0x00FF00FF;
  68957. y = (y | (y << 4)) & 0x0F0F0F0F;
  68958. y = (y | (y << 2)) & 0x33333333;
  68959. y = (y | (y << 1)) & 0x55555555;
  68960. return x | (y << 1);
  68961. }
  68962. // find the leftmost node of a polygon ring
  68963. function getLeftmost(start) {
  68964. var p = start, leftmost = start;
  68965. do {
  68966. if (p.x < leftmost.x)
  68967. leftmost = p;
  68968. p = p.next;
  68969. } while (p !== start);
  68970. return leftmost;
  68971. }
  68972. // check if a point lies within a convex triangle
  68973. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  68974. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  68975. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  68976. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  68977. }
  68978. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  68979. function isValidDiagonal(a, b) {
  68980. return a.next.i !== b.i &&
  68981. a.prev.i !== b.i &&
  68982. !intersectsPolygon(a, b) &&
  68983. locallyInside(a, b) &&
  68984. locallyInside(b, a) &&
  68985. middleInside(a, b);
  68986. }
  68987. // signed area of a triangle
  68988. function area(p, q, r) {
  68989. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  68990. }
  68991. // check if two points are equal
  68992. function equals(p1, p2) {
  68993. return p1.x === p2.x && p1.y === p2.y;
  68994. }
  68995. // check if two segments intersect
  68996. function intersects(p1, q1, p2, q2) {
  68997. if ((equals(p1, q1) && equals(p2, q2)) ||
  68998. (equals(p1, q2) && equals(p2, q1)))
  68999. return true;
  69000. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  69001. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  69002. }
  69003. // check if a polygon diagonal intersects any polygon segments
  69004. function intersectsPolygon(a, b) {
  69005. var p = a;
  69006. do {
  69007. if (p.i !== a.i &&
  69008. p.next.i !== a.i &&
  69009. p.i !== b.i &&
  69010. p.next.i !== b.i &&
  69011. intersects(p, p.next, a, b))
  69012. return true;
  69013. p = p.next;
  69014. } while (p !== a);
  69015. return false;
  69016. }
  69017. // check if a polygon diagonal is locally inside the polygon
  69018. function locallyInside(a, b) {
  69019. return area(a.prev, a, a.next) < 0
  69020. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  69021. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  69022. }
  69023. // check if the middle point of a polygon diagonal is inside the polygon
  69024. function middleInside(a, b) {
  69025. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  69026. do {
  69027. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  69028. inside = !inside;
  69029. p = p.next;
  69030. } while (p !== a);
  69031. return inside;
  69032. }
  69033. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  69034. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  69035. function splitPolygon(a, b) {
  69036. 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;
  69037. a.next = b;
  69038. b.prev = a;
  69039. a2.next = an;
  69040. an.prev = a2;
  69041. b2.next = a2;
  69042. a2.prev = b2;
  69043. bp.next = b2;
  69044. b2.prev = bp;
  69045. return b2;
  69046. }
  69047. // create a node and optionally link it with previous one (in a circular doubly linked list)
  69048. function insertNode(i, x, y, last) {
  69049. var p = new Node(i, x, y);
  69050. if (!last) {
  69051. p.prev = p;
  69052. p.next = p;
  69053. }
  69054. else {
  69055. p.next = last.next;
  69056. p.prev = last;
  69057. last.next.prev = p;
  69058. last.next = p;
  69059. }
  69060. return p;
  69061. }
  69062. function removeNode(p) {
  69063. p.next.prev = p.prev;
  69064. p.prev.next = p.next;
  69065. if (p.prevZ)
  69066. p.prevZ.nextZ = p.nextZ;
  69067. if (p.nextZ)
  69068. p.nextZ.prevZ = p.prevZ;
  69069. }
  69070. /**
  69071. * return a percentage difference between the polygon area and its triangulation area;
  69072. * used to verify correctness of triangulation
  69073. */
  69074. function deviation(data, holeIndices, dim, triangles) {
  69075. var hasHoles = holeIndices && holeIndices.length;
  69076. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  69077. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  69078. if (hasHoles) {
  69079. for (var i = 0, len = holeIndices.length; i < len; i++) {
  69080. var start = holeIndices[i] * dim;
  69081. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  69082. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  69083. }
  69084. }
  69085. var trianglesArea = 0;
  69086. for (i = 0; i < triangles.length; i += 3) {
  69087. var a = triangles[i] * dim;
  69088. var b = triangles[i + 1] * dim;
  69089. var c = triangles[i + 2] * dim;
  69090. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  69091. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  69092. }
  69093. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  69094. }
  69095. Earcut.deviation = deviation;
  69096. ;
  69097. function signedArea(data, start, end, dim) {
  69098. var sum = 0;
  69099. for (var i = start, j = end - dim; i < end; i += dim) {
  69100. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  69101. j = i;
  69102. }
  69103. return sum;
  69104. }
  69105. /**
  69106. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  69107. */
  69108. function flatten(data) {
  69109. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  69110. for (var i = 0; i < data.length; i++) {
  69111. for (var j = 0; j < data[i].length; j++) {
  69112. for (var d = 0; d < dim; d++)
  69113. result.vertices.push(data[i][j][d]);
  69114. }
  69115. if (i > 0) {
  69116. holeIndex += data[i - 1].length;
  69117. result.holes.push(holeIndex);
  69118. }
  69119. }
  69120. return result;
  69121. }
  69122. Earcut.flatten = flatten;
  69123. ;
  69124. })(Earcut || (Earcut = {}));
  69125. //# sourceMappingURL=babylon.earcut.js.map
  69126. var BABYLON;
  69127. (function (BABYLON) {
  69128. var IndexedVector2 = /** @class */ (function (_super) {
  69129. __extends(IndexedVector2, _super);
  69130. function IndexedVector2(original, index) {
  69131. var _this = _super.call(this, original.x, original.y) || this;
  69132. _this.index = index;
  69133. return _this;
  69134. }
  69135. return IndexedVector2;
  69136. }(BABYLON.Vector2));
  69137. var PolygonPoints = /** @class */ (function () {
  69138. function PolygonPoints() {
  69139. this.elements = new Array();
  69140. }
  69141. PolygonPoints.prototype.add = function (originalPoints) {
  69142. var _this = this;
  69143. var result = new Array();
  69144. originalPoints.forEach(function (point) {
  69145. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  69146. var newPoint = new IndexedVector2(point, _this.elements.length);
  69147. result.push(newPoint);
  69148. _this.elements.push(newPoint);
  69149. }
  69150. });
  69151. return result;
  69152. };
  69153. PolygonPoints.prototype.computeBounds = function () {
  69154. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  69155. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  69156. this.elements.forEach(function (point) {
  69157. // x
  69158. if (point.x < lmin.x) {
  69159. lmin.x = point.x;
  69160. }
  69161. else if (point.x > lmax.x) {
  69162. lmax.x = point.x;
  69163. }
  69164. // y
  69165. if (point.y < lmin.y) {
  69166. lmin.y = point.y;
  69167. }
  69168. else if (point.y > lmax.y) {
  69169. lmax.y = point.y;
  69170. }
  69171. });
  69172. return {
  69173. min: lmin,
  69174. max: lmax,
  69175. width: lmax.x - lmin.x,
  69176. height: lmax.y - lmin.y
  69177. };
  69178. };
  69179. return PolygonPoints;
  69180. }());
  69181. var Polygon = /** @class */ (function () {
  69182. function Polygon() {
  69183. }
  69184. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  69185. return [
  69186. new BABYLON.Vector2(xmin, ymin),
  69187. new BABYLON.Vector2(xmax, ymin),
  69188. new BABYLON.Vector2(xmax, ymax),
  69189. new BABYLON.Vector2(xmin, ymax)
  69190. ];
  69191. };
  69192. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  69193. if (cx === void 0) { cx = 0; }
  69194. if (cy === void 0) { cy = 0; }
  69195. if (numberOfSides === void 0) { numberOfSides = 32; }
  69196. var result = new Array();
  69197. var angle = 0;
  69198. var increment = (Math.PI * 2) / numberOfSides;
  69199. for (var i = 0; i < numberOfSides; i++) {
  69200. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  69201. angle -= increment;
  69202. }
  69203. return result;
  69204. };
  69205. Polygon.Parse = function (input) {
  69206. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  69207. var i, result = [];
  69208. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  69209. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  69210. }
  69211. return result;
  69212. };
  69213. Polygon.StartingAt = function (x, y) {
  69214. return BABYLON.Path2.StartingAt(x, y);
  69215. };
  69216. return Polygon;
  69217. }());
  69218. BABYLON.Polygon = Polygon;
  69219. var PolygonMeshBuilder = /** @class */ (function () {
  69220. function PolygonMeshBuilder(name, contours, scene) {
  69221. this._points = new PolygonPoints();
  69222. this._outlinepoints = new PolygonPoints();
  69223. this._holes = new Array();
  69224. this._epoints = new Array();
  69225. this._eholes = new Array();
  69226. this._name = name;
  69227. this._scene = scene;
  69228. var points;
  69229. if (contours instanceof BABYLON.Path2) {
  69230. points = contours.getPoints();
  69231. }
  69232. else {
  69233. points = contours;
  69234. }
  69235. this._addToepoint(points);
  69236. this._points.add(points);
  69237. this._outlinepoints.add(points);
  69238. }
  69239. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  69240. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  69241. var p = points_1[_i];
  69242. this._epoints.push(p.x, p.y);
  69243. }
  69244. };
  69245. PolygonMeshBuilder.prototype.addHole = function (hole) {
  69246. this._points.add(hole);
  69247. var holepoints = new PolygonPoints();
  69248. holepoints.add(hole);
  69249. this._holes.push(holepoints);
  69250. this._eholes.push(this._epoints.length / 2);
  69251. this._addToepoint(hole);
  69252. return this;
  69253. };
  69254. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  69255. var _this = this;
  69256. if (updatable === void 0) { updatable = false; }
  69257. if (depth === void 0) { depth = 0; }
  69258. var result = new BABYLON.Mesh(this._name, this._scene);
  69259. var normals = new Array();
  69260. var positions = new Array();
  69261. var uvs = new Array();
  69262. var bounds = this._points.computeBounds();
  69263. this._points.elements.forEach(function (p) {
  69264. normals.push(0, 1.0, 0);
  69265. positions.push(p.x, 0, p.y);
  69266. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  69267. });
  69268. var indices = new Array();
  69269. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  69270. for (var i = 0; i < res.length; i++) {
  69271. indices.push(res[i]);
  69272. }
  69273. if (depth > 0) {
  69274. var positionscount = (positions.length / 3); //get the current pointcount
  69275. this._points.elements.forEach(function (p) {
  69276. normals.push(0, -1.0, 0);
  69277. positions.push(p.x, -depth, p.y);
  69278. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  69279. });
  69280. var totalCount = indices.length;
  69281. for (var i = 0; i < totalCount; i += 3) {
  69282. var i0 = indices[i + 0];
  69283. var i1 = indices[i + 1];
  69284. var i2 = indices[i + 2];
  69285. indices.push(i2 + positionscount);
  69286. indices.push(i1 + positionscount);
  69287. indices.push(i0 + positionscount);
  69288. }
  69289. //Add the sides
  69290. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  69291. this._holes.forEach(function (hole) {
  69292. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  69293. });
  69294. }
  69295. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  69296. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  69297. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  69298. result.setIndices(indices);
  69299. return result;
  69300. };
  69301. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  69302. var StartIndex = positions.length / 3;
  69303. var ulength = 0;
  69304. for (var i = 0; i < points.elements.length; i++) {
  69305. var p = points.elements[i];
  69306. var p1;
  69307. if ((i + 1) > points.elements.length - 1) {
  69308. p1 = points.elements[0];
  69309. }
  69310. else {
  69311. p1 = points.elements[i + 1];
  69312. }
  69313. positions.push(p.x, 0, p.y);
  69314. positions.push(p.x, -depth, p.y);
  69315. positions.push(p1.x, 0, p1.y);
  69316. positions.push(p1.x, -depth, p1.y);
  69317. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  69318. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  69319. var v3 = v2.subtract(v1);
  69320. var v4 = new BABYLON.Vector3(0, 1, 0);
  69321. var vn = BABYLON.Vector3.Cross(v3, v4);
  69322. vn = vn.normalize();
  69323. uvs.push(ulength / bounds.width, 0);
  69324. uvs.push(ulength / bounds.width, 1);
  69325. ulength += v3.length();
  69326. uvs.push((ulength / bounds.width), 0);
  69327. uvs.push((ulength / bounds.width), 1);
  69328. if (!flip) {
  69329. normals.push(-vn.x, -vn.y, -vn.z);
  69330. normals.push(-vn.x, -vn.y, -vn.z);
  69331. normals.push(-vn.x, -vn.y, -vn.z);
  69332. normals.push(-vn.x, -vn.y, -vn.z);
  69333. indices.push(StartIndex);
  69334. indices.push(StartIndex + 1);
  69335. indices.push(StartIndex + 2);
  69336. indices.push(StartIndex + 1);
  69337. indices.push(StartIndex + 3);
  69338. indices.push(StartIndex + 2);
  69339. }
  69340. else {
  69341. normals.push(vn.x, vn.y, vn.z);
  69342. normals.push(vn.x, vn.y, vn.z);
  69343. normals.push(vn.x, vn.y, vn.z);
  69344. normals.push(vn.x, vn.y, vn.z);
  69345. indices.push(StartIndex);
  69346. indices.push(StartIndex + 2);
  69347. indices.push(StartIndex + 1);
  69348. indices.push(StartIndex + 1);
  69349. indices.push(StartIndex + 2);
  69350. indices.push(StartIndex + 3);
  69351. }
  69352. StartIndex += 4;
  69353. }
  69354. ;
  69355. };
  69356. return PolygonMeshBuilder;
  69357. }());
  69358. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  69359. })(BABYLON || (BABYLON = {}));
  69360. //# sourceMappingURL=babylon.polygonMesh.js.map
  69361. var BABYLON;
  69362. (function (BABYLON) {
  69363. // Unique ID when we import meshes from Babylon to CSG
  69364. var currentCSGMeshId = 0;
  69365. // # class Vertex
  69366. // Represents a vertex of a polygon. Use your own vertex class instead of this
  69367. // one to provide additional features like texture coordinates and vertex
  69368. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  69369. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  69370. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  69371. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  69372. // is not used anywhere else.
  69373. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  69374. var Vertex = /** @class */ (function () {
  69375. function Vertex(pos, normal, uv) {
  69376. this.pos = pos;
  69377. this.normal = normal;
  69378. this.uv = uv;
  69379. }
  69380. Vertex.prototype.clone = function () {
  69381. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  69382. };
  69383. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  69384. // orientation of a polygon is flipped.
  69385. Vertex.prototype.flip = function () {
  69386. this.normal = this.normal.scale(-1);
  69387. };
  69388. // Create a new vertex between this vertex and `other` by linearly
  69389. // interpolating all properties using a parameter of `t`. Subclasses should
  69390. // override this to interpolate additional properties.
  69391. Vertex.prototype.interpolate = function (other, t) {
  69392. 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));
  69393. };
  69394. return Vertex;
  69395. }());
  69396. // # class Plane
  69397. // Represents a plane in 3D space.
  69398. var Plane = /** @class */ (function () {
  69399. function Plane(normal, w) {
  69400. this.normal = normal;
  69401. this.w = w;
  69402. }
  69403. Plane.FromPoints = function (a, b, c) {
  69404. var v0 = c.subtract(a);
  69405. var v1 = b.subtract(a);
  69406. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  69407. return null;
  69408. }
  69409. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  69410. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  69411. };
  69412. Plane.prototype.clone = function () {
  69413. return new Plane(this.normal.clone(), this.w);
  69414. };
  69415. Plane.prototype.flip = function () {
  69416. this.normal.scaleInPlace(-1);
  69417. this.w = -this.w;
  69418. };
  69419. // Split `polygon` by this plane if needed, then put the polygon or polygon
  69420. // fragments in the appropriate lists. Coplanar polygons go into either
  69421. // `coplanarFront` or `coplanarBack` depending on their orientation with
  69422. // respect to this plane. Polygons in front or in back of this plane go into
  69423. // either `front` or `back`.
  69424. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  69425. var COPLANAR = 0;
  69426. var FRONT = 1;
  69427. var BACK = 2;
  69428. var SPANNING = 3;
  69429. // Classify each point as well as the entire polygon into one of the above
  69430. // four classes.
  69431. var polygonType = 0;
  69432. var types = [];
  69433. var i;
  69434. var t;
  69435. for (i = 0; i < polygon.vertices.length; i++) {
  69436. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  69437. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  69438. polygonType |= type;
  69439. types.push(type);
  69440. }
  69441. // Put the polygon in the correct list, splitting it when necessary.
  69442. switch (polygonType) {
  69443. case COPLANAR:
  69444. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  69445. break;
  69446. case FRONT:
  69447. front.push(polygon);
  69448. break;
  69449. case BACK:
  69450. back.push(polygon);
  69451. break;
  69452. case SPANNING:
  69453. var f = [], b = [];
  69454. for (i = 0; i < polygon.vertices.length; i++) {
  69455. var j = (i + 1) % polygon.vertices.length;
  69456. var ti = types[i], tj = types[j];
  69457. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  69458. if (ti !== BACK)
  69459. f.push(vi);
  69460. if (ti !== FRONT)
  69461. b.push(ti !== BACK ? vi.clone() : vi);
  69462. if ((ti | tj) === SPANNING) {
  69463. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  69464. var v = vi.interpolate(vj, t);
  69465. f.push(v);
  69466. b.push(v.clone());
  69467. }
  69468. }
  69469. var poly;
  69470. if (f.length >= 3) {
  69471. poly = new Polygon(f, polygon.shared);
  69472. if (poly.plane)
  69473. front.push(poly);
  69474. }
  69475. if (b.length >= 3) {
  69476. poly = new Polygon(b, polygon.shared);
  69477. if (poly.plane)
  69478. back.push(poly);
  69479. }
  69480. break;
  69481. }
  69482. };
  69483. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  69484. // point is on the plane.
  69485. Plane.EPSILON = 1e-5;
  69486. return Plane;
  69487. }());
  69488. // # class Polygon
  69489. // Represents a convex polygon. The vertices used to initialize a polygon must
  69490. // be coplanar and form a convex loop.
  69491. //
  69492. // Each convex polygon has a `shared` property, which is shared between all
  69493. // polygons that are clones of each other or were split from the same polygon.
  69494. // This can be used to define per-polygon properties (such as surface color).
  69495. var Polygon = /** @class */ (function () {
  69496. function Polygon(vertices, shared) {
  69497. this.vertices = vertices;
  69498. this.shared = shared;
  69499. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  69500. }
  69501. Polygon.prototype.clone = function () {
  69502. var vertices = this.vertices.map(function (v) { return v.clone(); });
  69503. return new Polygon(vertices, this.shared);
  69504. };
  69505. Polygon.prototype.flip = function () {
  69506. this.vertices.reverse().map(function (v) { v.flip(); });
  69507. this.plane.flip();
  69508. };
  69509. return Polygon;
  69510. }());
  69511. // # class Node
  69512. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  69513. // by picking a polygon to split along. That polygon (and all other coplanar
  69514. // polygons) are added directly to that node and the other polygons are added to
  69515. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  69516. // no distinction between internal and leaf nodes.
  69517. var Node = /** @class */ (function () {
  69518. function Node(polygons) {
  69519. this.plane = null;
  69520. this.front = null;
  69521. this.back = null;
  69522. this.polygons = new Array();
  69523. if (polygons) {
  69524. this.build(polygons);
  69525. }
  69526. }
  69527. Node.prototype.clone = function () {
  69528. var node = new Node();
  69529. node.plane = this.plane && this.plane.clone();
  69530. node.front = this.front && this.front.clone();
  69531. node.back = this.back && this.back.clone();
  69532. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  69533. return node;
  69534. };
  69535. // Convert solid space to empty space and empty space to solid space.
  69536. Node.prototype.invert = function () {
  69537. for (var i = 0; i < this.polygons.length; i++) {
  69538. this.polygons[i].flip();
  69539. }
  69540. if (this.plane) {
  69541. this.plane.flip();
  69542. }
  69543. if (this.front) {
  69544. this.front.invert();
  69545. }
  69546. if (this.back) {
  69547. this.back.invert();
  69548. }
  69549. var temp = this.front;
  69550. this.front = this.back;
  69551. this.back = temp;
  69552. };
  69553. // Recursively remove all polygons in `polygons` that are inside this BSP
  69554. // tree.
  69555. Node.prototype.clipPolygons = function (polygons) {
  69556. if (!this.plane)
  69557. return polygons.slice();
  69558. var front = new Array(), back = new Array();
  69559. for (var i = 0; i < polygons.length; i++) {
  69560. this.plane.splitPolygon(polygons[i], front, back, front, back);
  69561. }
  69562. if (this.front) {
  69563. front = this.front.clipPolygons(front);
  69564. }
  69565. if (this.back) {
  69566. back = this.back.clipPolygons(back);
  69567. }
  69568. else {
  69569. back = [];
  69570. }
  69571. return front.concat(back);
  69572. };
  69573. // Remove all polygons in this BSP tree that are inside the other BSP tree
  69574. // `bsp`.
  69575. Node.prototype.clipTo = function (bsp) {
  69576. this.polygons = bsp.clipPolygons(this.polygons);
  69577. if (this.front)
  69578. this.front.clipTo(bsp);
  69579. if (this.back)
  69580. this.back.clipTo(bsp);
  69581. };
  69582. // Return a list of all polygons in this BSP tree.
  69583. Node.prototype.allPolygons = function () {
  69584. var polygons = this.polygons.slice();
  69585. if (this.front)
  69586. polygons = polygons.concat(this.front.allPolygons());
  69587. if (this.back)
  69588. polygons = polygons.concat(this.back.allPolygons());
  69589. return polygons;
  69590. };
  69591. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  69592. // new polygons are filtered down to the bottom of the tree and become new
  69593. // nodes there. Each set of polygons is partitioned using the first polygon
  69594. // (no heuristic is used to pick a good split).
  69595. Node.prototype.build = function (polygons) {
  69596. if (!polygons.length)
  69597. return;
  69598. if (!this.plane)
  69599. this.plane = polygons[0].plane.clone();
  69600. var front = new Array(), back = new Array();
  69601. for (var i = 0; i < polygons.length; i++) {
  69602. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  69603. }
  69604. if (front.length) {
  69605. if (!this.front)
  69606. this.front = new Node();
  69607. this.front.build(front);
  69608. }
  69609. if (back.length) {
  69610. if (!this.back)
  69611. this.back = new Node();
  69612. this.back.build(back);
  69613. }
  69614. };
  69615. return Node;
  69616. }());
  69617. var CSG = /** @class */ (function () {
  69618. function CSG() {
  69619. this.polygons = new Array();
  69620. }
  69621. // Convert BABYLON.Mesh to BABYLON.CSG
  69622. CSG.FromMesh = function (mesh) {
  69623. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  69624. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  69625. if (mesh instanceof BABYLON.Mesh) {
  69626. mesh.computeWorldMatrix(true);
  69627. matrix = mesh.getWorldMatrix();
  69628. meshPosition = mesh.position.clone();
  69629. meshRotation = mesh.rotation.clone();
  69630. if (mesh.rotationQuaternion) {
  69631. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  69632. }
  69633. meshScaling = mesh.scaling.clone();
  69634. }
  69635. else {
  69636. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  69637. }
  69638. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69639. var subMeshes = mesh.subMeshes;
  69640. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  69641. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  69642. vertices = [];
  69643. for (var j = 0; j < 3; j++) {
  69644. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  69645. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  69646. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  69647. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  69648. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  69649. vertex = new Vertex(position, normal, uv);
  69650. vertices.push(vertex);
  69651. }
  69652. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  69653. // To handle the case of degenerated triangle
  69654. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  69655. if (polygon.plane)
  69656. polygons.push(polygon);
  69657. }
  69658. }
  69659. var csg = CSG.FromPolygons(polygons);
  69660. csg.matrix = matrix;
  69661. csg.position = meshPosition;
  69662. csg.rotation = meshRotation;
  69663. csg.scaling = meshScaling;
  69664. csg.rotationQuaternion = meshRotationQuaternion;
  69665. currentCSGMeshId++;
  69666. return csg;
  69667. };
  69668. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  69669. CSG.FromPolygons = function (polygons) {
  69670. var csg = new CSG();
  69671. csg.polygons = polygons;
  69672. return csg;
  69673. };
  69674. CSG.prototype.clone = function () {
  69675. var csg = new CSG();
  69676. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  69677. csg.copyTransformAttributes(this);
  69678. return csg;
  69679. };
  69680. CSG.prototype.union = function (csg) {
  69681. var a = new Node(this.clone().polygons);
  69682. var b = new Node(csg.clone().polygons);
  69683. a.clipTo(b);
  69684. b.clipTo(a);
  69685. b.invert();
  69686. b.clipTo(a);
  69687. b.invert();
  69688. a.build(b.allPolygons());
  69689. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69690. };
  69691. CSG.prototype.unionInPlace = function (csg) {
  69692. var a = new Node(this.polygons);
  69693. var b = new Node(csg.polygons);
  69694. a.clipTo(b);
  69695. b.clipTo(a);
  69696. b.invert();
  69697. b.clipTo(a);
  69698. b.invert();
  69699. a.build(b.allPolygons());
  69700. this.polygons = a.allPolygons();
  69701. };
  69702. CSG.prototype.subtract = function (csg) {
  69703. var a = new Node(this.clone().polygons);
  69704. var b = new Node(csg.clone().polygons);
  69705. a.invert();
  69706. a.clipTo(b);
  69707. b.clipTo(a);
  69708. b.invert();
  69709. b.clipTo(a);
  69710. b.invert();
  69711. a.build(b.allPolygons());
  69712. a.invert();
  69713. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69714. };
  69715. CSG.prototype.subtractInPlace = function (csg) {
  69716. var a = new Node(this.polygons);
  69717. var b = new Node(csg.polygons);
  69718. a.invert();
  69719. a.clipTo(b);
  69720. b.clipTo(a);
  69721. b.invert();
  69722. b.clipTo(a);
  69723. b.invert();
  69724. a.build(b.allPolygons());
  69725. a.invert();
  69726. this.polygons = a.allPolygons();
  69727. };
  69728. CSG.prototype.intersect = function (csg) {
  69729. var a = new Node(this.clone().polygons);
  69730. var b = new Node(csg.clone().polygons);
  69731. a.invert();
  69732. b.clipTo(a);
  69733. b.invert();
  69734. a.clipTo(b);
  69735. b.clipTo(a);
  69736. a.build(b.allPolygons());
  69737. a.invert();
  69738. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69739. };
  69740. CSG.prototype.intersectInPlace = function (csg) {
  69741. var a = new Node(this.polygons);
  69742. var b = new Node(csg.polygons);
  69743. a.invert();
  69744. b.clipTo(a);
  69745. b.invert();
  69746. a.clipTo(b);
  69747. b.clipTo(a);
  69748. a.build(b.allPolygons());
  69749. a.invert();
  69750. this.polygons = a.allPolygons();
  69751. };
  69752. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  69753. // not modified.
  69754. CSG.prototype.inverse = function () {
  69755. var csg = this.clone();
  69756. csg.inverseInPlace();
  69757. return csg;
  69758. };
  69759. CSG.prototype.inverseInPlace = function () {
  69760. this.polygons.map(function (p) { p.flip(); });
  69761. };
  69762. // This is used to keep meshes transformations so they can be restored
  69763. // when we build back a Babylon Mesh
  69764. // NB : All CSG operations are performed in world coordinates
  69765. CSG.prototype.copyTransformAttributes = function (csg) {
  69766. this.matrix = csg.matrix;
  69767. this.position = csg.position;
  69768. this.rotation = csg.rotation;
  69769. this.scaling = csg.scaling;
  69770. this.rotationQuaternion = csg.rotationQuaternion;
  69771. return this;
  69772. };
  69773. // Build Raw mesh from CSG
  69774. // Coordinates here are in world space
  69775. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  69776. var matrix = this.matrix.clone();
  69777. matrix.invert();
  69778. 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;
  69779. if (keepSubMeshes) {
  69780. // Sort Polygons, since subMeshes are indices range
  69781. polygons.sort(function (a, b) {
  69782. if (a.shared.meshId === b.shared.meshId) {
  69783. return a.shared.subMeshId - b.shared.subMeshId;
  69784. }
  69785. else {
  69786. return a.shared.meshId - b.shared.meshId;
  69787. }
  69788. });
  69789. }
  69790. for (var i = 0, il = polygons.length; i < il; i++) {
  69791. polygon = polygons[i];
  69792. // Building SubMeshes
  69793. if (!subMesh_dict[polygon.shared.meshId]) {
  69794. subMesh_dict[polygon.shared.meshId] = {};
  69795. }
  69796. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  69797. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  69798. indexStart: +Infinity,
  69799. indexEnd: -Infinity,
  69800. materialIndex: polygon.shared.materialIndex
  69801. };
  69802. }
  69803. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  69804. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  69805. polygonIndices[0] = 0;
  69806. polygonIndices[1] = j - 1;
  69807. polygonIndices[2] = j;
  69808. for (var k = 0; k < 3; k++) {
  69809. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  69810. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  69811. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  69812. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  69813. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  69814. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  69815. // Check if 2 points can be merged
  69816. if (!(typeof vertex_idx !== 'undefined' &&
  69817. normals[vertex_idx * 3] === localNormal.x &&
  69818. normals[vertex_idx * 3 + 1] === localNormal.y &&
  69819. normals[vertex_idx * 3 + 2] === localNormal.z &&
  69820. uvs[vertex_idx * 2] === uv.x &&
  69821. uvs[vertex_idx * 2 + 1] === uv.y)) {
  69822. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  69823. uvs.push(uv.x, uv.y);
  69824. normals.push(normal.x, normal.y, normal.z);
  69825. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  69826. }
  69827. indices.push(vertex_idx);
  69828. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  69829. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  69830. currentIndex++;
  69831. }
  69832. }
  69833. }
  69834. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  69835. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  69836. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  69837. mesh.setIndices(indices, null);
  69838. if (keepSubMeshes) {
  69839. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  69840. var materialIndexOffset = 0, materialMaxIndex;
  69841. mesh.subMeshes = new Array();
  69842. for (var m in subMesh_dict) {
  69843. materialMaxIndex = -1;
  69844. for (var sm in subMesh_dict[m]) {
  69845. subMesh_obj = subMesh_dict[m][sm];
  69846. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  69847. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  69848. }
  69849. materialIndexOffset += ++materialMaxIndex;
  69850. }
  69851. }
  69852. return mesh;
  69853. };
  69854. // Build Mesh from CSG taking material and transforms into account
  69855. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  69856. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  69857. mesh.material = material;
  69858. mesh.position.copyFrom(this.position);
  69859. mesh.rotation.copyFrom(this.rotation);
  69860. if (this.rotationQuaternion) {
  69861. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  69862. }
  69863. mesh.scaling.copyFrom(this.scaling);
  69864. mesh.computeWorldMatrix(true);
  69865. return mesh;
  69866. };
  69867. return CSG;
  69868. }());
  69869. BABYLON.CSG = CSG;
  69870. })(BABYLON || (BABYLON = {}));
  69871. //# sourceMappingURL=babylon.csg.js.map
  69872. var BABYLON;
  69873. (function (BABYLON) {
  69874. var LensFlare = /** @class */ (function () {
  69875. function LensFlare(size, position, color, imgUrl, system) {
  69876. this.size = size;
  69877. this.position = position;
  69878. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  69879. this.color = color || new BABYLON.Color3(1, 1, 1);
  69880. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  69881. this._system = system;
  69882. system.lensFlares.push(this);
  69883. }
  69884. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  69885. return new LensFlare(size, position, color, imgUrl, system);
  69886. };
  69887. LensFlare.prototype.dispose = function () {
  69888. if (this.texture) {
  69889. this.texture.dispose();
  69890. }
  69891. // Remove from scene
  69892. var index = this._system.lensFlares.indexOf(this);
  69893. this._system.lensFlares.splice(index, 1);
  69894. };
  69895. ;
  69896. return LensFlare;
  69897. }());
  69898. BABYLON.LensFlare = LensFlare;
  69899. })(BABYLON || (BABYLON = {}));
  69900. //# sourceMappingURL=babylon.lensFlare.js.map
  69901. var BABYLON;
  69902. (function (BABYLON) {
  69903. var LensFlareSystem = /** @class */ (function () {
  69904. function LensFlareSystem(name, emitter, scene) {
  69905. this.name = name;
  69906. this.lensFlares = new Array();
  69907. this.borderLimit = 300;
  69908. this.viewportBorder = 0;
  69909. this.layerMask = 0x0FFFFFFF;
  69910. this._vertexBuffers = {};
  69911. this._isEnabled = true;
  69912. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69913. this._emitter = emitter;
  69914. this.id = name;
  69915. scene.lensFlareSystems.push(this);
  69916. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  69917. var engine = scene.getEngine();
  69918. // VBO
  69919. var vertices = [];
  69920. vertices.push(1, 1);
  69921. vertices.push(-1, 1);
  69922. vertices.push(-1, -1);
  69923. vertices.push(1, -1);
  69924. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69925. // Indices
  69926. var indices = [];
  69927. indices.push(0);
  69928. indices.push(1);
  69929. indices.push(2);
  69930. indices.push(0);
  69931. indices.push(2);
  69932. indices.push(3);
  69933. this._indexBuffer = engine.createIndexBuffer(indices);
  69934. // Effects
  69935. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  69936. }
  69937. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  69938. get: function () {
  69939. return this._isEnabled;
  69940. },
  69941. set: function (value) {
  69942. this._isEnabled = value;
  69943. },
  69944. enumerable: true,
  69945. configurable: true
  69946. });
  69947. LensFlareSystem.prototype.getScene = function () {
  69948. return this._scene;
  69949. };
  69950. LensFlareSystem.prototype.getEmitter = function () {
  69951. return this._emitter;
  69952. };
  69953. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  69954. this._emitter = newEmitter;
  69955. };
  69956. LensFlareSystem.prototype.getEmitterPosition = function () {
  69957. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  69958. };
  69959. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  69960. var position = this.getEmitterPosition();
  69961. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  69962. this._positionX = position.x;
  69963. this._positionY = position.y;
  69964. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  69965. if (this.viewportBorder > 0) {
  69966. globalViewport.x -= this.viewportBorder;
  69967. globalViewport.y -= this.viewportBorder;
  69968. globalViewport.width += this.viewportBorder * 2;
  69969. globalViewport.height += this.viewportBorder * 2;
  69970. position.x += this.viewportBorder;
  69971. position.y += this.viewportBorder;
  69972. this._positionX += this.viewportBorder;
  69973. this._positionY += this.viewportBorder;
  69974. }
  69975. if (position.z > 0) {
  69976. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  69977. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  69978. return true;
  69979. }
  69980. return true;
  69981. }
  69982. return false;
  69983. };
  69984. LensFlareSystem.prototype._isVisible = function () {
  69985. if (!this._isEnabled || !this._scene.activeCamera) {
  69986. return false;
  69987. }
  69988. var emitterPosition = this.getEmitterPosition();
  69989. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  69990. var distance = direction.length();
  69991. direction.normalize();
  69992. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  69993. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  69994. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  69995. };
  69996. LensFlareSystem.prototype.render = function () {
  69997. if (!this._effect.isReady() || !this._scene.activeCamera)
  69998. return false;
  69999. var engine = this._scene.getEngine();
  70000. var viewport = this._scene.activeCamera.viewport;
  70001. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  70002. // Position
  70003. if (!this.computeEffectivePosition(globalViewport)) {
  70004. return false;
  70005. }
  70006. // Visibility
  70007. if (!this._isVisible()) {
  70008. return false;
  70009. }
  70010. // Intensity
  70011. var awayX;
  70012. var awayY;
  70013. if (this._positionX < this.borderLimit + globalViewport.x) {
  70014. awayX = this.borderLimit + globalViewport.x - this._positionX;
  70015. }
  70016. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  70017. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  70018. }
  70019. else {
  70020. awayX = 0;
  70021. }
  70022. if (this._positionY < this.borderLimit + globalViewport.y) {
  70023. awayY = this.borderLimit + globalViewport.y - this._positionY;
  70024. }
  70025. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  70026. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  70027. }
  70028. else {
  70029. awayY = 0;
  70030. }
  70031. var away = (awayX > awayY) ? awayX : awayY;
  70032. away -= this.viewportBorder;
  70033. if (away > this.borderLimit) {
  70034. away = this.borderLimit;
  70035. }
  70036. var intensity = 1.0 - (away / this.borderLimit);
  70037. if (intensity < 0) {
  70038. return false;
  70039. }
  70040. if (intensity > 1.0) {
  70041. intensity = 1.0;
  70042. }
  70043. if (this.viewportBorder > 0) {
  70044. globalViewport.x += this.viewportBorder;
  70045. globalViewport.y += this.viewportBorder;
  70046. globalViewport.width -= this.viewportBorder * 2;
  70047. globalViewport.height -= this.viewportBorder * 2;
  70048. this._positionX -= this.viewportBorder;
  70049. this._positionY -= this.viewportBorder;
  70050. }
  70051. // Position
  70052. var centerX = globalViewport.x + globalViewport.width / 2;
  70053. var centerY = globalViewport.y + globalViewport.height / 2;
  70054. var distX = centerX - this._positionX;
  70055. var distY = centerY - this._positionY;
  70056. // Effects
  70057. engine.enableEffect(this._effect);
  70058. engine.setState(false);
  70059. engine.setDepthBuffer(false);
  70060. // VBOs
  70061. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70062. // Flares
  70063. for (var index = 0; index < this.lensFlares.length; index++) {
  70064. var flare = this.lensFlares[index];
  70065. engine.setAlphaMode(flare.alphaMode);
  70066. var x = centerX - (distX * flare.position);
  70067. var y = centerY - (distY * flare.position);
  70068. var cw = flare.size;
  70069. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  70070. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  70071. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  70072. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  70073. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  70074. // Texture
  70075. this._effect.setTexture("textureSampler", flare.texture);
  70076. // Color
  70077. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  70078. // Draw order
  70079. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70080. }
  70081. engine.setDepthBuffer(true);
  70082. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70083. return true;
  70084. };
  70085. LensFlareSystem.prototype.dispose = function () {
  70086. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70087. if (vertexBuffer) {
  70088. vertexBuffer.dispose();
  70089. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70090. }
  70091. if (this._indexBuffer) {
  70092. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70093. this._indexBuffer = null;
  70094. }
  70095. while (this.lensFlares.length) {
  70096. this.lensFlares[0].dispose();
  70097. }
  70098. // Remove from scene
  70099. var index = this._scene.lensFlareSystems.indexOf(this);
  70100. this._scene.lensFlareSystems.splice(index, 1);
  70101. };
  70102. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  70103. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  70104. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  70105. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  70106. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  70107. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  70108. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  70109. var parsedFlare = parsedLensFlareSystem.flares[index];
  70110. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  70111. }
  70112. return lensFlareSystem;
  70113. };
  70114. LensFlareSystem.prototype.serialize = function () {
  70115. var serializationObject = {};
  70116. serializationObject.id = this.id;
  70117. serializationObject.name = this.name;
  70118. serializationObject.emitterId = this.getEmitter().id;
  70119. serializationObject.borderLimit = this.borderLimit;
  70120. serializationObject.flares = [];
  70121. for (var index = 0; index < this.lensFlares.length; index++) {
  70122. var flare = this.lensFlares[index];
  70123. serializationObject.flares.push({
  70124. size: flare.size,
  70125. position: flare.position,
  70126. color: flare.color.asArray(),
  70127. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  70128. });
  70129. }
  70130. return serializationObject;
  70131. };
  70132. return LensFlareSystem;
  70133. }());
  70134. BABYLON.LensFlareSystem = LensFlareSystem;
  70135. })(BABYLON || (BABYLON = {}));
  70136. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  70137. var BABYLON;
  70138. (function (BABYLON) {
  70139. /**
  70140. * This is a holder class for the physics joint created by the physics plugin.
  70141. * It holds a set of functions to control the underlying joint.
  70142. */
  70143. var PhysicsJoint = /** @class */ (function () {
  70144. function PhysicsJoint(type, jointData) {
  70145. this.type = type;
  70146. this.jointData = jointData;
  70147. jointData.nativeParams = jointData.nativeParams || {};
  70148. }
  70149. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  70150. get: function () {
  70151. return this._physicsJoint;
  70152. },
  70153. set: function (newJoint) {
  70154. if (this._physicsJoint) {
  70155. //remove from the wolrd
  70156. }
  70157. this._physicsJoint = newJoint;
  70158. },
  70159. enumerable: true,
  70160. configurable: true
  70161. });
  70162. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  70163. set: function (physicsPlugin) {
  70164. this._physicsPlugin = physicsPlugin;
  70165. },
  70166. enumerable: true,
  70167. configurable: true
  70168. });
  70169. /**
  70170. * Execute a function that is physics-plugin specific.
  70171. * @param {Function} func the function that will be executed.
  70172. * It accepts two parameters: the physics world and the physics joint.
  70173. */
  70174. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  70175. func(this._physicsPlugin.world, this._physicsJoint);
  70176. };
  70177. //TODO check if the native joints are the same
  70178. //Joint Types
  70179. PhysicsJoint.DistanceJoint = 0;
  70180. PhysicsJoint.HingeJoint = 1;
  70181. PhysicsJoint.BallAndSocketJoint = 2;
  70182. PhysicsJoint.WheelJoint = 3;
  70183. PhysicsJoint.SliderJoint = 4;
  70184. //OIMO
  70185. PhysicsJoint.PrismaticJoint = 5;
  70186. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  70187. PhysicsJoint.UniversalJoint = 6;
  70188. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  70189. //Cannon
  70190. //Similar to a Ball-Joint. Different in params
  70191. PhysicsJoint.PointToPointJoint = 8;
  70192. //Cannon only at the moment
  70193. PhysicsJoint.SpringJoint = 9;
  70194. PhysicsJoint.LockJoint = 10;
  70195. return PhysicsJoint;
  70196. }());
  70197. BABYLON.PhysicsJoint = PhysicsJoint;
  70198. /**
  70199. * A class representing a physics distance joint.
  70200. */
  70201. var DistanceJoint = /** @class */ (function (_super) {
  70202. __extends(DistanceJoint, _super);
  70203. function DistanceJoint(jointData) {
  70204. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  70205. }
  70206. /**
  70207. * Update the predefined distance.
  70208. */
  70209. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  70210. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  70211. };
  70212. return DistanceJoint;
  70213. }(PhysicsJoint));
  70214. BABYLON.DistanceJoint = DistanceJoint;
  70215. var MotorEnabledJoint = /** @class */ (function (_super) {
  70216. __extends(MotorEnabledJoint, _super);
  70217. function MotorEnabledJoint(type, jointData) {
  70218. return _super.call(this, type, jointData) || this;
  70219. }
  70220. /**
  70221. * Set the motor values.
  70222. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70223. * @param {number} force the force to apply
  70224. * @param {number} maxForce max force for this motor.
  70225. */
  70226. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  70227. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  70228. };
  70229. /**
  70230. * Set the motor's limits.
  70231. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70232. */
  70233. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  70234. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  70235. };
  70236. return MotorEnabledJoint;
  70237. }(PhysicsJoint));
  70238. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  70239. /**
  70240. * This class represents a single hinge physics joint
  70241. */
  70242. var HingeJoint = /** @class */ (function (_super) {
  70243. __extends(HingeJoint, _super);
  70244. function HingeJoint(jointData) {
  70245. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  70246. }
  70247. /**
  70248. * Set the motor values.
  70249. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70250. * @param {number} force the force to apply
  70251. * @param {number} maxForce max force for this motor.
  70252. */
  70253. HingeJoint.prototype.setMotor = function (force, maxForce) {
  70254. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  70255. };
  70256. /**
  70257. * Set the motor's limits.
  70258. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70259. */
  70260. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  70261. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  70262. };
  70263. return HingeJoint;
  70264. }(MotorEnabledJoint));
  70265. BABYLON.HingeJoint = HingeJoint;
  70266. /**
  70267. * This class represents a dual hinge physics joint (same as wheel joint)
  70268. */
  70269. var Hinge2Joint = /** @class */ (function (_super) {
  70270. __extends(Hinge2Joint, _super);
  70271. function Hinge2Joint(jointData) {
  70272. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  70273. }
  70274. /**
  70275. * Set the motor values.
  70276. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70277. * @param {number} force the force to apply
  70278. * @param {number} maxForce max force for this motor.
  70279. * @param {motorIndex} the motor's index, 0 or 1.
  70280. */
  70281. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  70282. if (motorIndex === void 0) { motorIndex = 0; }
  70283. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  70284. };
  70285. /**
  70286. * Set the motor limits.
  70287. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70288. * @param {number} upperLimit the upper limit
  70289. * @param {number} lowerLimit lower limit
  70290. * @param {motorIndex} the motor's index, 0 or 1.
  70291. */
  70292. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  70293. if (motorIndex === void 0) { motorIndex = 0; }
  70294. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  70295. };
  70296. return Hinge2Joint;
  70297. }(MotorEnabledJoint));
  70298. BABYLON.Hinge2Joint = Hinge2Joint;
  70299. })(BABYLON || (BABYLON = {}));
  70300. //# sourceMappingURL=babylon.physicsJoint.js.map
  70301. var BABYLON;
  70302. (function (BABYLON) {
  70303. var PhysicsImpostor = /** @class */ (function () {
  70304. function PhysicsImpostor(object, type, _options, _scene) {
  70305. if (_options === void 0) { _options = { mass: 0 }; }
  70306. var _this = this;
  70307. this.object = object;
  70308. this.type = type;
  70309. this._options = _options;
  70310. this._scene = _scene;
  70311. this._bodyUpdateRequired = false;
  70312. this._onBeforePhysicsStepCallbacks = new Array();
  70313. this._onAfterPhysicsStepCallbacks = new Array();
  70314. this._onPhysicsCollideCallbacks = [];
  70315. this._deltaPosition = BABYLON.Vector3.Zero();
  70316. this._isDisposed = false;
  70317. //temp variables for parent rotation calculations
  70318. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  70319. this._tmpQuat = new BABYLON.Quaternion();
  70320. this._tmpQuat2 = new BABYLON.Quaternion();
  70321. /**
  70322. * this function is executed by the physics engine.
  70323. */
  70324. this.beforeStep = function () {
  70325. if (!_this._physicsEngine) {
  70326. return;
  70327. }
  70328. _this.object.translate(_this._deltaPosition, -1);
  70329. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  70330. _this.object.computeWorldMatrix(false);
  70331. if (_this.object.parent && _this.object.rotationQuaternion) {
  70332. _this.getParentsRotation();
  70333. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  70334. }
  70335. else {
  70336. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  70337. }
  70338. if (!_this._options.disableBidirectionalTransformation) {
  70339. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  70340. }
  70341. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  70342. func(_this);
  70343. });
  70344. };
  70345. /**
  70346. * this function is executed by the physics engine.
  70347. */
  70348. this.afterStep = function () {
  70349. if (!_this._physicsEngine) {
  70350. return;
  70351. }
  70352. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  70353. func(_this);
  70354. });
  70355. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  70356. // object has now its world rotation. needs to be converted to local.
  70357. if (_this.object.parent && _this.object.rotationQuaternion) {
  70358. _this.getParentsRotation();
  70359. _this._tmpQuat.conjugateInPlace();
  70360. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  70361. }
  70362. // take the position set and make it the absolute position of this object.
  70363. _this.object.setAbsolutePosition(_this.object.position);
  70364. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  70365. _this.object.translate(_this._deltaPosition, 1);
  70366. };
  70367. /**
  70368. * Legacy collision detection event support
  70369. */
  70370. this.onCollideEvent = null;
  70371. //event and body object due to cannon's event-based architecture.
  70372. this.onCollide = function (e) {
  70373. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  70374. return;
  70375. }
  70376. if (!_this._physicsEngine) {
  70377. return;
  70378. }
  70379. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  70380. if (otherImpostor) {
  70381. // Legacy collision detection event support
  70382. if (_this.onCollideEvent) {
  70383. _this.onCollideEvent(_this, otherImpostor);
  70384. }
  70385. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  70386. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  70387. }).forEach(function (obj) {
  70388. obj.callback(_this, otherImpostor);
  70389. });
  70390. }
  70391. };
  70392. //sanity check!
  70393. if (!this.object) {
  70394. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  70395. return;
  70396. }
  70397. //legacy support for old syntax.
  70398. if (!this._scene && object.getScene) {
  70399. this._scene = object.getScene();
  70400. }
  70401. if (!this._scene) {
  70402. return;
  70403. }
  70404. this._physicsEngine = this._scene.getPhysicsEngine();
  70405. if (!this._physicsEngine) {
  70406. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  70407. }
  70408. else {
  70409. //set the object's quaternion, if not set
  70410. if (!this.object.rotationQuaternion) {
  70411. if (this.object.rotation) {
  70412. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  70413. }
  70414. else {
  70415. this.object.rotationQuaternion = new BABYLON.Quaternion();
  70416. }
  70417. }
  70418. //default options params
  70419. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  70420. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  70421. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  70422. this._joints = [];
  70423. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  70424. if (!this.object.parent || this._options.ignoreParent) {
  70425. this._init();
  70426. }
  70427. else if (this.object.parent.physicsImpostor) {
  70428. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  70429. }
  70430. }
  70431. }
  70432. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  70433. get: function () {
  70434. return this._isDisposed;
  70435. },
  70436. enumerable: true,
  70437. configurable: true
  70438. });
  70439. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  70440. get: function () {
  70441. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  70442. },
  70443. set: function (value) {
  70444. this.setMass(value);
  70445. },
  70446. enumerable: true,
  70447. configurable: true
  70448. });
  70449. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  70450. get: function () {
  70451. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  70452. },
  70453. set: function (value) {
  70454. if (!this._physicsEngine) {
  70455. return;
  70456. }
  70457. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  70458. },
  70459. enumerable: true,
  70460. configurable: true
  70461. });
  70462. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  70463. get: function () {
  70464. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  70465. },
  70466. set: function (value) {
  70467. if (!this._physicsEngine) {
  70468. return;
  70469. }
  70470. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  70471. },
  70472. enumerable: true,
  70473. configurable: true
  70474. });
  70475. /**
  70476. * This function will completly initialize this impostor.
  70477. * It will create a new body - but only if this mesh has no parent.
  70478. * If it has, this impostor will not be used other than to define the impostor
  70479. * of the child mesh.
  70480. */
  70481. PhysicsImpostor.prototype._init = function () {
  70482. if (!this._physicsEngine) {
  70483. return;
  70484. }
  70485. this._physicsEngine.removeImpostor(this);
  70486. this.physicsBody = null;
  70487. this._parent = this._parent || this._getPhysicsParent();
  70488. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  70489. this._physicsEngine.addImpostor(this);
  70490. }
  70491. };
  70492. PhysicsImpostor.prototype._getPhysicsParent = function () {
  70493. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  70494. var parentMesh = this.object.parent;
  70495. return parentMesh.physicsImpostor;
  70496. }
  70497. return null;
  70498. };
  70499. /**
  70500. * Should a new body be generated.
  70501. */
  70502. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  70503. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  70504. };
  70505. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  70506. this.forceUpdate();
  70507. };
  70508. /**
  70509. * Force a regeneration of this or the parent's impostor's body.
  70510. * Use under cautious - This will remove all joints already implemented.
  70511. */
  70512. PhysicsImpostor.prototype.forceUpdate = function () {
  70513. this._init();
  70514. if (this.parent && !this._options.ignoreParent) {
  70515. this.parent.forceUpdate();
  70516. }
  70517. };
  70518. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  70519. /*public get mesh(): AbstractMesh {
  70520. return this._mesh;
  70521. }*/
  70522. /**
  70523. * Gets the body that holds this impostor. Either its own, or its parent.
  70524. */
  70525. get: function () {
  70526. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  70527. },
  70528. /**
  70529. * Set the physics body. Used mainly by the physics engine/plugin
  70530. */
  70531. set: function (physicsBody) {
  70532. if (this._physicsBody && this._physicsEngine) {
  70533. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  70534. }
  70535. this._physicsBody = physicsBody;
  70536. this.resetUpdateFlags();
  70537. },
  70538. enumerable: true,
  70539. configurable: true
  70540. });
  70541. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  70542. get: function () {
  70543. return !this._options.ignoreParent && this._parent ? this._parent : null;
  70544. },
  70545. set: function (value) {
  70546. this._parent = value;
  70547. },
  70548. enumerable: true,
  70549. configurable: true
  70550. });
  70551. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  70552. this._bodyUpdateRequired = false;
  70553. };
  70554. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  70555. if (this.object.getBoundingInfo) {
  70556. var q = this.object.rotationQuaternion;
  70557. //reset rotation
  70558. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  70559. //calculate the world matrix with no rotation
  70560. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  70561. var boundingInfo = this.object.getBoundingInfo();
  70562. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  70563. //bring back the rotation
  70564. this.object.rotationQuaternion = q;
  70565. //calculate the world matrix with the new rotation
  70566. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  70567. return size;
  70568. }
  70569. else {
  70570. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  70571. }
  70572. };
  70573. PhysicsImpostor.prototype.getObjectCenter = function () {
  70574. if (this.object.getBoundingInfo) {
  70575. var boundingInfo = this.object.getBoundingInfo();
  70576. return boundingInfo.boundingBox.centerWorld;
  70577. }
  70578. else {
  70579. return this.object.position;
  70580. }
  70581. };
  70582. /**
  70583. * Get a specific parametes from the options parameter.
  70584. */
  70585. PhysicsImpostor.prototype.getParam = function (paramName) {
  70586. return this._options[paramName];
  70587. };
  70588. /**
  70589. * Sets a specific parameter in the options given to the physics plugin
  70590. */
  70591. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  70592. this._options[paramName] = value;
  70593. this._bodyUpdateRequired = true;
  70594. };
  70595. /**
  70596. * Specifically change the body's mass option. Won't recreate the physics body object
  70597. */
  70598. PhysicsImpostor.prototype.setMass = function (mass) {
  70599. if (this.getParam("mass") !== mass) {
  70600. this.setParam("mass", mass);
  70601. }
  70602. if (this._physicsEngine) {
  70603. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  70604. }
  70605. };
  70606. PhysicsImpostor.prototype.getLinearVelocity = function () {
  70607. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  70608. };
  70609. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  70610. if (this._physicsEngine) {
  70611. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  70612. }
  70613. };
  70614. PhysicsImpostor.prototype.getAngularVelocity = function () {
  70615. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  70616. };
  70617. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  70618. if (this._physicsEngine) {
  70619. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  70620. }
  70621. };
  70622. /**
  70623. * Execute a function with the physics plugin native code.
  70624. * Provide a function the will have two variables - the world object and the physics body object.
  70625. */
  70626. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  70627. if (this._physicsEngine) {
  70628. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  70629. }
  70630. };
  70631. /**
  70632. * Register a function that will be executed before the physics world is stepping forward.
  70633. */
  70634. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  70635. this._onBeforePhysicsStepCallbacks.push(func);
  70636. };
  70637. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  70638. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  70639. if (index > -1) {
  70640. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  70641. }
  70642. else {
  70643. BABYLON.Tools.Warn("Function to remove was not found");
  70644. }
  70645. };
  70646. /**
  70647. * Register a function that will be executed after the physics step
  70648. */
  70649. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  70650. this._onAfterPhysicsStepCallbacks.push(func);
  70651. };
  70652. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  70653. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  70654. if (index > -1) {
  70655. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  70656. }
  70657. else {
  70658. BABYLON.Tools.Warn("Function to remove was not found");
  70659. }
  70660. };
  70661. /**
  70662. * register a function that will be executed when this impostor collides against a different body.
  70663. */
  70664. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  70665. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  70666. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  70667. };
  70668. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  70669. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  70670. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  70671. if (index > -1) {
  70672. this._onPhysicsCollideCallbacks.splice(index, 1);
  70673. }
  70674. else {
  70675. BABYLON.Tools.Warn("Function to remove was not found");
  70676. }
  70677. };
  70678. PhysicsImpostor.prototype.getParentsRotation = function () {
  70679. var parent = this.object.parent;
  70680. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  70681. while (parent) {
  70682. if (parent.rotationQuaternion) {
  70683. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  70684. }
  70685. else {
  70686. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  70687. }
  70688. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  70689. parent = parent.parent;
  70690. }
  70691. return this._tmpQuat;
  70692. };
  70693. /**
  70694. * Apply a force
  70695. */
  70696. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  70697. if (this._physicsEngine) {
  70698. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  70699. }
  70700. return this;
  70701. };
  70702. /**
  70703. * Apply an impulse
  70704. */
  70705. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  70706. if (this._physicsEngine) {
  70707. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  70708. }
  70709. return this;
  70710. };
  70711. /**
  70712. * A help function to create a joint.
  70713. */
  70714. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  70715. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  70716. this.addJoint(otherImpostor, joint);
  70717. return this;
  70718. };
  70719. /**
  70720. * Add a joint to this impostor with a different impostor.
  70721. */
  70722. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  70723. this._joints.push({
  70724. otherImpostor: otherImpostor,
  70725. joint: joint
  70726. });
  70727. if (this._physicsEngine) {
  70728. this._physicsEngine.addJoint(this, otherImpostor, joint);
  70729. }
  70730. return this;
  70731. };
  70732. /**
  70733. * Will keep this body still, in a sleep mode.
  70734. */
  70735. PhysicsImpostor.prototype.sleep = function () {
  70736. if (this._physicsEngine) {
  70737. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  70738. }
  70739. return this;
  70740. };
  70741. /**
  70742. * Wake the body up.
  70743. */
  70744. PhysicsImpostor.prototype.wakeUp = function () {
  70745. if (this._physicsEngine) {
  70746. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  70747. }
  70748. return this;
  70749. };
  70750. PhysicsImpostor.prototype.clone = function (newObject) {
  70751. if (!newObject)
  70752. return null;
  70753. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  70754. };
  70755. PhysicsImpostor.prototype.dispose = function () {
  70756. var _this = this;
  70757. //no dispose if no physics engine is available.
  70758. if (!this._physicsEngine) {
  70759. return;
  70760. }
  70761. this._joints.forEach(function (j) {
  70762. if (_this._physicsEngine) {
  70763. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  70764. }
  70765. });
  70766. //dispose the physics body
  70767. this._physicsEngine.removeImpostor(this);
  70768. if (this.parent) {
  70769. this.parent.forceUpdate();
  70770. }
  70771. else {
  70772. /*this._object.getChildMeshes().forEach(function(mesh) {
  70773. if (mesh.physicsImpostor) {
  70774. if (disposeChildren) {
  70775. mesh.physicsImpostor.dispose();
  70776. mesh.physicsImpostor = null;
  70777. }
  70778. }
  70779. })*/
  70780. }
  70781. this._isDisposed = true;
  70782. };
  70783. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  70784. this._deltaPosition.copyFrom(position);
  70785. };
  70786. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  70787. if (!this._deltaRotation) {
  70788. this._deltaRotation = new BABYLON.Quaternion();
  70789. }
  70790. this._deltaRotation.copyFrom(rotation);
  70791. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  70792. };
  70793. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  70794. if (this._physicsEngine) {
  70795. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  70796. }
  70797. return this;
  70798. };
  70799. PhysicsImpostor.prototype.getRadius = function () {
  70800. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  70801. };
  70802. /**
  70803. * Sync a bone with this impostor
  70804. * @param bone The bone to sync to the impostor.
  70805. * @param boneMesh The mesh that the bone is influencing.
  70806. * @param jointPivot The pivot of the joint / bone in local space.
  70807. * @param distToJoint Optional distance from the impostor to the joint.
  70808. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70809. */
  70810. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  70811. var tempVec = PhysicsImpostor._tmpVecs[0];
  70812. var mesh = this.object;
  70813. if (mesh.rotationQuaternion) {
  70814. if (adjustRotation) {
  70815. var tempQuat = PhysicsImpostor._tmpQuat;
  70816. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  70817. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  70818. }
  70819. else {
  70820. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  70821. }
  70822. }
  70823. tempVec.x = 0;
  70824. tempVec.y = 0;
  70825. tempVec.z = 0;
  70826. if (jointPivot) {
  70827. tempVec.x = jointPivot.x;
  70828. tempVec.y = jointPivot.y;
  70829. tempVec.z = jointPivot.z;
  70830. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  70831. if (distToJoint === undefined || distToJoint === null) {
  70832. distToJoint = jointPivot.length();
  70833. }
  70834. tempVec.x *= distToJoint;
  70835. tempVec.y *= distToJoint;
  70836. tempVec.z *= distToJoint;
  70837. }
  70838. if (bone.getParent()) {
  70839. tempVec.addInPlace(mesh.getAbsolutePosition());
  70840. bone.setAbsolutePosition(tempVec, boneMesh);
  70841. }
  70842. else {
  70843. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  70844. boneMesh.position.x -= tempVec.x;
  70845. boneMesh.position.y -= tempVec.y;
  70846. boneMesh.position.z -= tempVec.z;
  70847. }
  70848. };
  70849. /**
  70850. * Sync impostor to a bone
  70851. * @param bone The bone that the impostor will be synced to.
  70852. * @param boneMesh The mesh that the bone is influencing.
  70853. * @param jointPivot The pivot of the joint / bone in local space.
  70854. * @param distToJoint Optional distance from the impostor to the joint.
  70855. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70856. * @param boneAxis Optional vector3 axis the bone is aligned with
  70857. */
  70858. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  70859. var mesh = this.object;
  70860. if (mesh.rotationQuaternion) {
  70861. if (adjustRotation) {
  70862. var tempQuat = PhysicsImpostor._tmpQuat;
  70863. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  70864. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  70865. }
  70866. else {
  70867. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  70868. }
  70869. }
  70870. var pos = PhysicsImpostor._tmpVecs[0];
  70871. var boneDir = PhysicsImpostor._tmpVecs[1];
  70872. if (!boneAxis) {
  70873. boneAxis = PhysicsImpostor._tmpVecs[2];
  70874. boneAxis.x = 0;
  70875. boneAxis.y = 1;
  70876. boneAxis.z = 0;
  70877. }
  70878. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  70879. bone.getAbsolutePositionToRef(boneMesh, pos);
  70880. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  70881. distToJoint = jointPivot.length();
  70882. }
  70883. if (distToJoint !== undefined && distToJoint !== null) {
  70884. pos.x += boneDir.x * distToJoint;
  70885. pos.y += boneDir.y * distToJoint;
  70886. pos.z += boneDir.z * distToJoint;
  70887. }
  70888. mesh.setAbsolutePosition(pos);
  70889. };
  70890. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  70891. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  70892. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70893. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  70894. //Impostor types
  70895. PhysicsImpostor.NoImpostor = 0;
  70896. PhysicsImpostor.SphereImpostor = 1;
  70897. PhysicsImpostor.BoxImpostor = 2;
  70898. PhysicsImpostor.PlaneImpostor = 3;
  70899. PhysicsImpostor.MeshImpostor = 4;
  70900. PhysicsImpostor.CylinderImpostor = 7;
  70901. PhysicsImpostor.ParticleImpostor = 8;
  70902. PhysicsImpostor.HeightmapImpostor = 9;
  70903. return PhysicsImpostor;
  70904. }());
  70905. BABYLON.PhysicsImpostor = PhysicsImpostor;
  70906. })(BABYLON || (BABYLON = {}));
  70907. //# sourceMappingURL=babylon.physicsImpostor.js.map
  70908. var BABYLON;
  70909. (function (BABYLON) {
  70910. var PhysicsEngine = /** @class */ (function () {
  70911. function PhysicsEngine(gravity, _physicsPlugin) {
  70912. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  70913. this._physicsPlugin = _physicsPlugin;
  70914. //new methods and parameters
  70915. this._impostors = [];
  70916. this._joints = [];
  70917. if (!this._physicsPlugin.isSupported()) {
  70918. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  70919. + "Please make sure it is included.");
  70920. }
  70921. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  70922. this.setGravity(gravity);
  70923. this.setTimeStep();
  70924. }
  70925. PhysicsEngine.prototype.setGravity = function (gravity) {
  70926. this.gravity = gravity;
  70927. this._physicsPlugin.setGravity(this.gravity);
  70928. };
  70929. /**
  70930. * Set the time step of the physics engine.
  70931. * default is 1/60.
  70932. * To slow it down, enter 1/600 for example.
  70933. * To speed it up, 1/30
  70934. * @param {number} newTimeStep the new timestep to apply to this world.
  70935. */
  70936. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  70937. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  70938. this._physicsPlugin.setTimeStep(newTimeStep);
  70939. };
  70940. /**
  70941. * Get the time step of the physics engine.
  70942. */
  70943. PhysicsEngine.prototype.getTimeStep = function () {
  70944. return this._physicsPlugin.getTimeStep();
  70945. };
  70946. PhysicsEngine.prototype.dispose = function () {
  70947. this._impostors.forEach(function (impostor) {
  70948. impostor.dispose();
  70949. });
  70950. this._physicsPlugin.dispose();
  70951. };
  70952. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  70953. return this._physicsPlugin.name;
  70954. };
  70955. /**
  70956. * Adding a new impostor for the impostor tracking.
  70957. * This will be done by the impostor itself.
  70958. * @param {PhysicsImpostor} impostor the impostor to add
  70959. */
  70960. PhysicsEngine.prototype.addImpostor = function (impostor) {
  70961. impostor.uniqueId = this._impostors.push(impostor);
  70962. //if no parent, generate the body
  70963. if (!impostor.parent) {
  70964. this._physicsPlugin.generatePhysicsBody(impostor);
  70965. }
  70966. };
  70967. /**
  70968. * Remove an impostor from the engine.
  70969. * This impostor and its mesh will not longer be updated by the physics engine.
  70970. * @param {PhysicsImpostor} impostor the impostor to remove
  70971. */
  70972. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  70973. var index = this._impostors.indexOf(impostor);
  70974. if (index > -1) {
  70975. var removed = this._impostors.splice(index, 1);
  70976. //Is it needed?
  70977. if (removed.length) {
  70978. //this will also remove it from the world.
  70979. removed[0].physicsBody = null;
  70980. }
  70981. }
  70982. };
  70983. /**
  70984. * Add a joint to the physics engine
  70985. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  70986. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  70987. * @param {PhysicsJoint} the joint that will connect both impostors.
  70988. */
  70989. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  70990. var impostorJoint = {
  70991. mainImpostor: mainImpostor,
  70992. connectedImpostor: connectedImpostor,
  70993. joint: joint
  70994. };
  70995. joint.physicsPlugin = this._physicsPlugin;
  70996. this._joints.push(impostorJoint);
  70997. this._physicsPlugin.generateJoint(impostorJoint);
  70998. };
  70999. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  71000. var matchingJoints = this._joints.filter(function (impostorJoint) {
  71001. return (impostorJoint.connectedImpostor === connectedImpostor
  71002. && impostorJoint.joint === joint
  71003. && impostorJoint.mainImpostor === mainImpostor);
  71004. });
  71005. if (matchingJoints.length) {
  71006. this._physicsPlugin.removeJoint(matchingJoints[0]);
  71007. //TODO remove it from the list as well
  71008. }
  71009. };
  71010. /**
  71011. * Called by the scene. no need to call it.
  71012. */
  71013. PhysicsEngine.prototype._step = function (delta) {
  71014. var _this = this;
  71015. //check if any mesh has no body / requires an update
  71016. this._impostors.forEach(function (impostor) {
  71017. if (impostor.isBodyInitRequired()) {
  71018. _this._physicsPlugin.generatePhysicsBody(impostor);
  71019. }
  71020. });
  71021. if (delta > 0.1) {
  71022. delta = 0.1;
  71023. }
  71024. else if (delta <= 0) {
  71025. delta = 1.0 / 60.0;
  71026. }
  71027. this._physicsPlugin.executeStep(delta, this._impostors);
  71028. };
  71029. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  71030. return this._physicsPlugin;
  71031. };
  71032. PhysicsEngine.prototype.getImpostors = function () {
  71033. return this._impostors;
  71034. };
  71035. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  71036. for (var i = 0; i < this._impostors.length; ++i) {
  71037. if (this._impostors[i].object === object) {
  71038. return this._impostors[i];
  71039. }
  71040. }
  71041. return null;
  71042. };
  71043. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  71044. for (var i = 0; i < this._impostors.length; ++i) {
  71045. if (this._impostors[i].physicsBody === body) {
  71046. return this._impostors[i];
  71047. }
  71048. }
  71049. return null;
  71050. };
  71051. // Statics
  71052. PhysicsEngine.Epsilon = 0.001;
  71053. return PhysicsEngine;
  71054. }());
  71055. BABYLON.PhysicsEngine = PhysicsEngine;
  71056. })(BABYLON || (BABYLON = {}));
  71057. //# sourceMappingURL=babylon.physicsEngine.js.map
  71058. var BABYLON;
  71059. (function (BABYLON) {
  71060. var PhysicsHelper = /** @class */ (function () {
  71061. function PhysicsHelper(scene) {
  71062. this._scene = scene;
  71063. this._physicsEngine = this._scene.getPhysicsEngine();
  71064. if (!this._physicsEngine) {
  71065. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  71066. }
  71067. }
  71068. /**
  71069. * @param {Vector3} origin the origin of the explosion
  71070. * @param {number} radius the explosion radius
  71071. * @param {number} strength the explosion strength
  71072. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71073. */
  71074. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  71075. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71076. if (!this._physicsEngine) {
  71077. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  71078. return null;
  71079. }
  71080. var impostors = this._physicsEngine.getImpostors();
  71081. if (impostors.length === 0) {
  71082. return null;
  71083. }
  71084. var event = new PhysicsRadialExplosionEvent(this._scene);
  71085. impostors.forEach(function (impostor) {
  71086. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  71087. if (!impostorForceAndContactPoint) {
  71088. return;
  71089. }
  71090. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71091. });
  71092. event.dispose(false);
  71093. return event;
  71094. };
  71095. /**
  71096. * @param {Vector3} origin the origin of the explosion
  71097. * @param {number} radius the explosion radius
  71098. * @param {number} strength the explosion strength
  71099. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71100. */
  71101. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  71102. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71103. if (!this._physicsEngine) {
  71104. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71105. return null;
  71106. }
  71107. var impostors = this._physicsEngine.getImpostors();
  71108. if (impostors.length === 0) {
  71109. return null;
  71110. }
  71111. var event = new PhysicsRadialExplosionEvent(this._scene);
  71112. impostors.forEach(function (impostor) {
  71113. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  71114. if (!impostorForceAndContactPoint) {
  71115. return;
  71116. }
  71117. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71118. });
  71119. event.dispose(false);
  71120. return event;
  71121. };
  71122. /**
  71123. * @param {Vector3} origin the origin of the explosion
  71124. * @param {number} radius the explosion radius
  71125. * @param {number} strength the explosion strength
  71126. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  71127. */
  71128. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  71129. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71130. if (!this._physicsEngine) {
  71131. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71132. return null;
  71133. }
  71134. var impostors = this._physicsEngine.getImpostors();
  71135. if (impostors.length === 0) {
  71136. return null;
  71137. }
  71138. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  71139. event.dispose(false);
  71140. return event;
  71141. };
  71142. /**
  71143. * @param {Vector3} origin the origin of the updraft
  71144. * @param {number} radius the radius of the updraft
  71145. * @param {number} strength the strength of the updraft
  71146. * @param {number} height the height of the updraft
  71147. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  71148. */
  71149. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  71150. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  71151. if (!this._physicsEngine) {
  71152. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71153. return null;
  71154. }
  71155. if (this._physicsEngine.getImpostors().length === 0) {
  71156. return null;
  71157. }
  71158. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  71159. event.dispose(false);
  71160. return event;
  71161. };
  71162. /**
  71163. * @param {Vector3} origin the of the vortex
  71164. * @param {number} radius the radius of the vortex
  71165. * @param {number} strength the strength of the vortex
  71166. * @param {number} height the height of the vortex
  71167. */
  71168. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  71169. if (!this._physicsEngine) {
  71170. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  71171. return null;
  71172. }
  71173. if (this._physicsEngine.getImpostors().length === 0) {
  71174. return null;
  71175. }
  71176. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  71177. event.dispose(false);
  71178. return event;
  71179. };
  71180. return PhysicsHelper;
  71181. }());
  71182. BABYLON.PhysicsHelper = PhysicsHelper;
  71183. /***** Radial explosion *****/
  71184. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  71185. function PhysicsRadialExplosionEvent(scene) {
  71186. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  71187. this._rays = [];
  71188. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  71189. this._scene = scene;
  71190. }
  71191. /**
  71192. * Returns the data related to the radial explosion event (sphere & rays).
  71193. * @returns {PhysicsRadialExplosionEventData}
  71194. */
  71195. PhysicsRadialExplosionEvent.prototype.getData = function () {
  71196. this._dataFetched = true;
  71197. return {
  71198. sphere: this._sphere,
  71199. rays: this._rays,
  71200. };
  71201. };
  71202. /**
  71203. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  71204. * @param impostor
  71205. * @param {Vector3} origin the origin of the explosion
  71206. * @param {number} radius the explosion radius
  71207. * @param {number} strength the explosion strength
  71208. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  71209. * @returns {Nullable<PhysicsForceAndContactPoint>}
  71210. */
  71211. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  71212. if (impostor.mass === 0) {
  71213. return null;
  71214. }
  71215. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  71216. return null;
  71217. }
  71218. if (impostor.object.getClassName() !== 'Mesh') {
  71219. return null;
  71220. }
  71221. var impostorObject = impostor.object;
  71222. var impostorObjectCenter = impostor.getObjectCenter();
  71223. var direction = impostorObjectCenter.subtract(origin);
  71224. var ray = new BABYLON.Ray(origin, direction, radius);
  71225. this._rays.push(ray);
  71226. var hit = ray.intersectsMesh(impostorObject);
  71227. var contactPoint = hit.pickedPoint;
  71228. if (!contactPoint) {
  71229. return null;
  71230. }
  71231. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  71232. if (distanceFromOrigin > radius) {
  71233. return null;
  71234. }
  71235. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  71236. ? strength
  71237. : strength * (1 - (distanceFromOrigin / radius));
  71238. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  71239. return { force: force, contactPoint: contactPoint };
  71240. };
  71241. /**
  71242. * Disposes the sphere.
  71243. * @param {bolean} force
  71244. */
  71245. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  71246. var _this = this;
  71247. if (force === void 0) { force = true; }
  71248. if (force) {
  71249. this._sphere.dispose();
  71250. }
  71251. else {
  71252. setTimeout(function () {
  71253. if (!_this._dataFetched) {
  71254. _this._sphere.dispose();
  71255. }
  71256. }, 0);
  71257. }
  71258. };
  71259. /*** Helpers ***/
  71260. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  71261. if (!this._sphere) {
  71262. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  71263. this._sphere.isVisible = false;
  71264. }
  71265. };
  71266. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  71267. var impostorObject = impostor.object;
  71268. this._prepareSphere();
  71269. this._sphere.position = origin;
  71270. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  71271. this._sphere._updateBoundingInfo();
  71272. this._sphere.computeWorldMatrix(true);
  71273. return this._sphere.intersectsMesh(impostorObject, true);
  71274. };
  71275. return PhysicsRadialExplosionEvent;
  71276. }());
  71277. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  71278. /***** Gravitational Field *****/
  71279. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  71280. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  71281. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71282. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71283. this._physicsHelper = physicsHelper;
  71284. this._scene = scene;
  71285. this._origin = origin;
  71286. this._radius = radius;
  71287. this._strength = strength;
  71288. this._falloff = falloff;
  71289. this._tickCallback = this._tick.bind(this);
  71290. }
  71291. /**
  71292. * Returns the data related to the gravitational field event (sphere).
  71293. * @returns {PhysicsGravitationalFieldEventData}
  71294. */
  71295. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  71296. this._dataFetched = true;
  71297. return {
  71298. sphere: this._sphere,
  71299. };
  71300. };
  71301. /**
  71302. * Enables the gravitational field.
  71303. */
  71304. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  71305. this._tickCallback.call(this);
  71306. this._scene.registerBeforeRender(this._tickCallback);
  71307. };
  71308. /**
  71309. * Disables the gravitational field.
  71310. */
  71311. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  71312. this._scene.unregisterBeforeRender(this._tickCallback);
  71313. };
  71314. /**
  71315. * Disposes the sphere.
  71316. * @param {bolean} force
  71317. */
  71318. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  71319. var _this = this;
  71320. if (force === void 0) { force = true; }
  71321. if (force) {
  71322. this._sphere.dispose();
  71323. }
  71324. else {
  71325. setTimeout(function () {
  71326. if (!_this._dataFetched) {
  71327. _this._sphere.dispose();
  71328. }
  71329. }, 0);
  71330. }
  71331. };
  71332. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  71333. // Since the params won't change, we fetch the event only once
  71334. if (this._sphere) {
  71335. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  71336. }
  71337. else {
  71338. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  71339. if (radialExplosionEvent) {
  71340. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  71341. }
  71342. }
  71343. };
  71344. return PhysicsGravitationalFieldEvent;
  71345. }());
  71346. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  71347. /***** Updraft *****/
  71348. var PhysicsUpdraftEvent = /** @class */ (function () {
  71349. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  71350. this._scene = _scene;
  71351. this._origin = _origin;
  71352. this._radius = _radius;
  71353. this._strength = _strength;
  71354. this._height = _height;
  71355. this._updraftMode = _updraftMode;
  71356. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  71357. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  71358. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  71359. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71360. this._physicsEngine = this._scene.getPhysicsEngine();
  71361. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  71362. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  71363. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  71364. this._originDirection = this._origin.subtract(this._originTop).normalize();
  71365. }
  71366. this._tickCallback = this._tick.bind(this);
  71367. }
  71368. /**
  71369. * Returns the data related to the updraft event (cylinder).
  71370. * @returns {PhysicsUpdraftEventData}
  71371. */
  71372. PhysicsUpdraftEvent.prototype.getData = function () {
  71373. this._dataFetched = true;
  71374. return {
  71375. cylinder: this._cylinder,
  71376. };
  71377. };
  71378. /**
  71379. * Enables the updraft.
  71380. */
  71381. PhysicsUpdraftEvent.prototype.enable = function () {
  71382. this._tickCallback.call(this);
  71383. this._scene.registerBeforeRender(this._tickCallback);
  71384. };
  71385. /**
  71386. * Disables the cortex.
  71387. */
  71388. PhysicsUpdraftEvent.prototype.disable = function () {
  71389. this._scene.unregisterBeforeRender(this._tickCallback);
  71390. };
  71391. /**
  71392. * Disposes the sphere.
  71393. * @param {bolean} force
  71394. */
  71395. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  71396. var _this = this;
  71397. if (force === void 0) { force = true; }
  71398. if (force) {
  71399. this._cylinder.dispose();
  71400. }
  71401. else {
  71402. setTimeout(function () {
  71403. if (!_this._dataFetched) {
  71404. _this._cylinder.dispose();
  71405. }
  71406. }, 0);
  71407. }
  71408. };
  71409. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  71410. if (impostor.mass === 0) {
  71411. return null;
  71412. }
  71413. if (!this._intersectsWithCylinder(impostor)) {
  71414. return null;
  71415. }
  71416. var impostorObjectCenter = impostor.getObjectCenter();
  71417. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  71418. var direction = this._originDirection;
  71419. }
  71420. else {
  71421. var direction = impostorObjectCenter.subtract(this._originTop);
  71422. }
  71423. var multiplier = this._strength * -1;
  71424. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  71425. return { force: force, contactPoint: impostorObjectCenter };
  71426. };
  71427. PhysicsUpdraftEvent.prototype._tick = function () {
  71428. var _this = this;
  71429. this._physicsEngine.getImpostors().forEach(function (impostor) {
  71430. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  71431. if (!impostorForceAndContactPoint) {
  71432. return;
  71433. }
  71434. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71435. });
  71436. };
  71437. /*** Helpers ***/
  71438. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  71439. if (!this._cylinder) {
  71440. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  71441. height: this._height,
  71442. diameter: this._radius * 2,
  71443. }, this._scene);
  71444. this._cylinder.isVisible = false;
  71445. }
  71446. };
  71447. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  71448. var impostorObject = impostor.object;
  71449. this._prepareCylinder();
  71450. this._cylinder.position = this._cylinderPosition;
  71451. return this._cylinder.intersectsMesh(impostorObject, true);
  71452. };
  71453. return PhysicsUpdraftEvent;
  71454. }());
  71455. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  71456. /***** Vortex *****/
  71457. var PhysicsVortexEvent = /** @class */ (function () {
  71458. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  71459. this._scene = _scene;
  71460. this._origin = _origin;
  71461. this._radius = _radius;
  71462. this._strength = _strength;
  71463. this._height = _height;
  71464. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  71465. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  71466. this._updraftMultiplier = 0.02;
  71467. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  71468. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71469. this._physicsEngine = this._scene.getPhysicsEngine();
  71470. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  71471. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  71472. this._tickCallback = this._tick.bind(this);
  71473. }
  71474. /**
  71475. * Returns the data related to the vortex event (cylinder).
  71476. * @returns {PhysicsVortexEventData}
  71477. */
  71478. PhysicsVortexEvent.prototype.getData = function () {
  71479. this._dataFetched = true;
  71480. return {
  71481. cylinder: this._cylinder,
  71482. };
  71483. };
  71484. /**
  71485. * Enables the vortex.
  71486. */
  71487. PhysicsVortexEvent.prototype.enable = function () {
  71488. this._tickCallback.call(this);
  71489. this._scene.registerBeforeRender(this._tickCallback);
  71490. };
  71491. /**
  71492. * Disables the cortex.
  71493. */
  71494. PhysicsVortexEvent.prototype.disable = function () {
  71495. this._scene.unregisterBeforeRender(this._tickCallback);
  71496. };
  71497. /**
  71498. * Disposes the sphere.
  71499. * @param {bolean} force
  71500. */
  71501. PhysicsVortexEvent.prototype.dispose = function (force) {
  71502. var _this = this;
  71503. if (force === void 0) { force = true; }
  71504. if (force) {
  71505. this._cylinder.dispose();
  71506. }
  71507. else {
  71508. setTimeout(function () {
  71509. if (!_this._dataFetched) {
  71510. _this._cylinder.dispose();
  71511. }
  71512. }, 0);
  71513. }
  71514. };
  71515. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  71516. if (impostor.mass === 0) {
  71517. return null;
  71518. }
  71519. if (!this._intersectsWithCylinder(impostor)) {
  71520. return null;
  71521. }
  71522. if (impostor.object.getClassName() !== 'Mesh') {
  71523. return null;
  71524. }
  71525. var impostorObject = impostor.object;
  71526. var impostorObjectCenter = impostor.getObjectCenter();
  71527. 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)
  71528. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  71529. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  71530. var hit = ray.intersectsMesh(impostorObject);
  71531. var contactPoint = hit.pickedPoint;
  71532. if (!contactPoint) {
  71533. return null;
  71534. }
  71535. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  71536. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  71537. var directionToOrigin = contactPoint.normalize();
  71538. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  71539. directionToOrigin = directionToOrigin.negate();
  71540. }
  71541. // TODO: find a more physically based solution
  71542. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  71543. var forceX = directionToOrigin.x * this._strength / 8;
  71544. var forceY = directionToOrigin.y * this._updraftMultiplier;
  71545. var forceZ = directionToOrigin.z * this._strength / 8;
  71546. }
  71547. else {
  71548. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  71549. var forceY = this._originTop.y * this._updraftMultiplier;
  71550. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  71551. }
  71552. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  71553. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  71554. return { force: force, contactPoint: impostorObjectCenter };
  71555. };
  71556. PhysicsVortexEvent.prototype._tick = function () {
  71557. var _this = this;
  71558. this._physicsEngine.getImpostors().forEach(function (impostor) {
  71559. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  71560. if (!impostorForceAndContactPoint) {
  71561. return;
  71562. }
  71563. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71564. });
  71565. };
  71566. /*** Helpers ***/
  71567. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  71568. if (!this._cylinder) {
  71569. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  71570. height: this._height,
  71571. diameter: this._radius * 2,
  71572. }, this._scene);
  71573. this._cylinder.isVisible = false;
  71574. }
  71575. };
  71576. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  71577. var impostorObject = impostor.object;
  71578. this._prepareCylinder();
  71579. this._cylinder.position = this._cylinderPosition;
  71580. return this._cylinder.intersectsMesh(impostorObject, true);
  71581. };
  71582. return PhysicsVortexEvent;
  71583. }());
  71584. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  71585. /***** Enums *****/
  71586. /**
  71587. * The strenght of the force in correspondence to the distance of the affected object
  71588. */
  71589. var PhysicsRadialImpulseFalloff;
  71590. (function (PhysicsRadialImpulseFalloff) {
  71591. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  71592. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  71593. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  71594. /**
  71595. * The strenght of the force in correspondence to the distance of the affected object
  71596. */
  71597. var PhysicsUpdraftMode;
  71598. (function (PhysicsUpdraftMode) {
  71599. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  71600. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  71601. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  71602. })(BABYLON || (BABYLON = {}));
  71603. //# sourceMappingURL=babylon.physicsHelper.js.map
  71604. var BABYLON;
  71605. (function (BABYLON) {
  71606. var CannonJSPlugin = /** @class */ (function () {
  71607. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  71608. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  71609. if (iterations === void 0) { iterations = 10; }
  71610. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  71611. this.name = "CannonJSPlugin";
  71612. this._physicsMaterials = new Array();
  71613. this._fixedTimeStep = 1 / 60;
  71614. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  71615. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  71616. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  71617. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  71618. this._tmpPosition = BABYLON.Vector3.Zero();
  71619. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  71620. this._tmpUnityRotation = new BABYLON.Quaternion();
  71621. if (!this.isSupported()) {
  71622. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  71623. return;
  71624. }
  71625. this._extendNamespace();
  71626. this.world = new this.BJSCANNON.World();
  71627. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  71628. this.world.solver.iterations = iterations;
  71629. }
  71630. CannonJSPlugin.prototype.setGravity = function (gravity) {
  71631. this.world.gravity.copy(gravity);
  71632. };
  71633. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  71634. this._fixedTimeStep = timeStep;
  71635. };
  71636. CannonJSPlugin.prototype.getTimeStep = function () {
  71637. return this._fixedTimeStep;
  71638. };
  71639. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  71640. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  71641. };
  71642. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  71643. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  71644. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  71645. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  71646. };
  71647. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  71648. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  71649. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  71650. impostor.physicsBody.applyForce(impulse, worldPoint);
  71651. };
  71652. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  71653. //parent-child relationship. Does this impostor has a parent impostor?
  71654. if (impostor.parent) {
  71655. if (impostor.physicsBody) {
  71656. this.removePhysicsBody(impostor);
  71657. //TODO is that needed?
  71658. impostor.forceUpdate();
  71659. }
  71660. return;
  71661. }
  71662. //should a new body be created for this impostor?
  71663. if (impostor.isBodyInitRequired()) {
  71664. var shape = this._createShape(impostor);
  71665. //unregister events, if body is being changed
  71666. var oldBody = impostor.physicsBody;
  71667. if (oldBody) {
  71668. this.removePhysicsBody(impostor);
  71669. }
  71670. //create the body and material
  71671. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  71672. var bodyCreationObject = {
  71673. mass: impostor.getParam("mass"),
  71674. material: material
  71675. };
  71676. // A simple extend, in case native options were used.
  71677. var nativeOptions = impostor.getParam("nativeOptions");
  71678. for (var key in nativeOptions) {
  71679. if (nativeOptions.hasOwnProperty(key)) {
  71680. bodyCreationObject[key] = nativeOptions[key];
  71681. }
  71682. }
  71683. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  71684. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  71685. this.world.addEventListener("preStep", impostor.beforeStep);
  71686. this.world.addEventListener("postStep", impostor.afterStep);
  71687. impostor.physicsBody.addShape(shape);
  71688. this.world.add(impostor.physicsBody);
  71689. //try to keep the body moving in the right direction by taking old properties.
  71690. //Should be tested!
  71691. if (oldBody) {
  71692. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  71693. impostor.physicsBody[param].copy(oldBody[param]);
  71694. });
  71695. }
  71696. this._processChildMeshes(impostor);
  71697. }
  71698. //now update the body's transformation
  71699. this._updatePhysicsBodyTransformation(impostor);
  71700. };
  71701. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  71702. var _this = this;
  71703. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  71704. var currentRotation = mainImpostor.object.rotationQuaternion;
  71705. if (meshChildren.length) {
  71706. var processMesh = function (localPosition, mesh) {
  71707. if (!currentRotation || !mesh.rotationQuaternion) {
  71708. return;
  71709. }
  71710. var childImpostor = mesh.getPhysicsImpostor();
  71711. if (childImpostor) {
  71712. var parent = childImpostor.parent;
  71713. if (parent !== mainImpostor) {
  71714. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  71715. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  71716. if (childImpostor.physicsBody) {
  71717. _this.removePhysicsBody(childImpostor);
  71718. childImpostor.physicsBody = null;
  71719. }
  71720. childImpostor.parent = mainImpostor;
  71721. childImpostor.resetUpdateFlags();
  71722. 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));
  71723. //Add the mass of the children.
  71724. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  71725. }
  71726. }
  71727. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  71728. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  71729. };
  71730. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  71731. }
  71732. };
  71733. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  71734. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  71735. this.world.removeEventListener("preStep", impostor.beforeStep);
  71736. this.world.removeEventListener("postStep", impostor.afterStep);
  71737. this.world.remove(impostor.physicsBody);
  71738. };
  71739. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  71740. var mainBody = impostorJoint.mainImpostor.physicsBody;
  71741. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  71742. if (!mainBody || !connectedBody) {
  71743. return;
  71744. }
  71745. var constraint;
  71746. var jointData = impostorJoint.joint.jointData;
  71747. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  71748. var constraintData = {
  71749. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  71750. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  71751. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  71752. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  71753. maxForce: jointData.nativeParams.maxForce,
  71754. collideConnected: !!jointData.collision
  71755. };
  71756. switch (impostorJoint.joint.type) {
  71757. case BABYLON.PhysicsJoint.HingeJoint:
  71758. case BABYLON.PhysicsJoint.Hinge2Joint:
  71759. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  71760. break;
  71761. case BABYLON.PhysicsJoint.DistanceJoint:
  71762. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  71763. break;
  71764. case BABYLON.PhysicsJoint.SpringJoint:
  71765. var springData = jointData;
  71766. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  71767. restLength: springData.length,
  71768. stiffness: springData.stiffness,
  71769. damping: springData.damping,
  71770. localAnchorA: constraintData.pivotA,
  71771. localAnchorB: constraintData.pivotB
  71772. });
  71773. break;
  71774. case BABYLON.PhysicsJoint.LockJoint:
  71775. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  71776. break;
  71777. case BABYLON.PhysicsJoint.PointToPointJoint:
  71778. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  71779. default:
  71780. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  71781. break;
  71782. }
  71783. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  71784. constraint.collideConnected = !!jointData.collision;
  71785. impostorJoint.joint.physicsJoint = constraint;
  71786. //don't add spring as constraint, as it is not one.
  71787. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  71788. this.world.addConstraint(constraint);
  71789. }
  71790. else {
  71791. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  71792. constraint.applyForce();
  71793. });
  71794. }
  71795. };
  71796. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  71797. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  71798. };
  71799. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  71800. var index;
  71801. var mat;
  71802. for (index = 0; index < this._physicsMaterials.length; index++) {
  71803. mat = this._physicsMaterials[index];
  71804. if (mat.friction === friction && mat.restitution === restitution) {
  71805. return mat;
  71806. }
  71807. }
  71808. var currentMat = new this.BJSCANNON.Material(name);
  71809. currentMat.friction = friction;
  71810. currentMat.restitution = restitution;
  71811. this._physicsMaterials.push(currentMat);
  71812. return currentMat;
  71813. };
  71814. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  71815. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  71816. };
  71817. CannonJSPlugin.prototype._createShape = function (impostor) {
  71818. var object = impostor.object;
  71819. var returnValue;
  71820. var extendSize = impostor.getObjectExtendSize();
  71821. switch (impostor.type) {
  71822. case BABYLON.PhysicsImpostor.SphereImpostor:
  71823. var radiusX = extendSize.x;
  71824. var radiusY = extendSize.y;
  71825. var radiusZ = extendSize.z;
  71826. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  71827. break;
  71828. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  71829. case BABYLON.PhysicsImpostor.CylinderImpostor:
  71830. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  71831. break;
  71832. case BABYLON.PhysicsImpostor.BoxImpostor:
  71833. var box = extendSize.scale(0.5);
  71834. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  71835. break;
  71836. case BABYLON.PhysicsImpostor.PlaneImpostor:
  71837. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  71838. returnValue = new this.BJSCANNON.Plane();
  71839. break;
  71840. case BABYLON.PhysicsImpostor.MeshImpostor:
  71841. // should transform the vertex data to world coordinates!!
  71842. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  71843. var rawFaces = object.getIndices ? object.getIndices() : [];
  71844. if (!rawVerts)
  71845. return;
  71846. // get only scale! so the object could transform correctly.
  71847. var oldPosition = object.position.clone();
  71848. var oldRotation = object.rotation && object.rotation.clone();
  71849. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  71850. object.position.copyFromFloats(0, 0, 0);
  71851. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71852. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71853. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71854. var transform = object.computeWorldMatrix(true);
  71855. // convert rawVerts to object space
  71856. var temp = new Array();
  71857. var index;
  71858. for (index = 0; index < rawVerts.length; index += 3) {
  71859. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  71860. }
  71861. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  71862. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  71863. //now set back the transformation!
  71864. object.position.copyFrom(oldPosition);
  71865. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  71866. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  71867. break;
  71868. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  71869. var oldPosition2 = object.position.clone();
  71870. var oldRotation2 = object.rotation && object.rotation.clone();
  71871. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  71872. object.position.copyFromFloats(0, 0, 0);
  71873. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71874. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71875. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71876. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  71877. returnValue = this._createHeightmap(object);
  71878. object.position.copyFrom(oldPosition2);
  71879. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  71880. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  71881. object.computeWorldMatrix(true);
  71882. break;
  71883. case BABYLON.PhysicsImpostor.ParticleImpostor:
  71884. returnValue = new this.BJSCANNON.Particle();
  71885. break;
  71886. }
  71887. return returnValue;
  71888. };
  71889. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  71890. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71891. var transform = object.computeWorldMatrix(true);
  71892. // convert rawVerts to object space
  71893. var temp = new Array();
  71894. var index;
  71895. for (index = 0; index < pos.length; index += 3) {
  71896. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  71897. }
  71898. pos = temp;
  71899. var matrix = new Array();
  71900. //For now pointDepth will not be used and will be automatically calculated.
  71901. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  71902. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  71903. var boundingInfo = object.getBoundingInfo();
  71904. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  71905. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  71906. var elementSize = dim * 2 / arraySize;
  71907. for (var i = 0; i < pos.length; i = i + 3) {
  71908. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  71909. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  71910. var y = -pos[i + 2] + minY;
  71911. if (!matrix[x]) {
  71912. matrix[x] = [];
  71913. }
  71914. if (!matrix[x][z]) {
  71915. matrix[x][z] = y;
  71916. }
  71917. matrix[x][z] = Math.max(y, matrix[x][z]);
  71918. }
  71919. for (var x = 0; x <= arraySize; ++x) {
  71920. if (!matrix[x]) {
  71921. var loc = 1;
  71922. while (!matrix[(x + loc) % arraySize]) {
  71923. loc++;
  71924. }
  71925. matrix[x] = matrix[(x + loc) % arraySize].slice();
  71926. //console.log("missing x", x);
  71927. }
  71928. for (var z = 0; z <= arraySize; ++z) {
  71929. if (!matrix[x][z]) {
  71930. var loc = 1;
  71931. var newValue;
  71932. while (newValue === undefined) {
  71933. newValue = matrix[x][(z + loc++) % arraySize];
  71934. }
  71935. matrix[x][z] = newValue;
  71936. }
  71937. }
  71938. }
  71939. var shape = new this.BJSCANNON.Heightfield(matrix, {
  71940. elementSize: elementSize
  71941. });
  71942. //For future reference, needed for body transformation
  71943. shape.minY = minY;
  71944. return shape;
  71945. };
  71946. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  71947. var object = impostor.object;
  71948. //make sure it is updated...
  71949. object.computeWorldMatrix && object.computeWorldMatrix(true);
  71950. // The delta between the mesh position and the mesh bounding box center
  71951. var bInfo = object.getBoundingInfo();
  71952. if (!bInfo)
  71953. return;
  71954. var center = impostor.getObjectCenter();
  71955. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  71956. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  71957. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  71958. this._tmpPosition.copyFrom(center);
  71959. var quaternion = object.rotationQuaternion;
  71960. if (!quaternion) {
  71961. return;
  71962. }
  71963. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  71964. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  71965. //-90 DEG in X, precalculated
  71966. quaternion = quaternion.multiply(this._minus90X);
  71967. //Invert! (Precalculated, 90 deg in X)
  71968. //No need to clone. this will never change.
  71969. impostor.setDeltaRotation(this._plus90X);
  71970. }
  71971. //If it is a heightfield, if should be centered.
  71972. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  71973. var mesh = object;
  71974. var boundingInfo = mesh.getBoundingInfo();
  71975. //calculate the correct body position:
  71976. var rotationQuaternion = mesh.rotationQuaternion;
  71977. mesh.rotationQuaternion = this._tmpUnityRotation;
  71978. mesh.computeWorldMatrix(true);
  71979. //get original center with no rotation
  71980. var c = center.clone();
  71981. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  71982. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  71983. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  71984. mesh.setPivotMatrix(p);
  71985. mesh.computeWorldMatrix(true);
  71986. //calculate the translation
  71987. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  71988. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  71989. //add it inverted to the delta
  71990. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  71991. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  71992. //rotation is back
  71993. mesh.rotationQuaternion = rotationQuaternion;
  71994. mesh.setPivotMatrix(oldPivot);
  71995. mesh.computeWorldMatrix(true);
  71996. }
  71997. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  71998. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  71999. //this._tmpPosition.copyFrom(object.position);
  72000. }
  72001. impostor.setDeltaPosition(this._tmpDeltaPosition);
  72002. //Now update the impostor object
  72003. impostor.physicsBody.position.copy(this._tmpPosition);
  72004. impostor.physicsBody.quaternion.copy(quaternion);
  72005. };
  72006. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  72007. impostor.object.position.copyFrom(impostor.physicsBody.position);
  72008. if (impostor.object.rotationQuaternion) {
  72009. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  72010. }
  72011. };
  72012. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  72013. impostor.physicsBody.position.copy(newPosition);
  72014. impostor.physicsBody.quaternion.copy(newRotation);
  72015. };
  72016. CannonJSPlugin.prototype.isSupported = function () {
  72017. return this.BJSCANNON !== undefined;
  72018. };
  72019. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  72020. impostor.physicsBody.velocity.copy(velocity);
  72021. };
  72022. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  72023. impostor.physicsBody.angularVelocity.copy(velocity);
  72024. };
  72025. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  72026. var v = impostor.physicsBody.velocity;
  72027. if (!v) {
  72028. return null;
  72029. }
  72030. return new BABYLON.Vector3(v.x, v.y, v.z);
  72031. };
  72032. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  72033. var v = impostor.physicsBody.angularVelocity;
  72034. if (!v) {
  72035. return null;
  72036. }
  72037. return new BABYLON.Vector3(v.x, v.y, v.z);
  72038. };
  72039. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  72040. impostor.physicsBody.mass = mass;
  72041. impostor.physicsBody.updateMassProperties();
  72042. };
  72043. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  72044. return impostor.physicsBody.mass;
  72045. };
  72046. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  72047. return impostor.physicsBody.material.friction;
  72048. };
  72049. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  72050. impostor.physicsBody.material.friction = friction;
  72051. };
  72052. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  72053. return impostor.physicsBody.material.restitution;
  72054. };
  72055. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  72056. impostor.physicsBody.material.restitution = restitution;
  72057. };
  72058. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  72059. impostor.physicsBody.sleep();
  72060. };
  72061. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  72062. impostor.physicsBody.wakeUp();
  72063. };
  72064. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  72065. joint.physicsJoint.distance = maxDistance;
  72066. };
  72067. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  72068. // if (!motorIndex) {
  72069. // joint.physicsJoint.enableMotor();
  72070. // }
  72071. // }
  72072. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  72073. // if (!motorIndex) {
  72074. // joint.physicsJoint.disableMotor();
  72075. // }
  72076. // }
  72077. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  72078. if (!motorIndex) {
  72079. joint.physicsJoint.enableMotor();
  72080. joint.physicsJoint.setMotorSpeed(speed);
  72081. if (maxForce) {
  72082. this.setLimit(joint, maxForce);
  72083. }
  72084. }
  72085. };
  72086. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  72087. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  72088. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  72089. };
  72090. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  72091. var body = impostor.physicsBody;
  72092. mesh.position.x = body.position.x;
  72093. mesh.position.y = body.position.y;
  72094. mesh.position.z = body.position.z;
  72095. if (mesh.rotationQuaternion) {
  72096. mesh.rotationQuaternion.x = body.quaternion.x;
  72097. mesh.rotationQuaternion.y = body.quaternion.y;
  72098. mesh.rotationQuaternion.z = body.quaternion.z;
  72099. mesh.rotationQuaternion.w = body.quaternion.w;
  72100. }
  72101. };
  72102. CannonJSPlugin.prototype.getRadius = function (impostor) {
  72103. var shape = impostor.physicsBody.shapes[0];
  72104. return shape.boundingSphereRadius;
  72105. };
  72106. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  72107. var shape = impostor.physicsBody.shapes[0];
  72108. result.x = shape.halfExtents.x * 2;
  72109. result.y = shape.halfExtents.y * 2;
  72110. result.z = shape.halfExtents.z * 2;
  72111. };
  72112. CannonJSPlugin.prototype.dispose = function () {
  72113. };
  72114. CannonJSPlugin.prototype._extendNamespace = function () {
  72115. //this will force cannon to execute at least one step when using interpolation
  72116. var step_tmp1 = new this.BJSCANNON.Vec3();
  72117. var Engine = this.BJSCANNON;
  72118. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  72119. maxSubSteps = maxSubSteps || 10;
  72120. timeSinceLastCalled = timeSinceLastCalled || 0;
  72121. if (timeSinceLastCalled === 0) {
  72122. this.internalStep(dt);
  72123. this.time += dt;
  72124. }
  72125. else {
  72126. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  72127. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  72128. var t0 = performance.now();
  72129. for (var i = 0; i !== internalSteps; i++) {
  72130. this.internalStep(dt);
  72131. if (performance.now() - t0 > dt * 1000) {
  72132. break;
  72133. }
  72134. }
  72135. this.time += timeSinceLastCalled;
  72136. var h = this.time % dt;
  72137. var h_div_dt = h / dt;
  72138. var interpvelo = step_tmp1;
  72139. var bodies = this.bodies;
  72140. for (var j = 0; j !== bodies.length; j++) {
  72141. var b = bodies[j];
  72142. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  72143. b.position.vsub(b.previousPosition, interpvelo);
  72144. interpvelo.scale(h_div_dt, interpvelo);
  72145. b.position.vadd(interpvelo, b.interpolatedPosition);
  72146. }
  72147. else {
  72148. b.interpolatedPosition.copy(b.position);
  72149. b.interpolatedQuaternion.copy(b.quaternion);
  72150. }
  72151. }
  72152. }
  72153. };
  72154. };
  72155. return CannonJSPlugin;
  72156. }());
  72157. BABYLON.CannonJSPlugin = CannonJSPlugin;
  72158. })(BABYLON || (BABYLON = {}));
  72159. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  72160. var BABYLON;
  72161. (function (BABYLON) {
  72162. var OimoJSPlugin = /** @class */ (function () {
  72163. function OimoJSPlugin(iterations) {
  72164. this.name = "OimoJSPlugin";
  72165. this._tmpImpostorsArray = [];
  72166. this._tmpPositionVector = BABYLON.Vector3.Zero();
  72167. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  72168. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  72169. this.world.worldscale(1);
  72170. this.world.clear();
  72171. //making sure no stats are calculated
  72172. this.world.isNoStat = true;
  72173. }
  72174. OimoJSPlugin.prototype.setGravity = function (gravity) {
  72175. this.world.gravity.copy(gravity);
  72176. };
  72177. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  72178. this.world.timeStep = timeStep;
  72179. };
  72180. OimoJSPlugin.prototype.getTimeStep = function () {
  72181. return this.world.timeStep;
  72182. };
  72183. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  72184. var _this = this;
  72185. impostors.forEach(function (impostor) {
  72186. impostor.beforeStep();
  72187. });
  72188. this.world.step();
  72189. impostors.forEach(function (impostor) {
  72190. impostor.afterStep();
  72191. //update the ordered impostors array
  72192. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  72193. });
  72194. //check for collisions
  72195. var contact = this.world.contacts;
  72196. while (contact !== null) {
  72197. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  72198. contact = contact.next;
  72199. continue;
  72200. }
  72201. //is this body colliding with any other? get the impostor
  72202. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  72203. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  72204. if (!mainImpostor || !collidingImpostor) {
  72205. contact = contact.next;
  72206. continue;
  72207. }
  72208. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  72209. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  72210. contact = contact.next;
  72211. }
  72212. };
  72213. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  72214. var mass = impostor.physicsBody.massInfo.mass;
  72215. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  72216. };
  72217. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  72218. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  72219. this.applyImpulse(impostor, force, contactPoint);
  72220. };
  72221. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  72222. var _this = this;
  72223. //parent-child relationship. Does this impostor has a parent impostor?
  72224. if (impostor.parent) {
  72225. if (impostor.physicsBody) {
  72226. this.removePhysicsBody(impostor);
  72227. //TODO is that needed?
  72228. impostor.forceUpdate();
  72229. }
  72230. return;
  72231. }
  72232. if (impostor.isBodyInitRequired()) {
  72233. var bodyConfig = {
  72234. name: impostor.uniqueId,
  72235. //Oimo must have mass, also for static objects.
  72236. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  72237. size: [],
  72238. type: [],
  72239. pos: [],
  72240. rot: [],
  72241. move: impostor.getParam("mass") !== 0,
  72242. //Supporting older versions of Oimo
  72243. world: this.world
  72244. };
  72245. var impostors = [impostor];
  72246. var addToArray = function (parent) {
  72247. if (!parent.getChildMeshes)
  72248. return;
  72249. parent.getChildMeshes().forEach(function (m) {
  72250. if (m.physicsImpostor) {
  72251. impostors.push(m.physicsImpostor);
  72252. //m.physicsImpostor._init();
  72253. }
  72254. });
  72255. };
  72256. addToArray(impostor.object);
  72257. var checkWithEpsilon_1 = function (value) {
  72258. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  72259. };
  72260. impostors.forEach(function (i) {
  72261. if (!impostor.object.rotationQuaternion) {
  72262. return;
  72263. }
  72264. //get the correct bounding box
  72265. var oldQuaternion = i.object.rotationQuaternion;
  72266. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  72267. x: impostor.object.rotationQuaternion.x,
  72268. y: impostor.object.rotationQuaternion.y,
  72269. z: impostor.object.rotationQuaternion.z,
  72270. s: impostor.object.rotationQuaternion.w
  72271. });
  72272. var extendSize = i.getObjectExtendSize();
  72273. if (i === impostor) {
  72274. var center = impostor.getObjectCenter();
  72275. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  72276. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  72277. //Can also use Array.prototype.push.apply
  72278. bodyConfig.pos.push(center.x);
  72279. bodyConfig.pos.push(center.y);
  72280. bodyConfig.pos.push(center.z);
  72281. //tmp solution
  72282. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72283. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72284. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72285. }
  72286. else {
  72287. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  72288. bodyConfig.pos.push(localPosition.x);
  72289. bodyConfig.pos.push(localPosition.y);
  72290. bodyConfig.pos.push(localPosition.z);
  72291. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  72292. bodyConfig.rot.push(0);
  72293. bodyConfig.rot.push(0);
  72294. bodyConfig.rot.push(0);
  72295. }
  72296. // register mesh
  72297. switch (i.type) {
  72298. case BABYLON.PhysicsImpostor.ParticleImpostor:
  72299. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  72300. case BABYLON.PhysicsImpostor.SphereImpostor:
  72301. var radiusX = extendSize.x;
  72302. var radiusY = extendSize.y;
  72303. var radiusZ = extendSize.z;
  72304. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  72305. bodyConfig.type.push('sphere');
  72306. //due to the way oimo works with compounds, add 3 times
  72307. bodyConfig.size.push(size);
  72308. bodyConfig.size.push(size);
  72309. bodyConfig.size.push(size);
  72310. break;
  72311. case BABYLON.PhysicsImpostor.CylinderImpostor:
  72312. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  72313. var sizeY = checkWithEpsilon_1(extendSize.y);
  72314. bodyConfig.type.push('cylinder');
  72315. bodyConfig.size.push(sizeX);
  72316. bodyConfig.size.push(sizeY);
  72317. //due to the way oimo works with compounds, add one more value.
  72318. bodyConfig.size.push(sizeY);
  72319. break;
  72320. case BABYLON.PhysicsImpostor.PlaneImpostor:
  72321. case BABYLON.PhysicsImpostor.BoxImpostor:
  72322. default:
  72323. var sizeX = checkWithEpsilon_1(extendSize.x);
  72324. var sizeY = checkWithEpsilon_1(extendSize.y);
  72325. var sizeZ = checkWithEpsilon_1(extendSize.z);
  72326. bodyConfig.type.push('box');
  72327. bodyConfig.size.push(sizeX);
  72328. bodyConfig.size.push(sizeY);
  72329. bodyConfig.size.push(sizeZ);
  72330. break;
  72331. }
  72332. //actually not needed, but hey...
  72333. i.object.rotationQuaternion = oldQuaternion;
  72334. });
  72335. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  72336. }
  72337. else {
  72338. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  72339. }
  72340. impostor.setDeltaPosition(this._tmpPositionVector);
  72341. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  72342. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  72343. };
  72344. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  72345. //impostor.physicsBody.dispose();
  72346. //Same as : (older oimo versions)
  72347. this.world.removeRigidBody(impostor.physicsBody);
  72348. };
  72349. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  72350. var mainBody = impostorJoint.mainImpostor.physicsBody;
  72351. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  72352. if (!mainBody || !connectedBody) {
  72353. return;
  72354. }
  72355. var jointData = impostorJoint.joint.jointData;
  72356. var options = jointData.nativeParams || {};
  72357. var type;
  72358. var nativeJointData = {
  72359. body1: mainBody,
  72360. body2: connectedBody,
  72361. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  72362. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  72363. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  72364. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  72365. min: options.min,
  72366. max: options.max,
  72367. collision: options.collision || jointData.collision,
  72368. spring: options.spring,
  72369. //supporting older version of Oimo
  72370. world: this.world
  72371. };
  72372. switch (impostorJoint.joint.type) {
  72373. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  72374. type = "jointBall";
  72375. break;
  72376. case BABYLON.PhysicsJoint.SpringJoint:
  72377. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  72378. var springData = jointData;
  72379. nativeJointData.min = springData.length || nativeJointData.min;
  72380. //Max should also be set, just make sure it is at least min
  72381. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  72382. case BABYLON.PhysicsJoint.DistanceJoint:
  72383. type = "jointDistance";
  72384. nativeJointData.max = jointData.maxDistance;
  72385. break;
  72386. case BABYLON.PhysicsJoint.PrismaticJoint:
  72387. type = "jointPrisme";
  72388. break;
  72389. case BABYLON.PhysicsJoint.SliderJoint:
  72390. type = "jointSlide";
  72391. break;
  72392. case BABYLON.PhysicsJoint.WheelJoint:
  72393. type = "jointWheel";
  72394. break;
  72395. case BABYLON.PhysicsJoint.HingeJoint:
  72396. default:
  72397. type = "jointHinge";
  72398. break;
  72399. }
  72400. nativeJointData.type = type;
  72401. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  72402. };
  72403. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  72404. //Bug in Oimo prevents us from disposing a joint in the playground
  72405. //joint.joint.physicsJoint.dispose();
  72406. //So we will bruteforce it!
  72407. try {
  72408. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  72409. }
  72410. catch (e) {
  72411. BABYLON.Tools.Warn(e);
  72412. }
  72413. };
  72414. OimoJSPlugin.prototype.isSupported = function () {
  72415. return this.BJSOIMO !== undefined;
  72416. };
  72417. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  72418. if (!impostor.physicsBody.sleeping) {
  72419. //TODO check that
  72420. if (impostor.physicsBody.shapes.next) {
  72421. var parentShape = this._getLastShape(impostor.physicsBody);
  72422. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  72423. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  72424. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  72425. }
  72426. else {
  72427. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  72428. }
  72429. if (impostor.object.rotationQuaternion) {
  72430. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  72431. impostor.object.rotationQuaternion.normalize();
  72432. }
  72433. }
  72434. };
  72435. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  72436. var body = impostor.physicsBody;
  72437. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  72438. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  72439. body.syncShapes();
  72440. body.awake();
  72441. };
  72442. OimoJSPlugin.prototype._getLastShape = function (body) {
  72443. var lastShape = body.shapes;
  72444. while (lastShape.next) {
  72445. lastShape = lastShape.next;
  72446. }
  72447. return lastShape;
  72448. };
  72449. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  72450. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  72451. };
  72452. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  72453. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  72454. };
  72455. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  72456. var v = impostor.physicsBody.linearVelocity;
  72457. if (!v) {
  72458. return null;
  72459. }
  72460. return new BABYLON.Vector3(v.x, v.y, v.z);
  72461. };
  72462. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  72463. var v = impostor.physicsBody.angularVelocity;
  72464. if (!v) {
  72465. return null;
  72466. }
  72467. return new BABYLON.Vector3(v.x, v.y, v.z);
  72468. };
  72469. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  72470. var staticBody = mass === 0;
  72471. //this will actually set the body's density and not its mass.
  72472. //But this is how oimo treats the mass variable.
  72473. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  72474. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  72475. };
  72476. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  72477. return impostor.physicsBody.shapes.density;
  72478. };
  72479. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  72480. return impostor.physicsBody.shapes.friction;
  72481. };
  72482. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  72483. impostor.physicsBody.shapes.friction = friction;
  72484. };
  72485. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  72486. return impostor.physicsBody.shapes.restitution;
  72487. };
  72488. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  72489. impostor.physicsBody.shapes.restitution = restitution;
  72490. };
  72491. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  72492. impostor.physicsBody.sleep();
  72493. };
  72494. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  72495. impostor.physicsBody.awake();
  72496. };
  72497. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  72498. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  72499. if (minDistance !== void 0) {
  72500. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  72501. }
  72502. };
  72503. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  72504. //TODO separate rotational and transational motors.
  72505. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  72506. if (motor) {
  72507. motor.setMotor(speed, maxForce);
  72508. }
  72509. };
  72510. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  72511. //TODO separate rotational and transational motors.
  72512. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  72513. if (motor) {
  72514. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  72515. }
  72516. };
  72517. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  72518. var body = impostor.physicsBody;
  72519. mesh.position.x = body.position.x;
  72520. mesh.position.y = body.position.y;
  72521. mesh.position.z = body.position.z;
  72522. if (mesh.rotationQuaternion) {
  72523. mesh.rotationQuaternion.x = body.orientation.x;
  72524. mesh.rotationQuaternion.y = body.orientation.y;
  72525. mesh.rotationQuaternion.z = body.orientation.z;
  72526. mesh.rotationQuaternion.w = body.orientation.s;
  72527. }
  72528. };
  72529. OimoJSPlugin.prototype.getRadius = function (impostor) {
  72530. return impostor.physicsBody.shapes.radius;
  72531. };
  72532. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  72533. var shape = impostor.physicsBody.shapes;
  72534. result.x = shape.halfWidth * 2;
  72535. result.y = shape.halfHeight * 2;
  72536. result.z = shape.halfDepth * 2;
  72537. };
  72538. OimoJSPlugin.prototype.dispose = function () {
  72539. this.world.clear();
  72540. };
  72541. return OimoJSPlugin;
  72542. }());
  72543. BABYLON.OimoJSPlugin = OimoJSPlugin;
  72544. })(BABYLON || (BABYLON = {}));
  72545. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  72546. var BABYLON;
  72547. (function (BABYLON) {
  72548. /*
  72549. * Based on jsTGALoader - Javascript loader for TGA file
  72550. * By Vincent Thibault
  72551. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  72552. */
  72553. var TGATools = /** @class */ (function () {
  72554. function TGATools() {
  72555. }
  72556. TGATools.GetTGAHeader = function (data) {
  72557. var offset = 0;
  72558. var header = {
  72559. id_length: data[offset++],
  72560. colormap_type: data[offset++],
  72561. image_type: data[offset++],
  72562. colormap_index: data[offset++] | data[offset++] << 8,
  72563. colormap_length: data[offset++] | data[offset++] << 8,
  72564. colormap_size: data[offset++],
  72565. origin: [
  72566. data[offset++] | data[offset++] << 8,
  72567. data[offset++] | data[offset++] << 8
  72568. ],
  72569. width: data[offset++] | data[offset++] << 8,
  72570. height: data[offset++] | data[offset++] << 8,
  72571. pixel_size: data[offset++],
  72572. flags: data[offset++]
  72573. };
  72574. return header;
  72575. };
  72576. TGATools.UploadContent = function (gl, data) {
  72577. // Not enough data to contain header ?
  72578. if (data.length < 19) {
  72579. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  72580. return;
  72581. }
  72582. // Read Header
  72583. var offset = 18;
  72584. var header = TGATools.GetTGAHeader(data);
  72585. // Assume it's a valid Targa file.
  72586. if (header.id_length + offset > data.length) {
  72587. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  72588. return;
  72589. }
  72590. // Skip not needed data
  72591. offset += header.id_length;
  72592. var use_rle = false;
  72593. var use_pal = false;
  72594. var use_grey = false;
  72595. // Get some informations.
  72596. switch (header.image_type) {
  72597. case TGATools._TYPE_RLE_INDEXED:
  72598. use_rle = true;
  72599. case TGATools._TYPE_INDEXED:
  72600. use_pal = true;
  72601. break;
  72602. case TGATools._TYPE_RLE_RGB:
  72603. use_rle = true;
  72604. case TGATools._TYPE_RGB:
  72605. // use_rgb = true;
  72606. break;
  72607. case TGATools._TYPE_RLE_GREY:
  72608. use_rle = true;
  72609. case TGATools._TYPE_GREY:
  72610. use_grey = true;
  72611. break;
  72612. }
  72613. var pixel_data;
  72614. // var numAlphaBits = header.flags & 0xf;
  72615. var pixel_size = header.pixel_size >> 3;
  72616. var pixel_total = header.width * header.height * pixel_size;
  72617. // Read palettes
  72618. var palettes;
  72619. if (use_pal) {
  72620. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  72621. }
  72622. // Read LRE
  72623. if (use_rle) {
  72624. pixel_data = new Uint8Array(pixel_total);
  72625. var c, count, i;
  72626. var localOffset = 0;
  72627. var pixels = new Uint8Array(pixel_size);
  72628. while (offset < pixel_total && localOffset < pixel_total) {
  72629. c = data[offset++];
  72630. count = (c & 0x7f) + 1;
  72631. // RLE pixels
  72632. if (c & 0x80) {
  72633. // Bind pixel tmp array
  72634. for (i = 0; i < pixel_size; ++i) {
  72635. pixels[i] = data[offset++];
  72636. }
  72637. // Copy pixel array
  72638. for (i = 0; i < count; ++i) {
  72639. pixel_data.set(pixels, localOffset + i * pixel_size);
  72640. }
  72641. localOffset += pixel_size * count;
  72642. }
  72643. else {
  72644. count *= pixel_size;
  72645. for (i = 0; i < count; ++i) {
  72646. pixel_data[localOffset + i] = data[offset++];
  72647. }
  72648. localOffset += count;
  72649. }
  72650. }
  72651. }
  72652. else {
  72653. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  72654. }
  72655. // Load to texture
  72656. var x_start, y_start, x_step, y_step, y_end, x_end;
  72657. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  72658. default:
  72659. case TGATools._ORIGIN_UL:
  72660. x_start = 0;
  72661. x_step = 1;
  72662. x_end = header.width;
  72663. y_start = 0;
  72664. y_step = 1;
  72665. y_end = header.height;
  72666. break;
  72667. case TGATools._ORIGIN_BL:
  72668. x_start = 0;
  72669. x_step = 1;
  72670. x_end = header.width;
  72671. y_start = header.height - 1;
  72672. y_step = -1;
  72673. y_end = -1;
  72674. break;
  72675. case TGATools._ORIGIN_UR:
  72676. x_start = header.width - 1;
  72677. x_step = -1;
  72678. x_end = -1;
  72679. y_start = 0;
  72680. y_step = 1;
  72681. y_end = header.height;
  72682. break;
  72683. case TGATools._ORIGIN_BR:
  72684. x_start = header.width - 1;
  72685. x_step = -1;
  72686. x_end = -1;
  72687. y_start = header.height - 1;
  72688. y_step = -1;
  72689. y_end = -1;
  72690. break;
  72691. }
  72692. // Load the specify method
  72693. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  72694. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  72695. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  72696. };
  72697. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72698. var image = pixel_data, colormap = palettes;
  72699. var width = header.width, height = header.height;
  72700. var color, i = 0, x, y;
  72701. var imageData = new Uint8Array(width * height * 4);
  72702. for (y = y_start; y !== y_end; y += y_step) {
  72703. for (x = x_start; x !== x_end; x += x_step, i++) {
  72704. color = image[i];
  72705. imageData[(x + width * y) * 4 + 3] = 255;
  72706. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  72707. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  72708. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  72709. }
  72710. }
  72711. return imageData;
  72712. };
  72713. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72714. var image = pixel_data;
  72715. var width = header.width, height = header.height;
  72716. var color, i = 0, x, y;
  72717. var imageData = new Uint8Array(width * height * 4);
  72718. for (y = y_start; y !== y_end; y += y_step) {
  72719. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  72720. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  72721. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  72722. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  72723. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  72724. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  72725. }
  72726. }
  72727. return imageData;
  72728. };
  72729. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72730. var image = pixel_data;
  72731. var width = header.width, height = header.height;
  72732. var i = 0, x, y;
  72733. var imageData = new Uint8Array(width * height * 4);
  72734. for (y = y_start; y !== y_end; y += y_step) {
  72735. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  72736. imageData[(x + width * y) * 4 + 3] = 255;
  72737. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72738. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  72739. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  72740. }
  72741. }
  72742. return imageData;
  72743. };
  72744. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72745. var image = pixel_data;
  72746. var width = header.width, height = header.height;
  72747. var i = 0, x, y;
  72748. var imageData = new Uint8Array(width * height * 4);
  72749. for (y = y_start; y !== y_end; y += y_step) {
  72750. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  72751. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72752. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  72753. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  72754. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  72755. }
  72756. }
  72757. return imageData;
  72758. };
  72759. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72760. var image = pixel_data;
  72761. var width = header.width, height = header.height;
  72762. var color, i = 0, x, y;
  72763. var imageData = new Uint8Array(width * height * 4);
  72764. for (y = y_start; y !== y_end; y += y_step) {
  72765. for (x = x_start; x !== x_end; x += x_step, i++) {
  72766. color = image[i];
  72767. imageData[(x + width * y) * 4 + 0] = color;
  72768. imageData[(x + width * y) * 4 + 1] = color;
  72769. imageData[(x + width * y) * 4 + 2] = color;
  72770. imageData[(x + width * y) * 4 + 3] = 255;
  72771. }
  72772. }
  72773. return imageData;
  72774. };
  72775. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72776. var image = pixel_data;
  72777. var width = header.width, height = header.height;
  72778. var i = 0, x, y;
  72779. var imageData = new Uint8Array(width * height * 4);
  72780. for (y = y_start; y !== y_end; y += y_step) {
  72781. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  72782. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  72783. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  72784. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72785. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  72786. }
  72787. }
  72788. return imageData;
  72789. };
  72790. //private static _TYPE_NO_DATA = 0;
  72791. TGATools._TYPE_INDEXED = 1;
  72792. TGATools._TYPE_RGB = 2;
  72793. TGATools._TYPE_GREY = 3;
  72794. TGATools._TYPE_RLE_INDEXED = 9;
  72795. TGATools._TYPE_RLE_RGB = 10;
  72796. TGATools._TYPE_RLE_GREY = 11;
  72797. TGATools._ORIGIN_MASK = 0x30;
  72798. TGATools._ORIGIN_SHIFT = 0x04;
  72799. TGATools._ORIGIN_BL = 0x00;
  72800. TGATools._ORIGIN_BR = 0x01;
  72801. TGATools._ORIGIN_UL = 0x02;
  72802. TGATools._ORIGIN_UR = 0x03;
  72803. return TGATools;
  72804. }());
  72805. BABYLON.TGATools = TGATools;
  72806. })(BABYLON || (BABYLON = {}));
  72807. //# sourceMappingURL=babylon.tga.js.map
  72808. var BABYLON;
  72809. (function (BABYLON) {
  72810. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  72811. // All values and structures referenced from:
  72812. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  72813. var DDS_MAGIC = 0x20534444;
  72814. var
  72815. //DDSD_CAPS = 0x1,
  72816. //DDSD_HEIGHT = 0x2,
  72817. //DDSD_WIDTH = 0x4,
  72818. //DDSD_PITCH = 0x8,
  72819. //DDSD_PIXELFORMAT = 0x1000,
  72820. DDSD_MIPMAPCOUNT = 0x20000;
  72821. //DDSD_LINEARSIZE = 0x80000,
  72822. //DDSD_DEPTH = 0x800000;
  72823. // var DDSCAPS_COMPLEX = 0x8,
  72824. // DDSCAPS_MIPMAP = 0x400000,
  72825. // DDSCAPS_TEXTURE = 0x1000;
  72826. var DDSCAPS2_CUBEMAP = 0x200;
  72827. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  72828. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  72829. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  72830. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  72831. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  72832. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  72833. // DDSCAPS2_VOLUME = 0x200000;
  72834. var
  72835. //DDPF_ALPHAPIXELS = 0x1,
  72836. //DDPF_ALPHA = 0x2,
  72837. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  72838. //DDPF_YUV = 0x200,
  72839. DDPF_LUMINANCE = 0x20000;
  72840. function FourCCToInt32(value) {
  72841. return value.charCodeAt(0) +
  72842. (value.charCodeAt(1) << 8) +
  72843. (value.charCodeAt(2) << 16) +
  72844. (value.charCodeAt(3) << 24);
  72845. }
  72846. function Int32ToFourCC(value) {
  72847. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  72848. }
  72849. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  72850. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  72851. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  72852. var FOURCC_DX10 = FourCCToInt32("DX10");
  72853. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  72854. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  72855. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  72856. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  72857. var headerLengthInt = 31; // The header length in 32 bit ints
  72858. // Offsets into the header array
  72859. var off_magic = 0;
  72860. var off_size = 1;
  72861. var off_flags = 2;
  72862. var off_height = 3;
  72863. var off_width = 4;
  72864. var off_mipmapCount = 7;
  72865. var off_pfFlags = 20;
  72866. var off_pfFourCC = 21;
  72867. var off_RGBbpp = 22;
  72868. var off_RMask = 23;
  72869. var off_GMask = 24;
  72870. var off_BMask = 25;
  72871. var off_AMask = 26;
  72872. // var off_caps1 = 27;
  72873. var off_caps2 = 28;
  72874. // var off_caps3 = 29;
  72875. // var off_caps4 = 30;
  72876. var off_dxgiFormat = 32;
  72877. ;
  72878. var DDSTools = /** @class */ (function () {
  72879. function DDSTools() {
  72880. }
  72881. DDSTools.GetDDSInfo = function (arrayBuffer) {
  72882. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72883. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  72884. var mipmapCount = 1;
  72885. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  72886. mipmapCount = Math.max(1, header[off_mipmapCount]);
  72887. }
  72888. var fourCC = header[off_pfFourCC];
  72889. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  72890. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72891. switch (fourCC) {
  72892. case FOURCC_D3DFMT_R16G16B16A16F:
  72893. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72894. break;
  72895. case FOURCC_D3DFMT_R32G32B32A32F:
  72896. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72897. break;
  72898. case FOURCC_DX10:
  72899. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  72900. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72901. break;
  72902. }
  72903. }
  72904. return {
  72905. width: header[off_width],
  72906. height: header[off_height],
  72907. mipmapCount: mipmapCount,
  72908. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  72909. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  72910. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  72911. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  72912. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  72913. dxgiFormat: dxgiFormat,
  72914. textureType: textureType
  72915. };
  72916. };
  72917. DDSTools._ToHalfFloat = function (value) {
  72918. if (!DDSTools._FloatView) {
  72919. DDSTools._FloatView = new Float32Array(1);
  72920. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  72921. }
  72922. DDSTools._FloatView[0] = value;
  72923. var x = DDSTools._Int32View[0];
  72924. var bits = (x >> 16) & 0x8000; /* Get the sign */
  72925. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  72926. var e = (x >> 23) & 0xff; /* Using int is faster here */
  72927. /* If zero, or denormal, or exponent underflows too much for a denormal
  72928. * half, return signed zero. */
  72929. if (e < 103) {
  72930. return bits;
  72931. }
  72932. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  72933. if (e > 142) {
  72934. bits |= 0x7c00;
  72935. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  72936. * not Inf, so make sure we set one mantissa bit too. */
  72937. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  72938. return bits;
  72939. }
  72940. /* If exponent underflows but not too much, return a denormal */
  72941. if (e < 113) {
  72942. m |= 0x0800;
  72943. /* Extra rounding may overflow and set mantissa to 0 and exponent
  72944. * to 1, which is OK. */
  72945. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  72946. return bits;
  72947. }
  72948. bits |= ((e - 112) << 10) | (m >> 1);
  72949. bits += m & 1;
  72950. return bits;
  72951. };
  72952. DDSTools._FromHalfFloat = function (value) {
  72953. var s = (value & 0x8000) >> 15;
  72954. var e = (value & 0x7C00) >> 10;
  72955. var f = value & 0x03FF;
  72956. if (e === 0) {
  72957. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  72958. }
  72959. else if (e == 0x1F) {
  72960. return f ? NaN : ((s ? -1 : 1) * Infinity);
  72961. }
  72962. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  72963. };
  72964. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72965. var destArray = new Float32Array(dataLength);
  72966. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72967. var index = 0;
  72968. for (var y = 0; y < height; y++) {
  72969. for (var x = 0; x < width; x++) {
  72970. var srcPos = (x + y * width) * 4;
  72971. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  72972. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  72973. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  72974. if (DDSTools.StoreLODInAlphaChannel) {
  72975. destArray[index + 3] = lod;
  72976. }
  72977. else {
  72978. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  72979. }
  72980. index += 4;
  72981. }
  72982. }
  72983. return destArray;
  72984. };
  72985. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72986. if (DDSTools.StoreLODInAlphaChannel) {
  72987. var destArray = new Uint16Array(dataLength);
  72988. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72989. var index = 0;
  72990. for (var y = 0; y < height; y++) {
  72991. for (var x = 0; x < width; x++) {
  72992. var srcPos = (x + y * width) * 4;
  72993. destArray[index] = srcData[srcPos];
  72994. destArray[index + 1] = srcData[srcPos + 1];
  72995. destArray[index + 2] = srcData[srcPos + 2];
  72996. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  72997. index += 4;
  72998. }
  72999. }
  73000. return destArray;
  73001. }
  73002. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  73003. };
  73004. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73005. if (DDSTools.StoreLODInAlphaChannel) {
  73006. var destArray = new Float32Array(dataLength);
  73007. var srcData = new Float32Array(arrayBuffer, dataOffset);
  73008. var index = 0;
  73009. for (var y = 0; y < height; y++) {
  73010. for (var x = 0; x < width; x++) {
  73011. var srcPos = (x + y * width) * 4;
  73012. destArray[index] = srcData[srcPos];
  73013. destArray[index + 1] = srcData[srcPos + 1];
  73014. destArray[index + 2] = srcData[srcPos + 2];
  73015. destArray[index + 3] = lod;
  73016. index += 4;
  73017. }
  73018. }
  73019. return destArray;
  73020. }
  73021. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  73022. };
  73023. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73024. var destArray = new Uint8Array(dataLength);
  73025. var srcData = new Float32Array(arrayBuffer, dataOffset);
  73026. var index = 0;
  73027. for (var y = 0; y < height; y++) {
  73028. for (var x = 0; x < width; x++) {
  73029. var srcPos = (x + y * width) * 4;
  73030. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  73031. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  73032. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  73033. if (DDSTools.StoreLODInAlphaChannel) {
  73034. destArray[index + 3] = lod;
  73035. }
  73036. else {
  73037. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  73038. }
  73039. index += 4;
  73040. }
  73041. }
  73042. return destArray;
  73043. };
  73044. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  73045. var destArray = new Uint8Array(dataLength);
  73046. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  73047. var index = 0;
  73048. for (var y = 0; y < height; y++) {
  73049. for (var x = 0; x < width; x++) {
  73050. var srcPos = (x + y * width) * 4;
  73051. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  73052. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  73053. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  73054. if (DDSTools.StoreLODInAlphaChannel) {
  73055. destArray[index + 3] = lod;
  73056. }
  73057. else {
  73058. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  73059. }
  73060. index += 4;
  73061. }
  73062. }
  73063. return destArray;
  73064. };
  73065. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  73066. var byteArray = new Uint8Array(dataLength);
  73067. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73068. var index = 0;
  73069. for (var y = 0; y < height; y++) {
  73070. for (var x = 0; x < width; x++) {
  73071. var srcPos = (x + y * width) * 4;
  73072. byteArray[index] = srcData[srcPos + rOffset];
  73073. byteArray[index + 1] = srcData[srcPos + gOffset];
  73074. byteArray[index + 2] = srcData[srcPos + bOffset];
  73075. byteArray[index + 3] = srcData[srcPos + aOffset];
  73076. index += 4;
  73077. }
  73078. }
  73079. return byteArray;
  73080. };
  73081. DDSTools._ExtractLongWordOrder = function (value) {
  73082. if (value === 0 || value === 255 || value === -16777216) {
  73083. return 0;
  73084. }
  73085. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  73086. };
  73087. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  73088. var byteArray = new Uint8Array(dataLength);
  73089. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73090. var index = 0;
  73091. for (var y = 0; y < height; y++) {
  73092. for (var x = 0; x < width; x++) {
  73093. var srcPos = (x + y * width) * 3;
  73094. byteArray[index] = srcData[srcPos + rOffset];
  73095. byteArray[index + 1] = srcData[srcPos + gOffset];
  73096. byteArray[index + 2] = srcData[srcPos + bOffset];
  73097. index += 3;
  73098. }
  73099. }
  73100. return byteArray;
  73101. };
  73102. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  73103. var byteArray = new Uint8Array(dataLength);
  73104. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  73105. var index = 0;
  73106. for (var y = 0; y < height; y++) {
  73107. for (var x = 0; x < width; x++) {
  73108. var srcPos = (x + y * width);
  73109. byteArray[index] = srcData[srcPos];
  73110. index++;
  73111. }
  73112. }
  73113. return byteArray;
  73114. };
  73115. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  73116. if (lodIndex === void 0) { lodIndex = -1; }
  73117. var ext = engine.getCaps().s3tc;
  73118. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  73119. var fourCC, width, height, dataLength = 0, dataOffset;
  73120. var byteArray, mipmapCount, mip;
  73121. var internalFormat = 0;
  73122. var format = 0;
  73123. var blockBytes = 1;
  73124. if (header[off_magic] !== DDS_MAGIC) {
  73125. BABYLON.Tools.Error("Invalid magic number in DDS header");
  73126. return;
  73127. }
  73128. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  73129. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  73130. return;
  73131. }
  73132. if (info.isCompressed && !ext) {
  73133. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  73134. return;
  73135. }
  73136. var bpp = header[off_RGBbpp];
  73137. dataOffset = header[off_size] + 4;
  73138. var computeFormats = false;
  73139. if (info.isFourCC) {
  73140. fourCC = header[off_pfFourCC];
  73141. switch (fourCC) {
  73142. case FOURCC_DXT1:
  73143. blockBytes = 8;
  73144. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  73145. break;
  73146. case FOURCC_DXT3:
  73147. blockBytes = 16;
  73148. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  73149. break;
  73150. case FOURCC_DXT5:
  73151. blockBytes = 16;
  73152. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  73153. break;
  73154. case FOURCC_D3DFMT_R16G16B16A16F:
  73155. computeFormats = true;
  73156. break;
  73157. case FOURCC_D3DFMT_R32G32B32A32F:
  73158. computeFormats = true;
  73159. break;
  73160. case FOURCC_DX10:
  73161. // There is an additionnal header so dataOffset need to be changed
  73162. dataOffset += 5 * 4; // 5 uints
  73163. var supported = false;
  73164. switch (info.dxgiFormat) {
  73165. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  73166. computeFormats = true;
  73167. supported = true;
  73168. break;
  73169. case DXGI_FORMAT_B8G8R8X8_UNORM:
  73170. info.isRGB = true;
  73171. info.isFourCC = false;
  73172. bpp = 32;
  73173. supported = true;
  73174. break;
  73175. }
  73176. if (supported) {
  73177. break;
  73178. }
  73179. default:
  73180. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  73181. return;
  73182. }
  73183. }
  73184. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  73185. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  73186. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  73187. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  73188. if (computeFormats) {
  73189. format = engine._getWebGLTextureType(info.textureType);
  73190. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73191. }
  73192. mipmapCount = 1;
  73193. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  73194. mipmapCount = Math.max(1, header[off_mipmapCount]);
  73195. }
  73196. for (var face = 0; face < faces; face++) {
  73197. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  73198. width = header[off_width];
  73199. height = header[off_height];
  73200. for (mip = 0; mip < mipmapCount; ++mip) {
  73201. if (lodIndex === -1 || lodIndex === mip) {
  73202. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  73203. var i = (lodIndex === -1) ? mip : 0;
  73204. if (!info.isCompressed && info.isFourCC) {
  73205. dataLength = width * height * 4;
  73206. var floatArray = null;
  73207. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  73208. if (bpp === 128) {
  73209. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73210. }
  73211. else if (bpp === 64) {
  73212. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73213. }
  73214. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73215. format = engine._getWebGLTextureType(info.textureType);
  73216. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73217. }
  73218. else {
  73219. if (bpp === 128) {
  73220. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73221. }
  73222. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  73223. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73224. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73225. format = engine._getWebGLTextureType(info.textureType);
  73226. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  73227. }
  73228. else {
  73229. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  73230. }
  73231. }
  73232. if (floatArray) {
  73233. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  73234. }
  73235. }
  73236. else if (info.isRGB) {
  73237. if (bpp === 24) {
  73238. dataLength = width * height * 3;
  73239. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  73240. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  73241. }
  73242. else {
  73243. dataLength = width * height * 4;
  73244. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  73245. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  73246. }
  73247. }
  73248. else if (info.isLuminance) {
  73249. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  73250. var unpaddedRowSize = width;
  73251. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  73252. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  73253. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  73254. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  73255. }
  73256. else {
  73257. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  73258. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  73259. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  73260. }
  73261. }
  73262. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  73263. width *= 0.5;
  73264. height *= 0.5;
  73265. width = Math.max(1.0, width);
  73266. height = Math.max(1.0, height);
  73267. }
  73268. if (currentFace !== undefined) {
  73269. // Loading a single face
  73270. break;
  73271. }
  73272. }
  73273. };
  73274. DDSTools.StoreLODInAlphaChannel = false;
  73275. return DDSTools;
  73276. }());
  73277. BABYLON.DDSTools = DDSTools;
  73278. })(BABYLON || (BABYLON = {}));
  73279. //# sourceMappingURL=babylon.dds.js.map
  73280. var BABYLON;
  73281. (function (BABYLON) {
  73282. /**
  73283. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  73284. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  73285. */
  73286. var KhronosTextureContainer = /** @class */ (function () {
  73287. /**
  73288. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  73289. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  73290. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  73291. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  73292. */
  73293. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  73294. this.arrayBuffer = arrayBuffer;
  73295. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  73296. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  73297. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  73298. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  73299. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  73300. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  73301. BABYLON.Tools.Error("texture missing KTX identifier");
  73302. return;
  73303. }
  73304. // load the reset of the header in native 32 bit int
  73305. var header = new Int32Array(this.arrayBuffer, 12, 13);
  73306. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  73307. var oppositeEndianess = header[0] === 0x01020304;
  73308. // read all the header elements in order they exist in the file, without modification (sans endainness)
  73309. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  73310. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  73311. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  73312. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  73313. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  73314. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  73315. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  73316. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  73317. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  73318. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  73319. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  73320. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  73321. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  73322. if (this.glType !== 0) {
  73323. BABYLON.Tools.Error("only compressed formats currently supported");
  73324. return;
  73325. }
  73326. else {
  73327. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  73328. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  73329. }
  73330. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  73331. BABYLON.Tools.Error("only 2D textures currently supported");
  73332. return;
  73333. }
  73334. if (this.numberOfArrayElements !== 0) {
  73335. BABYLON.Tools.Error("texture arrays not currently supported");
  73336. return;
  73337. }
  73338. if (this.numberOfFaces !== facesExpected) {
  73339. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  73340. return;
  73341. }
  73342. // we now have a completely validated file, so could use existence of loadType as success
  73343. // would need to make this more elaborate & adjust checks above to support more than one load type
  73344. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  73345. }
  73346. // not as fast hardware based, but will probably never need to use
  73347. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  73348. return ((val & 0xFF) << 24)
  73349. | ((val & 0xFF00) << 8)
  73350. | ((val >> 8) & 0xFF00)
  73351. | ((val >> 24) & 0xFF);
  73352. };
  73353. /**
  73354. * It is assumed that the texture has already been created & is currently bound
  73355. */
  73356. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  73357. switch (this.loadType) {
  73358. case KhronosTextureContainer.COMPRESSED_2D:
  73359. this._upload2DCompressedLevels(gl, loadMipmaps);
  73360. break;
  73361. case KhronosTextureContainer.TEX_2D:
  73362. case KhronosTextureContainer.COMPRESSED_3D:
  73363. case KhronosTextureContainer.TEX_3D:
  73364. }
  73365. };
  73366. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  73367. // initialize width & height for level 1
  73368. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  73369. var width = this.pixelWidth;
  73370. var height = this.pixelHeight;
  73371. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  73372. for (var level = 0; level < mipmapCount; level++) {
  73373. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  73374. for (var face = 0; face < this.numberOfFaces; face++) {
  73375. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  73376. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  73377. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  73378. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  73379. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  73380. }
  73381. width = Math.max(1.0, width * 0.5);
  73382. height = Math.max(1.0, height * 0.5);
  73383. }
  73384. };
  73385. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  73386. // load types
  73387. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  73388. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  73389. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  73390. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  73391. return KhronosTextureContainer;
  73392. }());
  73393. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  73394. })(BABYLON || (BABYLON = {}));
  73395. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  73396. var BABYLON;
  73397. (function (BABYLON) {
  73398. var Debug = /** @class */ (function () {
  73399. function Debug() {
  73400. }
  73401. Debug.AxesViewer = /** @class */ (function () {
  73402. function AxesViewer(scene, scaleLines) {
  73403. if (scaleLines === void 0) { scaleLines = 1; }
  73404. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73405. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73406. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73407. this.scaleLines = 1;
  73408. this.scaleLines = scaleLines;
  73409. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  73410. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  73411. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  73412. this._xmesh.renderingGroupId = 2;
  73413. this._ymesh.renderingGroupId = 2;
  73414. this._zmesh.renderingGroupId = 2;
  73415. this._xmesh.material.checkReadyOnlyOnce = true;
  73416. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  73417. this._ymesh.material.checkReadyOnlyOnce = true;
  73418. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  73419. this._zmesh.material.checkReadyOnlyOnce = true;
  73420. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  73421. this.scene = scene;
  73422. }
  73423. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  73424. var scaleLines = this.scaleLines;
  73425. if (this._xmesh) {
  73426. this._xmesh.position.copyFrom(position);
  73427. }
  73428. if (this._ymesh) {
  73429. this._ymesh.position.copyFrom(position);
  73430. }
  73431. if (this._zmesh) {
  73432. this._zmesh.position.copyFrom(position);
  73433. }
  73434. var point2 = this._xline[1];
  73435. point2.x = xaxis.x * scaleLines;
  73436. point2.y = xaxis.y * scaleLines;
  73437. point2.z = xaxis.z * scaleLines;
  73438. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  73439. point2 = this._yline[1];
  73440. point2.x = yaxis.x * scaleLines;
  73441. point2.y = yaxis.y * scaleLines;
  73442. point2.z = yaxis.z * scaleLines;
  73443. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  73444. point2 = this._zline[1];
  73445. point2.x = zaxis.x * scaleLines;
  73446. point2.y = zaxis.y * scaleLines;
  73447. point2.z = zaxis.z * scaleLines;
  73448. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  73449. };
  73450. AxesViewer.prototype.dispose = function () {
  73451. if (this._xmesh) {
  73452. this._xmesh.dispose();
  73453. }
  73454. if (this._ymesh) {
  73455. this._ymesh.dispose();
  73456. }
  73457. if (this._zmesh) {
  73458. this._zmesh.dispose();
  73459. }
  73460. this._xmesh = null;
  73461. this._ymesh = null;
  73462. this._zmesh = null;
  73463. this.scene = null;
  73464. };
  73465. return AxesViewer;
  73466. }());
  73467. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  73468. __extends(BoneAxesViewer, _super);
  73469. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  73470. if (scaleLines === void 0) { scaleLines = 1; }
  73471. var _this = _super.call(this, scene, scaleLines) || this;
  73472. _this.pos = BABYLON.Vector3.Zero();
  73473. _this.xaxis = BABYLON.Vector3.Zero();
  73474. _this.yaxis = BABYLON.Vector3.Zero();
  73475. _this.zaxis = BABYLON.Vector3.Zero();
  73476. _this.mesh = mesh;
  73477. _this.bone = bone;
  73478. return _this;
  73479. }
  73480. BoneAxesViewer.prototype.update = function () {
  73481. if (!this.mesh || !this.bone) {
  73482. return;
  73483. }
  73484. var bone = this.bone;
  73485. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  73486. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  73487. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  73488. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  73489. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  73490. };
  73491. BoneAxesViewer.prototype.dispose = function () {
  73492. if (this.mesh) {
  73493. this.mesh = null;
  73494. this.bone = null;
  73495. _super.prototype.dispose.call(this);
  73496. }
  73497. };
  73498. return BoneAxesViewer;
  73499. }(Debug.AxesViewer));
  73500. Debug.PhysicsViewer = /** @class */ (function () {
  73501. function PhysicsViewer(scene) {
  73502. this._impostors = [];
  73503. this._meshes = [];
  73504. this._numMeshes = 0;
  73505. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73506. var physicEngine = this._scene.getPhysicsEngine();
  73507. if (physicEngine) {
  73508. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  73509. }
  73510. }
  73511. PhysicsViewer.prototype._updateDebugMeshes = function () {
  73512. var plugin = this._physicsEnginePlugin;
  73513. for (var i = 0; i < this._numMeshes; i++) {
  73514. var impostor = this._impostors[i];
  73515. if (!impostor) {
  73516. continue;
  73517. }
  73518. if (impostor.isDisposed) {
  73519. this.hideImpostor(this._impostors[i--]);
  73520. }
  73521. else {
  73522. var mesh = this._meshes[i];
  73523. if (mesh && plugin) {
  73524. plugin.syncMeshWithImpostor(mesh, impostor);
  73525. }
  73526. }
  73527. }
  73528. };
  73529. PhysicsViewer.prototype.showImpostor = function (impostor) {
  73530. if (!this._scene) {
  73531. return;
  73532. }
  73533. for (var i = 0; i < this._numMeshes; i++) {
  73534. if (this._impostors[i] == impostor) {
  73535. return;
  73536. }
  73537. }
  73538. var debugMesh = this._getDebugMesh(impostor, this._scene);
  73539. if (debugMesh) {
  73540. this._impostors[this._numMeshes] = impostor;
  73541. this._meshes[this._numMeshes] = debugMesh;
  73542. if (this._numMeshes === 0) {
  73543. this._renderFunction = this._updateDebugMeshes.bind(this);
  73544. this._scene.registerBeforeRender(this._renderFunction);
  73545. }
  73546. this._numMeshes++;
  73547. }
  73548. };
  73549. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  73550. if (!impostor || !this._scene) {
  73551. return;
  73552. }
  73553. var removed = false;
  73554. for (var i = 0; i < this._numMeshes; i++) {
  73555. if (this._impostors[i] == impostor) {
  73556. var mesh = this._meshes[i];
  73557. if (!mesh) {
  73558. continue;
  73559. }
  73560. this._scene.removeMesh(mesh);
  73561. mesh.dispose();
  73562. this._numMeshes--;
  73563. if (this._numMeshes > 0) {
  73564. this._meshes[i] = this._meshes[this._numMeshes];
  73565. this._impostors[i] = this._impostors[this._numMeshes];
  73566. this._meshes[this._numMeshes] = null;
  73567. this._impostors[this._numMeshes] = null;
  73568. }
  73569. else {
  73570. this._meshes[0] = null;
  73571. this._impostors[0] = null;
  73572. }
  73573. removed = true;
  73574. break;
  73575. }
  73576. }
  73577. if (removed && this._numMeshes === 0) {
  73578. this._scene.unregisterBeforeRender(this._renderFunction);
  73579. }
  73580. };
  73581. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  73582. if (!this._debugMaterial) {
  73583. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  73584. this._debugMaterial.wireframe = true;
  73585. }
  73586. return this._debugMaterial;
  73587. };
  73588. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  73589. if (!this._debugBoxMesh) {
  73590. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  73591. this._debugBoxMesh.renderingGroupId = 1;
  73592. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  73593. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  73594. scene.removeMesh(this._debugBoxMesh);
  73595. }
  73596. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  73597. };
  73598. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  73599. if (!this._debugSphereMesh) {
  73600. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  73601. this._debugSphereMesh.renderingGroupId = 1;
  73602. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  73603. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  73604. scene.removeMesh(this._debugSphereMesh);
  73605. }
  73606. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  73607. };
  73608. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  73609. var mesh = null;
  73610. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  73611. mesh = this._getDebugBoxMesh(scene);
  73612. impostor.getBoxSizeToRef(mesh.scaling);
  73613. }
  73614. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  73615. mesh = this._getDebugSphereMesh(scene);
  73616. var radius = impostor.getRadius();
  73617. mesh.scaling.x = radius * 2;
  73618. mesh.scaling.y = radius * 2;
  73619. mesh.scaling.z = radius * 2;
  73620. }
  73621. return mesh;
  73622. };
  73623. PhysicsViewer.prototype.dispose = function () {
  73624. for (var i = 0; i < this._numMeshes; i++) {
  73625. this.hideImpostor(this._impostors[i]);
  73626. }
  73627. if (this._debugBoxMesh) {
  73628. this._debugBoxMesh.dispose();
  73629. }
  73630. if (this._debugSphereMesh) {
  73631. this._debugSphereMesh.dispose();
  73632. }
  73633. if (this._debugMaterial) {
  73634. this._debugMaterial.dispose();
  73635. }
  73636. this._impostors.length = 0;
  73637. this._scene = null;
  73638. this._physicsEnginePlugin = null;
  73639. };
  73640. return PhysicsViewer;
  73641. }());
  73642. Debug.SkeletonViewer = /** @class */ (function () {
  73643. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  73644. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  73645. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  73646. this.skeleton = skeleton;
  73647. this.mesh = mesh;
  73648. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  73649. this.renderingGroupId = renderingGroupId;
  73650. this.color = BABYLON.Color3.White();
  73651. this._debugLines = new Array();
  73652. this._isEnabled = false;
  73653. this._scene = scene;
  73654. this.update();
  73655. this._renderFunction = this.update.bind(this);
  73656. }
  73657. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  73658. get: function () {
  73659. return this._isEnabled;
  73660. },
  73661. set: function (value) {
  73662. if (this._isEnabled === value) {
  73663. return;
  73664. }
  73665. this._isEnabled = value;
  73666. if (value) {
  73667. this._scene.registerBeforeRender(this._renderFunction);
  73668. }
  73669. else {
  73670. this._scene.unregisterBeforeRender(this._renderFunction);
  73671. }
  73672. },
  73673. enumerable: true,
  73674. configurable: true
  73675. });
  73676. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  73677. if (x === void 0) { x = 0; }
  73678. if (y === void 0) { y = 0; }
  73679. if (z === void 0) { z = 0; }
  73680. var tmat = BABYLON.Tmp.Matrix[0];
  73681. var parentBone = bone.getParent();
  73682. tmat.copyFrom(bone.getLocalMatrix());
  73683. if (x !== 0 || y !== 0 || z !== 0) {
  73684. var tmat2 = BABYLON.Tmp.Matrix[1];
  73685. BABYLON.Matrix.IdentityToRef(tmat2);
  73686. tmat2.m[12] = x;
  73687. tmat2.m[13] = y;
  73688. tmat2.m[14] = z;
  73689. tmat2.multiplyToRef(tmat, tmat);
  73690. }
  73691. if (parentBone) {
  73692. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  73693. }
  73694. tmat.multiplyToRef(meshMat, tmat);
  73695. position.x = tmat.m[12];
  73696. position.y = tmat.m[13];
  73697. position.z = tmat.m[14];
  73698. };
  73699. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  73700. var len = bones.length;
  73701. var meshPos = this.mesh.position;
  73702. for (var i = 0; i < len; i++) {
  73703. var bone = bones[i];
  73704. var points = this._debugLines[i];
  73705. if (!points) {
  73706. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73707. this._debugLines[i] = points;
  73708. }
  73709. this._getBonePosition(points[0], bone, meshMat);
  73710. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  73711. points[0].subtractInPlace(meshPos);
  73712. points[1].subtractInPlace(meshPos);
  73713. }
  73714. };
  73715. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  73716. var len = bones.length;
  73717. var boneNum = 0;
  73718. var meshPos = this.mesh.position;
  73719. for (var i = len - 1; i >= 0; i--) {
  73720. var childBone = bones[i];
  73721. var parentBone = childBone.getParent();
  73722. if (!parentBone) {
  73723. continue;
  73724. }
  73725. var points = this._debugLines[boneNum];
  73726. if (!points) {
  73727. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73728. this._debugLines[boneNum] = points;
  73729. }
  73730. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  73731. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  73732. points[0].subtractInPlace(meshPos);
  73733. points[1].subtractInPlace(meshPos);
  73734. boneNum++;
  73735. }
  73736. };
  73737. SkeletonViewer.prototype.update = function () {
  73738. if (this.autoUpdateBonesMatrices) {
  73739. this.skeleton.computeAbsoluteTransforms();
  73740. }
  73741. if (this.skeleton.bones[0].length === undefined) {
  73742. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  73743. }
  73744. else {
  73745. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  73746. }
  73747. if (!this._debugMesh) {
  73748. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  73749. this._debugMesh.renderingGroupId = this.renderingGroupId;
  73750. }
  73751. else {
  73752. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  73753. }
  73754. this._debugMesh.position.copyFrom(this.mesh.position);
  73755. this._debugMesh.color = this.color;
  73756. };
  73757. SkeletonViewer.prototype.dispose = function () {
  73758. if (this._debugMesh) {
  73759. this.isEnabled = false;
  73760. this._debugMesh.dispose();
  73761. this._debugMesh = null;
  73762. }
  73763. };
  73764. return SkeletonViewer;
  73765. }());
  73766. return Debug;
  73767. }());
  73768. BABYLON.Debug = Debug;
  73769. })(BABYLON || (BABYLON = {}));
  73770. //# sourceMappingURL=babylon.debugModules.js.map
  73771. var BABYLON;
  73772. (function (BABYLON) {
  73773. var RayHelper = /** @class */ (function () {
  73774. function RayHelper(ray) {
  73775. this.ray = ray;
  73776. }
  73777. RayHelper.CreateAndShow = function (ray, scene, color) {
  73778. var helper = new RayHelper(ray);
  73779. helper.show(scene, color);
  73780. return helper;
  73781. };
  73782. RayHelper.prototype.show = function (scene, color) {
  73783. if (!this._renderFunction && this.ray) {
  73784. var ray = this.ray;
  73785. this._renderFunction = this._render.bind(this);
  73786. this._scene = scene;
  73787. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  73788. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  73789. if (this._renderFunction) {
  73790. this._scene.registerBeforeRender(this._renderFunction);
  73791. }
  73792. }
  73793. if (color && this._renderLine) {
  73794. this._renderLine.color.copyFrom(color);
  73795. }
  73796. };
  73797. RayHelper.prototype.hide = function () {
  73798. if (this._renderFunction && this._scene) {
  73799. this._scene.unregisterBeforeRender(this._renderFunction);
  73800. this._scene = null;
  73801. this._renderFunction = null;
  73802. if (this._renderLine) {
  73803. this._renderLine.dispose();
  73804. this._renderLine = null;
  73805. }
  73806. this._renderPoints = [];
  73807. }
  73808. };
  73809. RayHelper.prototype._render = function () {
  73810. var ray = this.ray;
  73811. if (!ray) {
  73812. return;
  73813. }
  73814. var point = this._renderPoints[1];
  73815. var len = Math.min(ray.length, 1000000);
  73816. point.copyFrom(ray.direction);
  73817. point.scaleInPlace(len);
  73818. point.addInPlace(ray.origin);
  73819. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  73820. };
  73821. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  73822. this._attachedToMesh = mesh;
  73823. var ray = this.ray;
  73824. if (!ray) {
  73825. return;
  73826. }
  73827. if (!ray.direction) {
  73828. ray.direction = BABYLON.Vector3.Zero();
  73829. }
  73830. if (!ray.origin) {
  73831. ray.origin = BABYLON.Vector3.Zero();
  73832. }
  73833. if (length) {
  73834. ray.length = length;
  73835. }
  73836. if (!meshSpaceOrigin) {
  73837. meshSpaceOrigin = BABYLON.Vector3.Zero();
  73838. }
  73839. if (!meshSpaceDirection) {
  73840. // -1 so that this will work with Mesh.lookAt
  73841. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  73842. }
  73843. if (!this._meshSpaceDirection) {
  73844. this._meshSpaceDirection = meshSpaceDirection.clone();
  73845. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  73846. }
  73847. else {
  73848. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  73849. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  73850. }
  73851. if (!this._updateToMeshFunction) {
  73852. this._updateToMeshFunction = this._updateToMesh.bind(this);
  73853. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  73854. }
  73855. this._updateToMesh();
  73856. };
  73857. RayHelper.prototype.detachFromMesh = function () {
  73858. if (this._attachedToMesh) {
  73859. if (this._updateToMeshFunction) {
  73860. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  73861. }
  73862. this._attachedToMesh = null;
  73863. this._updateToMeshFunction = null;
  73864. }
  73865. };
  73866. RayHelper.prototype._updateToMesh = function () {
  73867. var ray = this.ray;
  73868. if (!this._attachedToMesh || !ray) {
  73869. return;
  73870. }
  73871. if (this._attachedToMesh._isDisposed) {
  73872. this.detachFromMesh();
  73873. return;
  73874. }
  73875. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  73876. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  73877. };
  73878. RayHelper.prototype.dispose = function () {
  73879. this.hide();
  73880. this.detachFromMesh();
  73881. this.ray = null;
  73882. };
  73883. return RayHelper;
  73884. }());
  73885. BABYLON.RayHelper = RayHelper;
  73886. })(BABYLON || (BABYLON = {}));
  73887. //# sourceMappingURL=babylon.rayHelper.js.map
  73888. var BABYLON;
  73889. (function (BABYLON) {
  73890. // load the inspector using require, if not present in the global namespace.
  73891. var DebugLayer = /** @class */ (function () {
  73892. function DebugLayer(scene) {
  73893. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73894. this._scene = scene;
  73895. // load inspector using require, if it doesn't exist on the global namespace.
  73896. }
  73897. /** Creates the inspector window. */
  73898. DebugLayer.prototype._createInspector = function (config) {
  73899. if (config === void 0) { config = {}; }
  73900. var popup = config.popup || false;
  73901. var initialTab = config.initialTab || 0;
  73902. var parentElement = config.parentElement || null;
  73903. if (!this._inspector) {
  73904. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73905. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  73906. } // else nothing to do,; instance is already existing
  73907. };
  73908. DebugLayer.prototype.isVisible = function () {
  73909. if (!this._inspector) {
  73910. return false;
  73911. }
  73912. return true;
  73913. };
  73914. DebugLayer.prototype.hide = function () {
  73915. if (this._inspector) {
  73916. try {
  73917. this._inspector.dispose();
  73918. }
  73919. catch (e) {
  73920. // If the inspector has been removed directly from the inspector tool
  73921. }
  73922. this._inspector = null;
  73923. }
  73924. };
  73925. DebugLayer.prototype.show = function (config) {
  73926. if (config === void 0) { config = {}; }
  73927. if (typeof this.BJSINSPECTOR == 'undefined') {
  73928. // Load inspector and add it to the DOM
  73929. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  73930. }
  73931. else {
  73932. // Otherwise creates the inspector
  73933. this._createInspector(config);
  73934. }
  73935. };
  73936. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  73937. return DebugLayer;
  73938. }());
  73939. BABYLON.DebugLayer = DebugLayer;
  73940. })(BABYLON || (BABYLON = {}));
  73941. //# sourceMappingURL=babylon.debugLayer.js.map
  73942. var BABYLON;
  73943. (function (BABYLON) {
  73944. var BoundingBoxRenderer = /** @class */ (function () {
  73945. function BoundingBoxRenderer(scene) {
  73946. this.frontColor = new BABYLON.Color3(1, 1, 1);
  73947. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  73948. this.showBackLines = true;
  73949. this.renderList = new BABYLON.SmartArray(32);
  73950. this._vertexBuffers = {};
  73951. this._scene = scene;
  73952. }
  73953. BoundingBoxRenderer.prototype._prepareRessources = function () {
  73954. if (this._colorShader) {
  73955. return;
  73956. }
  73957. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  73958. attributes: [BABYLON.VertexBuffer.PositionKind],
  73959. uniforms: ["world", "viewProjection", "color"]
  73960. });
  73961. var engine = this._scene.getEngine();
  73962. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  73963. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  73964. this._createIndexBuffer();
  73965. };
  73966. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  73967. var engine = this._scene.getEngine();
  73968. 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]);
  73969. };
  73970. BoundingBoxRenderer.prototype._rebuild = function () {
  73971. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73972. if (vb) {
  73973. vb._rebuild();
  73974. }
  73975. this._createIndexBuffer();
  73976. };
  73977. BoundingBoxRenderer.prototype.reset = function () {
  73978. this.renderList.reset();
  73979. };
  73980. BoundingBoxRenderer.prototype.render = function () {
  73981. if (this.renderList.length === 0) {
  73982. return;
  73983. }
  73984. this._prepareRessources();
  73985. if (!this._colorShader.isReady()) {
  73986. return;
  73987. }
  73988. var engine = this._scene.getEngine();
  73989. engine.setDepthWrite(false);
  73990. this._colorShader._preBind();
  73991. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  73992. var boundingBox = this.renderList.data[boundingBoxIndex];
  73993. var min = boundingBox.minimum;
  73994. var max = boundingBox.maximum;
  73995. var diff = max.subtract(min);
  73996. var median = min.add(diff.scale(0.5));
  73997. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73998. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73999. .multiply(boundingBox.getWorldMatrix());
  74000. // VBOs
  74001. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  74002. if (this.showBackLines) {
  74003. // Back
  74004. engine.setDepthFunctionToGreaterOrEqual();
  74005. this._scene.resetCachedMaterial();
  74006. this._colorShader.setColor4("color", this.backColor.toColor4());
  74007. this._colorShader.bind(worldMatrix);
  74008. // Draw order
  74009. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74010. }
  74011. // Front
  74012. engine.setDepthFunctionToLess();
  74013. this._scene.resetCachedMaterial();
  74014. this._colorShader.setColor4("color", this.frontColor.toColor4());
  74015. this._colorShader.bind(worldMatrix);
  74016. // Draw order
  74017. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74018. }
  74019. this._colorShader.unbind();
  74020. engine.setDepthFunctionToLessOrEqual();
  74021. engine.setDepthWrite(true);
  74022. };
  74023. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  74024. this._prepareRessources();
  74025. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  74026. return;
  74027. }
  74028. var engine = this._scene.getEngine();
  74029. engine.setDepthWrite(false);
  74030. engine.setColorWrite(false);
  74031. this._colorShader._preBind();
  74032. var boundingBox = mesh._boundingInfo.boundingBox;
  74033. var min = boundingBox.minimum;
  74034. var max = boundingBox.maximum;
  74035. var diff = max.subtract(min);
  74036. var median = min.add(diff.scale(0.5));
  74037. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  74038. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  74039. .multiply(boundingBox.getWorldMatrix());
  74040. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  74041. engine.setDepthFunctionToLess();
  74042. this._scene.resetCachedMaterial();
  74043. this._colorShader.bind(worldMatrix);
  74044. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  74045. this._colorShader.unbind();
  74046. engine.setDepthFunctionToLessOrEqual();
  74047. engine.setDepthWrite(true);
  74048. engine.setColorWrite(true);
  74049. };
  74050. BoundingBoxRenderer.prototype.dispose = function () {
  74051. if (!this._colorShader) {
  74052. return;
  74053. }
  74054. this.renderList.dispose();
  74055. this._colorShader.dispose();
  74056. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74057. if (buffer) {
  74058. buffer.dispose();
  74059. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74060. }
  74061. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74062. };
  74063. return BoundingBoxRenderer;
  74064. }());
  74065. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  74066. })(BABYLON || (BABYLON = {}));
  74067. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  74068. var BABYLON;
  74069. (function (BABYLON) {
  74070. var MorphTarget = /** @class */ (function () {
  74071. function MorphTarget(name, influence) {
  74072. if (influence === void 0) { influence = 0; }
  74073. this.name = name;
  74074. this.animations = new Array();
  74075. this._positions = null;
  74076. this._normals = null;
  74077. this._tangents = null;
  74078. this.onInfluenceChanged = new BABYLON.Observable();
  74079. this.influence = influence;
  74080. }
  74081. Object.defineProperty(MorphTarget.prototype, "influence", {
  74082. get: function () {
  74083. return this._influence;
  74084. },
  74085. set: function (influence) {
  74086. if (this._influence === influence) {
  74087. return;
  74088. }
  74089. var previous = this._influence;
  74090. this._influence = influence;
  74091. if (this.onInfluenceChanged.hasObservers) {
  74092. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  74093. }
  74094. },
  74095. enumerable: true,
  74096. configurable: true
  74097. });
  74098. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  74099. get: function () {
  74100. return !!this._positions;
  74101. },
  74102. enumerable: true,
  74103. configurable: true
  74104. });
  74105. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  74106. get: function () {
  74107. return !!this._normals;
  74108. },
  74109. enumerable: true,
  74110. configurable: true
  74111. });
  74112. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  74113. get: function () {
  74114. return !!this._tangents;
  74115. },
  74116. enumerable: true,
  74117. configurable: true
  74118. });
  74119. MorphTarget.prototype.setPositions = function (data) {
  74120. this._positions = data;
  74121. };
  74122. MorphTarget.prototype.getPositions = function () {
  74123. return this._positions;
  74124. };
  74125. MorphTarget.prototype.setNormals = function (data) {
  74126. this._normals = data;
  74127. };
  74128. MorphTarget.prototype.getNormals = function () {
  74129. return this._normals;
  74130. };
  74131. MorphTarget.prototype.setTangents = function (data) {
  74132. this._tangents = data;
  74133. };
  74134. MorphTarget.prototype.getTangents = function () {
  74135. return this._tangents;
  74136. };
  74137. /**
  74138. * Serializes the current target into a Serialization object.
  74139. * Returns the serialized object.
  74140. */
  74141. MorphTarget.prototype.serialize = function () {
  74142. var serializationObject = {};
  74143. serializationObject.name = this.name;
  74144. serializationObject.influence = this.influence;
  74145. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  74146. if (this.hasNormals) {
  74147. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  74148. }
  74149. if (this.hasTangents) {
  74150. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  74151. }
  74152. // Animations
  74153. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  74154. return serializationObject;
  74155. };
  74156. // Statics
  74157. MorphTarget.Parse = function (serializationObject) {
  74158. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  74159. result.setPositions(serializationObject.positions);
  74160. if (serializationObject.normals) {
  74161. result.setNormals(serializationObject.normals);
  74162. }
  74163. if (serializationObject.tangents) {
  74164. result.setTangents(serializationObject.tangents);
  74165. }
  74166. // Animations
  74167. if (serializationObject.animations) {
  74168. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  74169. var parsedAnimation = serializationObject.animations[animationIndex];
  74170. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  74171. }
  74172. }
  74173. return result;
  74174. };
  74175. MorphTarget.FromMesh = function (mesh, name, influence) {
  74176. if (!name) {
  74177. name = mesh.name;
  74178. }
  74179. var result = new MorphTarget(name, influence);
  74180. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  74181. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  74182. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  74183. }
  74184. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  74185. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  74186. }
  74187. return result;
  74188. };
  74189. return MorphTarget;
  74190. }());
  74191. BABYLON.MorphTarget = MorphTarget;
  74192. })(BABYLON || (BABYLON = {}));
  74193. //# sourceMappingURL=babylon.morphTarget.js.map
  74194. var BABYLON;
  74195. (function (BABYLON) {
  74196. var MorphTargetManager = /** @class */ (function () {
  74197. function MorphTargetManager(scene) {
  74198. if (scene === void 0) { scene = null; }
  74199. this._targets = new Array();
  74200. this._targetObservable = new Array();
  74201. this._activeTargets = new BABYLON.SmartArray(16);
  74202. this._supportsNormals = false;
  74203. this._supportsTangents = false;
  74204. this._vertexCount = 0;
  74205. this._uniqueId = 0;
  74206. this._tempInfluences = new Array();
  74207. if (!scene) {
  74208. scene = BABYLON.Engine.LastCreatedScene;
  74209. }
  74210. this._scene = scene;
  74211. if (this._scene) {
  74212. this._scene.morphTargetManagers.push(this);
  74213. this._uniqueId = this._scene.getUniqueId();
  74214. }
  74215. }
  74216. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  74217. get: function () {
  74218. return this._uniqueId;
  74219. },
  74220. enumerable: true,
  74221. configurable: true
  74222. });
  74223. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  74224. get: function () {
  74225. return this._vertexCount;
  74226. },
  74227. enumerable: true,
  74228. configurable: true
  74229. });
  74230. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  74231. get: function () {
  74232. return this._supportsNormals;
  74233. },
  74234. enumerable: true,
  74235. configurable: true
  74236. });
  74237. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  74238. get: function () {
  74239. return this._supportsTangents;
  74240. },
  74241. enumerable: true,
  74242. configurable: true
  74243. });
  74244. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  74245. get: function () {
  74246. return this._targets.length;
  74247. },
  74248. enumerable: true,
  74249. configurable: true
  74250. });
  74251. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  74252. get: function () {
  74253. return this._activeTargets.length;
  74254. },
  74255. enumerable: true,
  74256. configurable: true
  74257. });
  74258. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  74259. get: function () {
  74260. return this._influences;
  74261. },
  74262. enumerable: true,
  74263. configurable: true
  74264. });
  74265. MorphTargetManager.prototype.getActiveTarget = function (index) {
  74266. return this._activeTargets.data[index];
  74267. };
  74268. MorphTargetManager.prototype.getTarget = function (index) {
  74269. return this._targets[index];
  74270. };
  74271. MorphTargetManager.prototype.addTarget = function (target) {
  74272. var _this = this;
  74273. this._targets.push(target);
  74274. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  74275. _this._syncActiveTargets(needUpdate);
  74276. }));
  74277. this._syncActiveTargets(true);
  74278. };
  74279. MorphTargetManager.prototype.removeTarget = function (target) {
  74280. var index = this._targets.indexOf(target);
  74281. if (index >= 0) {
  74282. this._targets.splice(index, 1);
  74283. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  74284. this._syncActiveTargets(true);
  74285. }
  74286. };
  74287. /**
  74288. * Serializes the current manager into a Serialization object.
  74289. * Returns the serialized object.
  74290. */
  74291. MorphTargetManager.prototype.serialize = function () {
  74292. var serializationObject = {};
  74293. serializationObject.id = this.uniqueId;
  74294. serializationObject.targets = [];
  74295. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  74296. var target = _a[_i];
  74297. serializationObject.targets.push(target.serialize());
  74298. }
  74299. return serializationObject;
  74300. };
  74301. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  74302. var influenceCount = 0;
  74303. this._activeTargets.reset();
  74304. this._supportsNormals = true;
  74305. this._supportsTangents = true;
  74306. this._vertexCount = 0;
  74307. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  74308. var target = _a[_i];
  74309. this._activeTargets.push(target);
  74310. this._tempInfluences[influenceCount++] = target.influence;
  74311. var positions = target.getPositions();
  74312. if (positions) {
  74313. this._supportsNormals = this._supportsNormals && target.hasNormals;
  74314. this._supportsTangents = this._supportsTangents && target.hasTangents;
  74315. var vertexCount = positions.length / 3;
  74316. if (this._vertexCount === 0) {
  74317. this._vertexCount = vertexCount;
  74318. }
  74319. else if (this._vertexCount !== vertexCount) {
  74320. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  74321. return;
  74322. }
  74323. }
  74324. }
  74325. if (!this._influences || this._influences.length !== influenceCount) {
  74326. this._influences = new Float32Array(influenceCount);
  74327. }
  74328. for (var index = 0; index < influenceCount; index++) {
  74329. this._influences[index] = this._tempInfluences[index];
  74330. }
  74331. if (needUpdate && this._scene) {
  74332. // Flag meshes as dirty to resync with the active targets
  74333. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  74334. var mesh = _c[_b];
  74335. if (mesh.morphTargetManager === this) {
  74336. mesh._syncGeometryWithMorphTargetManager();
  74337. }
  74338. }
  74339. }
  74340. };
  74341. // Statics
  74342. MorphTargetManager.Parse = function (serializationObject, scene) {
  74343. var result = new MorphTargetManager(scene);
  74344. result._uniqueId = serializationObject.id;
  74345. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  74346. var targetData = _a[_i];
  74347. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  74348. }
  74349. return result;
  74350. };
  74351. return MorphTargetManager;
  74352. }());
  74353. BABYLON.MorphTargetManager = MorphTargetManager;
  74354. })(BABYLON || (BABYLON = {}));
  74355. //# sourceMappingURL=babylon.morphTargetManager.js.map
  74356. var BABYLON;
  74357. (function (BABYLON) {
  74358. var Octree = /** @class */ (function () {
  74359. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  74360. if (maxDepth === void 0) { maxDepth = 2; }
  74361. this.maxDepth = maxDepth;
  74362. this.dynamicContent = new Array();
  74363. this._maxBlockCapacity = maxBlockCapacity || 64;
  74364. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  74365. this._creationFunc = creationFunc;
  74366. }
  74367. // Methods
  74368. Octree.prototype.update = function (worldMin, worldMax, entries) {
  74369. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  74370. };
  74371. Octree.prototype.addMesh = function (entry) {
  74372. for (var index = 0; index < this.blocks.length; index++) {
  74373. var block = this.blocks[index];
  74374. block.addEntry(entry);
  74375. }
  74376. };
  74377. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  74378. this._selectionContent.reset();
  74379. for (var index = 0; index < this.blocks.length; index++) {
  74380. var block = this.blocks[index];
  74381. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  74382. }
  74383. if (allowDuplicate) {
  74384. this._selectionContent.concat(this.dynamicContent);
  74385. }
  74386. else {
  74387. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  74388. }
  74389. return this._selectionContent;
  74390. };
  74391. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  74392. this._selectionContent.reset();
  74393. for (var index = 0; index < this.blocks.length; index++) {
  74394. var block = this.blocks[index];
  74395. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  74396. }
  74397. if (allowDuplicate) {
  74398. this._selectionContent.concat(this.dynamicContent);
  74399. }
  74400. else {
  74401. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  74402. }
  74403. return this._selectionContent;
  74404. };
  74405. Octree.prototype.intersectsRay = function (ray) {
  74406. this._selectionContent.reset();
  74407. for (var index = 0; index < this.blocks.length; index++) {
  74408. var block = this.blocks[index];
  74409. block.intersectsRay(ray, this._selectionContent);
  74410. }
  74411. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  74412. return this._selectionContent;
  74413. };
  74414. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  74415. target.blocks = new Array();
  74416. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  74417. // Segmenting space
  74418. for (var x = 0; x < 2; x++) {
  74419. for (var y = 0; y < 2; y++) {
  74420. for (var z = 0; z < 2; z++) {
  74421. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  74422. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  74423. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  74424. block.addEntries(entries);
  74425. target.blocks.push(block);
  74426. }
  74427. }
  74428. }
  74429. };
  74430. Octree.CreationFuncForMeshes = function (entry, block) {
  74431. var boundingInfo = entry.getBoundingInfo();
  74432. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  74433. block.entries.push(entry);
  74434. }
  74435. };
  74436. Octree.CreationFuncForSubMeshes = function (entry, block) {
  74437. var boundingInfo = entry.getBoundingInfo();
  74438. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  74439. block.entries.push(entry);
  74440. }
  74441. };
  74442. return Octree;
  74443. }());
  74444. BABYLON.Octree = Octree;
  74445. })(BABYLON || (BABYLON = {}));
  74446. //# sourceMappingURL=babylon.octree.js.map
  74447. var BABYLON;
  74448. (function (BABYLON) {
  74449. var OctreeBlock = /** @class */ (function () {
  74450. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  74451. this.entries = new Array();
  74452. this._boundingVectors = new Array();
  74453. this._capacity = capacity;
  74454. this._depth = depth;
  74455. this._maxDepth = maxDepth;
  74456. this._creationFunc = creationFunc;
  74457. this._minPoint = minPoint;
  74458. this._maxPoint = maxPoint;
  74459. this._boundingVectors.push(minPoint.clone());
  74460. this._boundingVectors.push(maxPoint.clone());
  74461. this._boundingVectors.push(minPoint.clone());
  74462. this._boundingVectors[2].x = maxPoint.x;
  74463. this._boundingVectors.push(minPoint.clone());
  74464. this._boundingVectors[3].y = maxPoint.y;
  74465. this._boundingVectors.push(minPoint.clone());
  74466. this._boundingVectors[4].z = maxPoint.z;
  74467. this._boundingVectors.push(maxPoint.clone());
  74468. this._boundingVectors[5].z = minPoint.z;
  74469. this._boundingVectors.push(maxPoint.clone());
  74470. this._boundingVectors[6].x = minPoint.x;
  74471. this._boundingVectors.push(maxPoint.clone());
  74472. this._boundingVectors[7].y = minPoint.y;
  74473. }
  74474. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  74475. // Property
  74476. get: function () {
  74477. return this._capacity;
  74478. },
  74479. enumerable: true,
  74480. configurable: true
  74481. });
  74482. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  74483. get: function () {
  74484. return this._minPoint;
  74485. },
  74486. enumerable: true,
  74487. configurable: true
  74488. });
  74489. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  74490. get: function () {
  74491. return this._maxPoint;
  74492. },
  74493. enumerable: true,
  74494. configurable: true
  74495. });
  74496. // Methods
  74497. OctreeBlock.prototype.addEntry = function (entry) {
  74498. if (this.blocks) {
  74499. for (var index = 0; index < this.blocks.length; index++) {
  74500. var block = this.blocks[index];
  74501. block.addEntry(entry);
  74502. }
  74503. return;
  74504. }
  74505. this._creationFunc(entry, this);
  74506. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  74507. this.createInnerBlocks();
  74508. }
  74509. };
  74510. OctreeBlock.prototype.addEntries = function (entries) {
  74511. for (var index = 0; index < entries.length; index++) {
  74512. var mesh = entries[index];
  74513. this.addEntry(mesh);
  74514. }
  74515. };
  74516. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  74517. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  74518. if (this.blocks) {
  74519. for (var index = 0; index < this.blocks.length; index++) {
  74520. var block = this.blocks[index];
  74521. block.select(frustumPlanes, selection, allowDuplicate);
  74522. }
  74523. return;
  74524. }
  74525. if (allowDuplicate) {
  74526. selection.concat(this.entries);
  74527. }
  74528. else {
  74529. selection.concatWithNoDuplicate(this.entries);
  74530. }
  74531. }
  74532. };
  74533. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  74534. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  74535. if (this.blocks) {
  74536. for (var index = 0; index < this.blocks.length; index++) {
  74537. var block = this.blocks[index];
  74538. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  74539. }
  74540. return;
  74541. }
  74542. if (allowDuplicate) {
  74543. selection.concat(this.entries);
  74544. }
  74545. else {
  74546. selection.concatWithNoDuplicate(this.entries);
  74547. }
  74548. }
  74549. };
  74550. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  74551. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  74552. if (this.blocks) {
  74553. for (var index = 0; index < this.blocks.length; index++) {
  74554. var block = this.blocks[index];
  74555. block.intersectsRay(ray, selection);
  74556. }
  74557. return;
  74558. }
  74559. selection.concatWithNoDuplicate(this.entries);
  74560. }
  74561. };
  74562. OctreeBlock.prototype.createInnerBlocks = function () {
  74563. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  74564. };
  74565. return OctreeBlock;
  74566. }());
  74567. BABYLON.OctreeBlock = OctreeBlock;
  74568. })(BABYLON || (BABYLON = {}));
  74569. //# sourceMappingURL=babylon.octreeBlock.js.map
  74570. var BABYLON;
  74571. (function (BABYLON) {
  74572. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  74573. __extends(VRDistortionCorrectionPostProcess, _super);
  74574. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  74575. var _this = _super.call(this, name, "vrDistortionCorrection", [
  74576. 'LensCenter',
  74577. 'Scale',
  74578. 'ScaleIn',
  74579. 'HmdWarpParam'
  74580. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  74581. _this._isRightEye = isRightEye;
  74582. _this._distortionFactors = vrMetrics.distortionK;
  74583. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  74584. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  74585. _this.adaptScaleToCurrentViewport = true;
  74586. _this.onSizeChangedObservable.add(function () {
  74587. _this.aspectRatio = _this.width * .5 / _this.height;
  74588. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  74589. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  74590. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  74591. });
  74592. _this.onApplyObservable.add(function (effect) {
  74593. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  74594. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  74595. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  74596. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  74597. });
  74598. return _this;
  74599. }
  74600. return VRDistortionCorrectionPostProcess;
  74601. }(BABYLON.PostProcess));
  74602. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  74603. })(BABYLON || (BABYLON = {}));
  74604. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  74605. var BABYLON;
  74606. (function (BABYLON) {
  74607. var AnaglyphPostProcess = /** @class */ (function (_super) {
  74608. __extends(AnaglyphPostProcess, _super);
  74609. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  74610. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  74611. _this._passedProcess = rigCameras[0]._rigPostProcess;
  74612. _this.onApplyObservable.add(function (effect) {
  74613. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  74614. });
  74615. return _this;
  74616. }
  74617. return AnaglyphPostProcess;
  74618. }(BABYLON.PostProcess));
  74619. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  74620. })(BABYLON || (BABYLON = {}));
  74621. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  74622. var BABYLON;
  74623. (function (BABYLON) {
  74624. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  74625. __extends(StereoscopicInterlacePostProcess, _super);
  74626. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  74627. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  74628. _this._passedProcess = rigCameras[0]._rigPostProcess;
  74629. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  74630. _this.onSizeChangedObservable.add(function () {
  74631. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  74632. });
  74633. _this.onApplyObservable.add(function (effect) {
  74634. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  74635. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  74636. });
  74637. return _this;
  74638. }
  74639. return StereoscopicInterlacePostProcess;
  74640. }(BABYLON.PostProcess));
  74641. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  74642. })(BABYLON || (BABYLON = {}));
  74643. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  74644. var BABYLON;
  74645. (function (BABYLON) {
  74646. /**
  74647. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  74648. * Screen rotation is taken into account.
  74649. */
  74650. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  74651. function FreeCameraDeviceOrientationInput() {
  74652. var _this = this;
  74653. this._screenOrientationAngle = 0;
  74654. this._screenQuaternion = new BABYLON.Quaternion();
  74655. this._alpha = 0;
  74656. this._beta = 0;
  74657. this._gamma = 0;
  74658. this._orientationChanged = function () {
  74659. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  74660. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  74661. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  74662. };
  74663. this._deviceOrientation = function (evt) {
  74664. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  74665. _this._beta = evt.beta !== null ? evt.beta : 0;
  74666. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  74667. };
  74668. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  74669. this._orientationChanged();
  74670. }
  74671. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  74672. get: function () {
  74673. return this._camera;
  74674. },
  74675. set: function (camera) {
  74676. this._camera = camera;
  74677. if (this._camera != null && !this._camera.rotationQuaternion) {
  74678. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  74679. }
  74680. },
  74681. enumerable: true,
  74682. configurable: true
  74683. });
  74684. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  74685. window.addEventListener("orientationchange", this._orientationChanged);
  74686. window.addEventListener("deviceorientation", this._deviceOrientation);
  74687. //In certain cases, the attach control is called AFTER orientation was changed,
  74688. //So this is needed.
  74689. this._orientationChanged();
  74690. };
  74691. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  74692. window.removeEventListener("orientationchange", this._orientationChanged);
  74693. window.removeEventListener("deviceorientation", this._deviceOrientation);
  74694. };
  74695. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  74696. //if no device orientation provided, don't update the rotation.
  74697. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  74698. if (!this._alpha)
  74699. return;
  74700. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  74701. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  74702. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  74703. //Mirror on XY Plane
  74704. this._camera.rotationQuaternion.z *= -1;
  74705. this._camera.rotationQuaternion.w *= -1;
  74706. };
  74707. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  74708. return "FreeCameraDeviceOrientationInput";
  74709. };
  74710. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  74711. return "deviceOrientation";
  74712. };
  74713. return FreeCameraDeviceOrientationInput;
  74714. }());
  74715. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  74716. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  74717. })(BABYLON || (BABYLON = {}));
  74718. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  74719. var BABYLON;
  74720. (function (BABYLON) {
  74721. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  74722. function ArcRotateCameraVRDeviceOrientationInput() {
  74723. this.alphaCorrection = 1;
  74724. this.betaCorrection = 1;
  74725. this.gammaCorrection = 1;
  74726. this._alpha = 0;
  74727. this._gamma = 0;
  74728. this._dirty = false;
  74729. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  74730. }
  74731. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  74732. this.camera.attachControl(element, noPreventDefault);
  74733. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  74734. };
  74735. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  74736. if (evt.alpha !== null) {
  74737. this._alpha = +evt.alpha | 0;
  74738. }
  74739. if (evt.gamma !== null) {
  74740. this._gamma = +evt.gamma | 0;
  74741. }
  74742. this._dirty = true;
  74743. };
  74744. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  74745. if (this._dirty) {
  74746. this._dirty = false;
  74747. if (this._gamma < 0) {
  74748. this._gamma = 180 + this._gamma;
  74749. }
  74750. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  74751. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  74752. }
  74753. };
  74754. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  74755. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  74756. };
  74757. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  74758. return "ArcRotateCameraVRDeviceOrientationInput";
  74759. };
  74760. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  74761. return "VRDeviceOrientation";
  74762. };
  74763. return ArcRotateCameraVRDeviceOrientationInput;
  74764. }());
  74765. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  74766. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  74767. })(BABYLON || (BABYLON = {}));
  74768. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  74769. var BABYLON;
  74770. (function (BABYLON) {
  74771. var VRCameraMetrics = /** @class */ (function () {
  74772. function VRCameraMetrics() {
  74773. this.compensateDistortion = true;
  74774. }
  74775. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  74776. get: function () {
  74777. return this.hResolution / (2 * this.vResolution);
  74778. },
  74779. enumerable: true,
  74780. configurable: true
  74781. });
  74782. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  74783. get: function () {
  74784. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  74785. },
  74786. enumerable: true,
  74787. configurable: true
  74788. });
  74789. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  74790. get: function () {
  74791. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74792. var h = (4 * meters) / this.hScreenSize;
  74793. return BABYLON.Matrix.Translation(h, 0, 0);
  74794. },
  74795. enumerable: true,
  74796. configurable: true
  74797. });
  74798. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  74799. get: function () {
  74800. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74801. var h = (4 * meters) / this.hScreenSize;
  74802. return BABYLON.Matrix.Translation(-h, 0, 0);
  74803. },
  74804. enumerable: true,
  74805. configurable: true
  74806. });
  74807. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  74808. get: function () {
  74809. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  74810. },
  74811. enumerable: true,
  74812. configurable: true
  74813. });
  74814. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  74815. get: function () {
  74816. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  74817. },
  74818. enumerable: true,
  74819. configurable: true
  74820. });
  74821. VRCameraMetrics.GetDefault = function () {
  74822. var result = new VRCameraMetrics();
  74823. result.hResolution = 1280;
  74824. result.vResolution = 800;
  74825. result.hScreenSize = 0.149759993;
  74826. result.vScreenSize = 0.0935999975;
  74827. result.vScreenCenter = 0.0467999987;
  74828. result.eyeToScreenDistance = 0.0410000011;
  74829. result.lensSeparationDistance = 0.0635000020;
  74830. result.interpupillaryDistance = 0.0640000030;
  74831. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  74832. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  74833. result.postProcessScaleFactor = 1.714605507808412;
  74834. result.lensCenterOffset = 0.151976421;
  74835. return result;
  74836. };
  74837. return VRCameraMetrics;
  74838. }());
  74839. BABYLON.VRCameraMetrics = VRCameraMetrics;
  74840. })(BABYLON || (BABYLON = {}));
  74841. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  74842. var BABYLON;
  74843. (function (BABYLON) {
  74844. /**
  74845. * This represents a WebVR camera.
  74846. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  74847. * @example http://doc.babylonjs.com/how_to/webvr_camera
  74848. */
  74849. var WebVRFreeCamera = /** @class */ (function (_super) {
  74850. __extends(WebVRFreeCamera, _super);
  74851. /**
  74852. * Instantiates a WebVRFreeCamera.
  74853. * @param name The name of the WebVRFreeCamera
  74854. * @param position The starting anchor position for the camera
  74855. * @param scene The scene the camera belongs to
  74856. * @param webVROptions a set of customizable options for the webVRCamera
  74857. */
  74858. function WebVRFreeCamera(name, position, scene, webVROptions) {
  74859. if (webVROptions === void 0) { webVROptions = {}; }
  74860. var _this = _super.call(this, name, position, scene) || this;
  74861. _this.webVROptions = webVROptions;
  74862. /**
  74863. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  74864. */
  74865. _this._vrDevice = null;
  74866. /**
  74867. * The rawPose of the vrDevice.
  74868. */
  74869. _this.rawPose = null;
  74870. _this._specsVersion = "1.1";
  74871. _this._attached = false;
  74872. _this._descendants = [];
  74873. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74874. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74875. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  74876. _this._standingMatrix = null;
  74877. /**
  74878. * Represents device position in babylon space.
  74879. */
  74880. _this.devicePosition = BABYLON.Vector3.Zero();
  74881. /**
  74882. * Represents device rotation in babylon space.
  74883. */
  74884. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  74885. /**
  74886. * The scale of the device to be used when translating from device space to babylon space.
  74887. */
  74888. _this.deviceScaleFactor = 1;
  74889. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74890. _this._worldToDevice = BABYLON.Matrix.Identity();
  74891. /**
  74892. * References to the webVR controllers for the vrDevice.
  74893. */
  74894. _this.controllers = [];
  74895. /**
  74896. * Emits an event when a controller is attached.
  74897. */
  74898. _this.onControllersAttachedObservable = new BABYLON.Observable();
  74899. /**
  74900. * Emits an event when a controller's mesh has been loaded;
  74901. */
  74902. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  74903. /**
  74904. * If the rig cameras be used as parent instead of this camera.
  74905. */
  74906. _this.rigParenting = true;
  74907. _this._defaultHeight = undefined;
  74908. _this._workingVector = BABYLON.Vector3.Zero();
  74909. _this._oneVector = BABYLON.Vector3.One();
  74910. _this._workingMatrix = BABYLON.Matrix.Identity();
  74911. _this._cache.position = BABYLON.Vector3.Zero();
  74912. if (webVROptions.defaultHeight) {
  74913. _this._defaultHeight = webVROptions.defaultHeight;
  74914. _this.position.y = _this._defaultHeight;
  74915. }
  74916. _this.minZ = 0.1;
  74917. //legacy support - the compensation boolean was removed.
  74918. if (arguments.length === 5) {
  74919. _this.webVROptions = arguments[4];
  74920. }
  74921. // default webVR options
  74922. if (_this.webVROptions.trackPosition == undefined) {
  74923. _this.webVROptions.trackPosition = true;
  74924. }
  74925. if (_this.webVROptions.controllerMeshes == undefined) {
  74926. _this.webVROptions.controllerMeshes = true;
  74927. }
  74928. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  74929. _this.webVROptions.defaultLightingOnControllers = true;
  74930. }
  74931. _this.rotationQuaternion = new BABYLON.Quaternion();
  74932. if (_this.webVROptions && _this.webVROptions.positionScale) {
  74933. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  74934. }
  74935. //enable VR
  74936. var engine = _this.getEngine();
  74937. _this._onVREnabled = function (success) { if (success) {
  74938. _this.initControllers();
  74939. } };
  74940. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  74941. engine.initWebVR().add(function (event) {
  74942. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  74943. return;
  74944. }
  74945. _this._vrDevice = event.vrDisplay;
  74946. //reset the rig parameters.
  74947. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  74948. if (_this._attached) {
  74949. _this.getEngine().enableVR();
  74950. }
  74951. });
  74952. if (typeof (VRFrameData) !== "undefined")
  74953. _this._frameData = new VRFrameData();
  74954. /**
  74955. * The idea behind the following lines:
  74956. * objects that have the camera as parent should actually have the rig cameras as a parent.
  74957. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  74958. * the second will not show it correctly.
  74959. *
  74960. * To solve this - each object that has the camera as parent will be added to a protected array.
  74961. * When the rig camera renders, it will take this array and set all of those to be its children.
  74962. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  74963. * Amazing!
  74964. */
  74965. scene.onBeforeCameraRenderObservable.add(function (camera) {
  74966. if (camera.parent === _this && _this.rigParenting) {
  74967. _this._descendants = _this.getDescendants(true, function (n) {
  74968. // don't take the cameras or the controllers!
  74969. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  74970. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  74971. return !isController && !isRigCamera;
  74972. });
  74973. _this._descendants.forEach(function (node) {
  74974. node.parent = camera;
  74975. });
  74976. }
  74977. });
  74978. scene.onAfterCameraRenderObservable.add(function (camera) {
  74979. if (camera.parent === _this && _this.rigParenting) {
  74980. _this._descendants.forEach(function (node) {
  74981. node.parent = _this;
  74982. });
  74983. }
  74984. });
  74985. return _this;
  74986. }
  74987. /**
  74988. * Gets the device distance from the ground.
  74989. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  74990. */
  74991. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  74992. if (this._standingMatrix && this._defaultHeight === undefined) {
  74993. // Add standing matrix offset to get real offset from ground in room
  74994. this._standingMatrix.getTranslationToRef(this._workingVector);
  74995. return this._deviceRoomPosition.y + this._workingVector.y;
  74996. }
  74997. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  74998. return this._defaultHeight || 0;
  74999. };
  75000. /**
  75001. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  75002. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  75003. */
  75004. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  75005. var _this = this;
  75006. if (callback === void 0) { callback = function (bool) { }; }
  75007. // Use standing matrix if available
  75008. if (!navigator || !navigator.getVRDisplays) {
  75009. callback(false);
  75010. }
  75011. else {
  75012. navigator.getVRDisplays().then(function (displays) {
  75013. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  75014. callback(false);
  75015. }
  75016. else {
  75017. _this._standingMatrix = new BABYLON.Matrix();
  75018. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  75019. if (!_this.getScene().useRightHandedSystem) {
  75020. [2, 6, 8, 9, 14].forEach(function (num) {
  75021. if (_this._standingMatrix) {
  75022. _this._standingMatrix.m[num] *= -1;
  75023. }
  75024. });
  75025. }
  75026. callback(true);
  75027. }
  75028. });
  75029. }
  75030. };
  75031. /**
  75032. * Disposes the camera
  75033. */
  75034. WebVRFreeCamera.prototype.dispose = function () {
  75035. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  75036. _super.prototype.dispose.call(this);
  75037. };
  75038. /**
  75039. * Gets a vrController by name.
  75040. * @param name The name of the controller to retreive
  75041. * @returns the controller matching the name specified or null if not found
  75042. */
  75043. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  75044. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  75045. var gp = _a[_i];
  75046. if (gp.hand === name) {
  75047. return gp;
  75048. }
  75049. }
  75050. return null;
  75051. };
  75052. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  75053. /**
  75054. * The controller corrisponding to the users left hand.
  75055. */
  75056. get: function () {
  75057. if (!this._leftController) {
  75058. this._leftController = this.getControllerByName("left");
  75059. }
  75060. return this._leftController;
  75061. },
  75062. enumerable: true,
  75063. configurable: true
  75064. });
  75065. ;
  75066. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  75067. /**
  75068. * The controller corrisponding to the users right hand.
  75069. */
  75070. get: function () {
  75071. if (!this._rightController) {
  75072. this._rightController = this.getControllerByName("right");
  75073. }
  75074. return this._rightController;
  75075. },
  75076. enumerable: true,
  75077. configurable: true
  75078. });
  75079. ;
  75080. /**
  75081. * Casts a ray forward from the vrCamera's gaze.
  75082. * @param length Length of the ray (default: 100)
  75083. * @returns the ray corrisponding to the gaze
  75084. */
  75085. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  75086. if (length === void 0) { length = 100; }
  75087. if (this.leftCamera) {
  75088. // Use left eye to avoid computation to compute center on every call
  75089. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  75090. }
  75091. else {
  75092. return _super.prototype.getForwardRay.call(this, length);
  75093. }
  75094. };
  75095. /**
  75096. * Updates the camera based on device's frame data
  75097. */
  75098. WebVRFreeCamera.prototype._checkInputs = function () {
  75099. if (this._vrDevice && this._vrDevice.isPresenting) {
  75100. this._vrDevice.getFrameData(this._frameData);
  75101. this.updateFromDevice(this._frameData.pose);
  75102. }
  75103. _super.prototype._checkInputs.call(this);
  75104. };
  75105. /**
  75106. * Updates the poseControlled values based on the input device pose.
  75107. * @param poseData Pose coming from the device
  75108. */
  75109. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  75110. if (poseData && poseData.orientation) {
  75111. this.rawPose = poseData;
  75112. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  75113. if (this.getScene().useRightHandedSystem) {
  75114. this._deviceRoomRotationQuaternion.z *= -1;
  75115. this._deviceRoomRotationQuaternion.w *= -1;
  75116. }
  75117. if (this.webVROptions.trackPosition && this.rawPose.position) {
  75118. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  75119. if (this.getScene().useRightHandedSystem) {
  75120. this._deviceRoomPosition.z *= -1;
  75121. }
  75122. }
  75123. }
  75124. };
  75125. /**
  75126. * WebVR's attach control will start broadcasting frames to the device.
  75127. * Note that in certain browsers (chrome for example) this function must be called
  75128. * within a user-interaction callback. Example:
  75129. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  75130. *
  75131. * @param element html element to attach the vrDevice to
  75132. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  75133. */
  75134. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  75135. _super.prototype.attachControl.call(this, element, noPreventDefault);
  75136. this._attached = true;
  75137. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  75138. if (this._vrDevice) {
  75139. this.getEngine().enableVR();
  75140. }
  75141. };
  75142. /**
  75143. * Detaches the camera from the html element and disables VR
  75144. *
  75145. * @param element html element to detach from
  75146. */
  75147. WebVRFreeCamera.prototype.detachControl = function (element) {
  75148. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  75149. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  75150. _super.prototype.detachControl.call(this, element);
  75151. this._attached = false;
  75152. this.getEngine().disableVR();
  75153. };
  75154. /**
  75155. * @returns the name of this class
  75156. */
  75157. WebVRFreeCamera.prototype.getClassName = function () {
  75158. return "WebVRFreeCamera";
  75159. };
  75160. /**
  75161. * Calls resetPose on the vrDisplay
  75162. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  75163. */
  75164. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  75165. //uses the vrDisplay's "resetPose()".
  75166. //pitch and roll won't be affected.
  75167. this._vrDevice.resetPose();
  75168. };
  75169. /**
  75170. * Updates the rig cameras (left and right eye)
  75171. */
  75172. WebVRFreeCamera.prototype._updateRigCameras = function () {
  75173. var camLeft = this._rigCameras[0];
  75174. var camRight = this._rigCameras[1];
  75175. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  75176. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  75177. camLeft.position.copyFrom(this._deviceRoomPosition);
  75178. camRight.position.copyFrom(this._deviceRoomPosition);
  75179. };
  75180. /**
  75181. * Updates the cached values of the camera
  75182. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  75183. */
  75184. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  75185. var _this = this;
  75186. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  75187. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  75188. if (!this.updateCacheCalled) {
  75189. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  75190. this.updateCacheCalled = true;
  75191. this.update();
  75192. }
  75193. // Set working vector to the device position in room space rotated by the new rotation
  75194. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  75195. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  75196. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  75197. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  75198. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  75199. // Add translation from anchor position
  75200. this._deviceToWorld.getTranslationToRef(this._workingVector);
  75201. this._workingVector.addInPlace(this.position);
  75202. this._workingVector.subtractInPlace(this._cache.position);
  75203. this._deviceToWorld.setTranslation(this._workingVector);
  75204. // Set an inverted matrix to be used when updating the camera
  75205. this._deviceToWorld.invertToRef(this._worldToDevice);
  75206. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  75207. this.controllers.forEach(function (controller) {
  75208. controller._deviceToWorld = _this._deviceToWorld;
  75209. controller.update();
  75210. });
  75211. }
  75212. if (!ignoreParentClass) {
  75213. _super.prototype._updateCache.call(this);
  75214. }
  75215. this.updateCacheCalled = false;
  75216. };
  75217. /**
  75218. * Updates the current device position and rotation in the babylon world
  75219. */
  75220. WebVRFreeCamera.prototype.update = function () {
  75221. // Get current device position in babylon world
  75222. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  75223. // Get current device rotation in babylon world
  75224. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  75225. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  75226. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  75227. _super.prototype.update.call(this);
  75228. };
  75229. /**
  75230. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  75231. * @returns an identity matrix
  75232. */
  75233. WebVRFreeCamera.prototype._getViewMatrix = function () {
  75234. return BABYLON.Matrix.Identity();
  75235. };
  75236. /**
  75237. * This function is called by the two RIG cameras.
  75238. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  75239. */
  75240. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  75241. var _this = this;
  75242. //WebVR 1.1
  75243. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  75244. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  75245. if (!this.getScene().useRightHandedSystem) {
  75246. [2, 6, 8, 9, 14].forEach(function (num) {
  75247. _this._webvrViewMatrix.m[num] *= -1;
  75248. });
  75249. }
  75250. // update the camera rotation matrix
  75251. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  75252. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  75253. // Computing target and final matrix
  75254. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  75255. var parentCamera = this._cameraRigParams["parentCamera"];
  75256. // should the view matrix be updated with scale and position offset?
  75257. if (parentCamera.deviceScaleFactor !== 1) {
  75258. this._webvrViewMatrix.invert();
  75259. // scale the position, if set
  75260. if (parentCamera.deviceScaleFactor) {
  75261. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  75262. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  75263. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  75264. }
  75265. this._webvrViewMatrix.invert();
  75266. }
  75267. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  75268. return this._webvrViewMatrix;
  75269. };
  75270. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  75271. var _this = this;
  75272. var parentCamera = this.parent;
  75273. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  75274. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  75275. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  75276. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  75277. //babylon compatible matrix
  75278. if (!this.getScene().useRightHandedSystem) {
  75279. [8, 9, 10, 11].forEach(function (num) {
  75280. _this._projectionMatrix.m[num] *= -1;
  75281. });
  75282. }
  75283. return this._projectionMatrix;
  75284. };
  75285. /**
  75286. * Initializes the controllers and their meshes
  75287. */
  75288. WebVRFreeCamera.prototype.initControllers = function () {
  75289. var _this = this;
  75290. this.controllers = [];
  75291. var manager = this.getScene().gamepadManager;
  75292. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  75293. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  75294. var webVrController = gamepad;
  75295. if (webVrController.defaultModel) {
  75296. webVrController.defaultModel.setEnabled(false);
  75297. }
  75298. if (webVrController.hand === "right") {
  75299. _this._rightController = null;
  75300. }
  75301. if (webVrController.hand === "left") {
  75302. _this._rightController = null;
  75303. }
  75304. var controllerIndex = _this.controllers.indexOf(webVrController);
  75305. if (controllerIndex !== -1) {
  75306. _this.controllers.splice(controllerIndex, 1);
  75307. }
  75308. }
  75309. });
  75310. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  75311. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  75312. var webVrController_1 = gamepad;
  75313. webVrController_1._deviceToWorld = _this._deviceToWorld;
  75314. if (_this.webVROptions.controllerMeshes) {
  75315. if (webVrController_1.defaultModel) {
  75316. webVrController_1.defaultModel.setEnabled(true);
  75317. }
  75318. else {
  75319. // Load the meshes
  75320. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  75321. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  75322. if (_this.webVROptions.defaultLightingOnControllers) {
  75323. if (!_this._lightOnControllers) {
  75324. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  75325. }
  75326. var activateLightOnSubMeshes_1 = function (mesh, light) {
  75327. var children = mesh.getChildren();
  75328. if (children.length !== 0) {
  75329. children.forEach(function (mesh) {
  75330. light.includedOnlyMeshes.push(mesh);
  75331. activateLightOnSubMeshes_1(mesh, light);
  75332. });
  75333. }
  75334. };
  75335. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  75336. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  75337. }
  75338. });
  75339. }
  75340. }
  75341. webVrController_1.attachToPoseControlledCamera(_this);
  75342. // since this is async - sanity check. Is the controller already stored?
  75343. if (_this.controllers.indexOf(webVrController_1) === -1) {
  75344. //add to the controllers array
  75345. _this.controllers.push(webVrController_1);
  75346. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  75347. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  75348. // So we're overriding setting left & right manually to be sure
  75349. var firstViveWandDetected = false;
  75350. for (var i = 0; i < _this.controllers.length; i++) {
  75351. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  75352. if (!firstViveWandDetected) {
  75353. firstViveWandDetected = true;
  75354. _this.controllers[i].hand = "left";
  75355. }
  75356. else {
  75357. _this.controllers[i].hand = "right";
  75358. }
  75359. }
  75360. }
  75361. //did we find enough controllers? Great! let the developer know.
  75362. if (_this.controllers.length >= 2) {
  75363. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  75364. }
  75365. }
  75366. }
  75367. });
  75368. };
  75369. return WebVRFreeCamera;
  75370. }(BABYLON.FreeCamera));
  75371. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  75372. })(BABYLON || (BABYLON = {}));
  75373. //# sourceMappingURL=babylon.webVRCamera.js.map
  75374. var BABYLON;
  75375. (function (BABYLON) {
  75376. // We're mainly based on the logic defined into the FreeCamera code
  75377. /**
  75378. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  75379. * being tilted forward or back and left or right.
  75380. */
  75381. var DeviceOrientationCamera = /** @class */ (function (_super) {
  75382. __extends(DeviceOrientationCamera, _super);
  75383. /**
  75384. * Creates a new device orientation camera. @see DeviceOrientationCamera
  75385. * @param name The name of the camera
  75386. * @param position The start position camera
  75387. * @param scene The scene the camera belongs to
  75388. */
  75389. function DeviceOrientationCamera(name, position, scene) {
  75390. var _this = _super.call(this, name, position, scene) || this;
  75391. _this._quaternionCache = new BABYLON.Quaternion();
  75392. _this.inputs.addDeviceOrientation();
  75393. return _this;
  75394. }
  75395. /**
  75396. * Gets the current instance class name ("DeviceOrientationCamera").
  75397. * This helps avoiding instanceof at run time.
  75398. * @returns the class name
  75399. */
  75400. DeviceOrientationCamera.prototype.getClassName = function () {
  75401. return "DeviceOrientationCamera";
  75402. };
  75403. /**
  75404. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  75405. */
  75406. DeviceOrientationCamera.prototype._checkInputs = function () {
  75407. _super.prototype._checkInputs.call(this);
  75408. this._quaternionCache.copyFrom(this.rotationQuaternion);
  75409. if (this._initialQuaternion) {
  75410. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  75411. }
  75412. };
  75413. /**
  75414. * Reset the camera to its default orientation on the specified axis only.
  75415. * @param axis The axis to reset
  75416. */
  75417. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  75418. var _this = this;
  75419. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  75420. //can only work if this camera has a rotation quaternion already.
  75421. if (!this.rotationQuaternion)
  75422. return;
  75423. if (!this._initialQuaternion) {
  75424. this._initialQuaternion = new BABYLON.Quaternion();
  75425. }
  75426. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  75427. ['x', 'y', 'z'].forEach(function (axisName) {
  75428. if (!axis[axisName]) {
  75429. _this._initialQuaternion[axisName] = 0;
  75430. }
  75431. else {
  75432. _this._initialQuaternion[axisName] *= -1;
  75433. }
  75434. });
  75435. this._initialQuaternion.normalize();
  75436. //force rotation update
  75437. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  75438. };
  75439. return DeviceOrientationCamera;
  75440. }(BABYLON.FreeCamera));
  75441. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  75442. })(BABYLON || (BABYLON = {}));
  75443. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  75444. var BABYLON;
  75445. (function (BABYLON) {
  75446. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  75447. __extends(VRDeviceOrientationFreeCamera, _super);
  75448. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  75449. if (compensateDistortion === void 0) { compensateDistortion = true; }
  75450. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  75451. var _this = _super.call(this, name, position, scene) || this;
  75452. vrCameraMetrics.compensateDistortion = compensateDistortion;
  75453. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  75454. return _this;
  75455. }
  75456. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  75457. return "VRDeviceOrientationFreeCamera";
  75458. };
  75459. return VRDeviceOrientationFreeCamera;
  75460. }(BABYLON.DeviceOrientationCamera));
  75461. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  75462. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  75463. __extends(VRDeviceOrientationGamepadCamera, _super);
  75464. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  75465. if (compensateDistortion === void 0) { compensateDistortion = true; }
  75466. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  75467. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  75468. _this.inputs.addGamepad();
  75469. return _this;
  75470. }
  75471. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  75472. return "VRDeviceOrientationGamepadCamera";
  75473. };
  75474. return VRDeviceOrientationGamepadCamera;
  75475. }(VRDeviceOrientationFreeCamera));
  75476. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  75477. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  75478. __extends(VRDeviceOrientationArcRotateCamera, _super);
  75479. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  75480. if (compensateDistortion === void 0) { compensateDistortion = true; }
  75481. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  75482. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  75483. vrCameraMetrics.compensateDistortion = compensateDistortion;
  75484. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  75485. _this.inputs.addVRDeviceOrientation();
  75486. return _this;
  75487. }
  75488. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  75489. return "VRDeviceOrientationArcRotateCamera";
  75490. };
  75491. return VRDeviceOrientationArcRotateCamera;
  75492. }(BABYLON.ArcRotateCamera));
  75493. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  75494. })(BABYLON || (BABYLON = {}));
  75495. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  75496. var BABYLON;
  75497. (function (BABYLON) {
  75498. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  75499. __extends(AnaglyphFreeCamera, _super);
  75500. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  75501. var _this = _super.call(this, name, position, scene) || this;
  75502. _this.interaxialDistance = interaxialDistance;
  75503. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75504. return _this;
  75505. }
  75506. AnaglyphFreeCamera.prototype.getClassName = function () {
  75507. return "AnaglyphFreeCamera";
  75508. };
  75509. return AnaglyphFreeCamera;
  75510. }(BABYLON.FreeCamera));
  75511. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  75512. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  75513. __extends(AnaglyphArcRotateCamera, _super);
  75514. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  75515. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  75516. _this.interaxialDistance = interaxialDistance;
  75517. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75518. return _this;
  75519. }
  75520. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  75521. return "AnaglyphArcRotateCamera";
  75522. };
  75523. return AnaglyphArcRotateCamera;
  75524. }(BABYLON.ArcRotateCamera));
  75525. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  75526. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  75527. __extends(AnaglyphGamepadCamera, _super);
  75528. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  75529. var _this = _super.call(this, name, position, scene) || this;
  75530. _this.interaxialDistance = interaxialDistance;
  75531. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75532. return _this;
  75533. }
  75534. AnaglyphGamepadCamera.prototype.getClassName = function () {
  75535. return "AnaglyphGamepadCamera";
  75536. };
  75537. return AnaglyphGamepadCamera;
  75538. }(BABYLON.GamepadCamera));
  75539. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  75540. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  75541. __extends(AnaglyphUniversalCamera, _super);
  75542. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  75543. var _this = _super.call(this, name, position, scene) || this;
  75544. _this.interaxialDistance = interaxialDistance;
  75545. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75546. return _this;
  75547. }
  75548. AnaglyphUniversalCamera.prototype.getClassName = function () {
  75549. return "AnaglyphUniversalCamera";
  75550. };
  75551. return AnaglyphUniversalCamera;
  75552. }(BABYLON.UniversalCamera));
  75553. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  75554. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  75555. __extends(StereoscopicFreeCamera, _super);
  75556. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  75557. var _this = _super.call(this, name, position, scene) || this;
  75558. _this.interaxialDistance = interaxialDistance;
  75559. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75560. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75561. return _this;
  75562. }
  75563. StereoscopicFreeCamera.prototype.getClassName = function () {
  75564. return "StereoscopicFreeCamera";
  75565. };
  75566. return StereoscopicFreeCamera;
  75567. }(BABYLON.FreeCamera));
  75568. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  75569. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  75570. __extends(StereoscopicArcRotateCamera, _super);
  75571. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  75572. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  75573. _this.interaxialDistance = interaxialDistance;
  75574. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75575. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75576. return _this;
  75577. }
  75578. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  75579. return "StereoscopicArcRotateCamera";
  75580. };
  75581. return StereoscopicArcRotateCamera;
  75582. }(BABYLON.ArcRotateCamera));
  75583. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  75584. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  75585. __extends(StereoscopicGamepadCamera, _super);
  75586. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  75587. var _this = _super.call(this, name, position, scene) || this;
  75588. _this.interaxialDistance = interaxialDistance;
  75589. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75590. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75591. return _this;
  75592. }
  75593. StereoscopicGamepadCamera.prototype.getClassName = function () {
  75594. return "StereoscopicGamepadCamera";
  75595. };
  75596. return StereoscopicGamepadCamera;
  75597. }(BABYLON.GamepadCamera));
  75598. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  75599. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  75600. __extends(StereoscopicUniversalCamera, _super);
  75601. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  75602. var _this = _super.call(this, name, position, scene) || this;
  75603. _this.interaxialDistance = interaxialDistance;
  75604. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75605. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75606. return _this;
  75607. }
  75608. StereoscopicUniversalCamera.prototype.getClassName = function () {
  75609. return "StereoscopicUniversalCamera";
  75610. };
  75611. return StereoscopicUniversalCamera;
  75612. }(BABYLON.UniversalCamera));
  75613. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  75614. })(BABYLON || (BABYLON = {}));
  75615. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  75616. var BABYLON;
  75617. (function (BABYLON) {
  75618. /**
  75619. * Helps to quickly add VR support to an existing scene.
  75620. * See http://doc.babylonjs.com/how_to/webvr_helper
  75621. */
  75622. var VRExperienceHelper = /** @class */ (function () {
  75623. /**
  75624. * Instantiates a VRExperienceHelper.
  75625. * Helps to quickly add VR support to an existing scene.
  75626. * @param scene The scene the VRExperienceHelper belongs to.
  75627. * @param webVROptions Options to modify the vr experience helper's behavior.
  75628. */
  75629. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  75630. if (webVROptions === void 0) { webVROptions = {}; }
  75631. var _this = this;
  75632. this.webVROptions = webVROptions;
  75633. // Can the system support WebVR, even if a headset isn't plugged in?
  75634. this._webVRsupported = false;
  75635. // If WebVR is supported, is a headset plugged in and are we ready to present?
  75636. this._webVRready = false;
  75637. // Are we waiting for the requestPresent callback to complete?
  75638. this._webVRrequesting = false;
  75639. // Are we presenting to the headset right now?
  75640. this._webVRpresenting = false;
  75641. // Are we presenting in the fullscreen fallback?
  75642. this._fullscreenVRpresenting = false;
  75643. /**
  75644. * Observable raised when entering VR.
  75645. */
  75646. this.onEnteringVRObservable = new BABYLON.Observable();
  75647. /**
  75648. * Observable raised when exiting VR.
  75649. */
  75650. this.onExitingVRObservable = new BABYLON.Observable();
  75651. /**
  75652. * Observable raised when controller mesh is loaded.
  75653. */
  75654. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  75655. this._useCustomVRButton = false;
  75656. this._teleportationRequested = false;
  75657. this._teleportationEnabledOnLeftController = false;
  75658. this._teleportationEnabledOnRightController = false;
  75659. this._interactionsEnabledOnLeftController = false;
  75660. this._interactionsEnabledOnRightController = false;
  75661. this._leftControllerReady = false;
  75662. this._rightControllerReady = false;
  75663. this._floorMeshesCollection = [];
  75664. this._teleportationAllowed = false;
  75665. this._rotationAllowed = true;
  75666. this._teleportationRequestInitiated = false;
  75667. this._teleportationBackRequestInitiated = false;
  75668. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  75669. this._rotationRightAsked = false;
  75670. this._rotationLeftAsked = false;
  75671. this._isDefaultTeleportationTarget = true;
  75672. this._teleportationFillColor = "#444444";
  75673. this._teleportationBorderColor = "#FFFFFF";
  75674. this._rotationAngle = 0;
  75675. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  75676. this._padSensibilityUp = 0.65;
  75677. this._padSensibilityDown = 0.35;
  75678. /**
  75679. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  75680. */
  75681. this.onNewMeshSelected = new BABYLON.Observable();
  75682. /**
  75683. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  75684. */
  75685. this.onNewMeshPicked = new BABYLON.Observable();
  75686. /**
  75687. * Observable raised before camera teleportation
  75688. */
  75689. this.onBeforeCameraTeleport = new BABYLON.Observable();
  75690. /**
  75691. * Observable raised after camera teleportation
  75692. */
  75693. this.onAfterCameraTeleport = new BABYLON.Observable();
  75694. /**
  75695. * Observable raised when current selected mesh gets unselected
  75696. */
  75697. this.onSelectedMeshUnselected = new BABYLON.Observable();
  75698. /**
  75699. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  75700. */
  75701. this.teleportationEnabled = true;
  75702. this._pointerDownOnMeshAsked = false;
  75703. this._isActionableMesh = false;
  75704. this._teleportationInitialized = false;
  75705. this._interactionsEnabled = false;
  75706. this._interactionsRequested = false;
  75707. this._displayGaze = true;
  75708. this._displayLaserPointer = true;
  75709. this._dpadPressed = true;
  75710. this._onResize = function () {
  75711. _this.moveButtonToBottomRight();
  75712. if (_this._fullscreenVRpresenting && _this._webVRready) {
  75713. _this.exitVR();
  75714. }
  75715. };
  75716. this._onFullscreenChange = function () {
  75717. if (document.fullscreen !== undefined) {
  75718. _this._fullscreenVRpresenting = document.fullscreen;
  75719. }
  75720. else if (document.mozFullScreen !== undefined) {
  75721. _this._fullscreenVRpresenting = document.mozFullScreen;
  75722. }
  75723. else if (document.webkitIsFullScreen !== undefined) {
  75724. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  75725. }
  75726. else if (document.msIsFullScreen !== undefined) {
  75727. _this._fullscreenVRpresenting = document.msIsFullScreen;
  75728. }
  75729. if (!_this._fullscreenVRpresenting && _this._canvas) {
  75730. _this.exitVR();
  75731. if (!_this._useCustomVRButton) {
  75732. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  75733. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  75734. }
  75735. }
  75736. };
  75737. this.beforeRender = function () {
  75738. _this._castRayAndSelectObject();
  75739. };
  75740. this._onNewGamepadConnected = function (gamepad) {
  75741. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  75742. if (gamepad.leftStick) {
  75743. gamepad.onleftstickchanged(function (stickValues) {
  75744. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  75745. // Listening to classic/xbox gamepad only if no VR controller is active
  75746. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  75747. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  75748. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  75749. _this._checkTeleportWithRay(stickValues);
  75750. _this._checkTeleportBackwards(stickValues);
  75751. }
  75752. }
  75753. });
  75754. }
  75755. if (gamepad.rightStick) {
  75756. gamepad.onrightstickchanged(function (stickValues) {
  75757. if (_this._teleportationInitialized) {
  75758. _this._checkRotate(stickValues);
  75759. }
  75760. });
  75761. }
  75762. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  75763. gamepad.onbuttondown(function (buttonPressed) {
  75764. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  75765. _this._selectionPointerDown();
  75766. }
  75767. });
  75768. gamepad.onbuttonup(function (buttonPressed) {
  75769. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  75770. _this._selectionPointerUp();
  75771. }
  75772. });
  75773. }
  75774. }
  75775. else {
  75776. var webVRController = gamepad;
  75777. _this._tryEnableInteractionOnController(webVRController);
  75778. }
  75779. };
  75780. // 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
  75781. this._tryEnableInteractionOnController = function (webVRController) {
  75782. if (webVRController.hand === "left") {
  75783. _this._leftControllerReady = true;
  75784. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  75785. _this._enableInteractionOnController(webVRController);
  75786. }
  75787. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  75788. _this._enableTeleportationOnController(webVRController);
  75789. }
  75790. }
  75791. if (webVRController.hand === "right") {
  75792. _this._rightControllerReady = true;
  75793. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  75794. _this._enableInteractionOnController(webVRController);
  75795. }
  75796. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  75797. _this._enableTeleportationOnController(webVRController);
  75798. }
  75799. }
  75800. };
  75801. this._onNewGamepadDisconnected = function (gamepad) {
  75802. if (gamepad instanceof BABYLON.WebVRController) {
  75803. if (gamepad.hand === "left") {
  75804. _this._interactionsEnabledOnLeftController = false;
  75805. _this._teleportationEnabledOnLeftController = false;
  75806. _this._leftControllerReady = false;
  75807. if (_this._leftLaserPointer) {
  75808. _this._leftLaserPointer.dispose();
  75809. }
  75810. }
  75811. if (gamepad.hand === "right") {
  75812. _this._interactionsEnabledOnRightController = false;
  75813. _this._teleportationEnabledOnRightController = false;
  75814. _this._rightControllerReady = false;
  75815. if (_this._rightLaserPointer) {
  75816. _this._rightLaserPointer.dispose();
  75817. }
  75818. }
  75819. }
  75820. };
  75821. this._workingVector = BABYLON.Vector3.Zero();
  75822. this._workingQuaternion = BABYLON.Quaternion.Identity();
  75823. this._workingMatrix = BABYLON.Matrix.Identity();
  75824. this._scene = scene;
  75825. this._canvas = scene.getEngine().getRenderingCanvas();
  75826. // Parse options
  75827. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  75828. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  75829. }
  75830. if (webVROptions.createDeviceOrientationCamera === undefined) {
  75831. webVROptions.createDeviceOrientationCamera = true;
  75832. }
  75833. if (webVROptions.defaultHeight === undefined) {
  75834. webVROptions.defaultHeight = 1.7;
  75835. }
  75836. if (webVROptions.useCustomVRButton) {
  75837. this._useCustomVRButton = true;
  75838. if (webVROptions.customVRButton) {
  75839. this._btnVR = webVROptions.customVRButton;
  75840. }
  75841. }
  75842. if (webVROptions.rayLength) {
  75843. this._rayLength = webVROptions.rayLength;
  75844. }
  75845. this._defaultHeight = webVROptions.defaultHeight;
  75846. // Set position
  75847. if (this._scene.activeCamera) {
  75848. this._position = this._scene.activeCamera.position.clone();
  75849. }
  75850. else {
  75851. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  75852. }
  75853. // Set non-vr camera
  75854. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  75855. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  75856. // Copy data from existing camera
  75857. if (this._scene.activeCamera) {
  75858. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  75859. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  75860. // Set rotation from previous camera
  75861. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  75862. var targetCamera = this._scene.activeCamera;
  75863. if (targetCamera.rotationQuaternion) {
  75864. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  75865. }
  75866. else {
  75867. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  75868. }
  75869. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  75870. }
  75871. }
  75872. this._scene.activeCamera = this._deviceOrientationCamera;
  75873. if (this._canvas) {
  75874. this._scene.activeCamera.attachControl(this._canvas);
  75875. }
  75876. }
  75877. else {
  75878. this._existingCamera = this._scene.activeCamera;
  75879. }
  75880. // Create VR cameras
  75881. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75882. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  75883. }
  75884. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  75885. this._webVRCamera.useStandingMatrix();
  75886. // Create default button
  75887. if (!this._useCustomVRButton) {
  75888. this._btnVR = document.createElement("BUTTON");
  75889. this._btnVR.className = "babylonVRicon";
  75890. this._btnVR.id = "babylonVRiconbtn";
  75891. this._btnVR.title = "Click to switch to VR";
  75892. 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) }";
  75893. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  75894. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  75895. // css += ".babylonVRicon.vrdisplaysupported { }";
  75896. // css += ".babylonVRicon.vrdisplayready { }";
  75897. // css += ".babylonVRicon.vrdisplayrequesting { }";
  75898. var style = document.createElement('style');
  75899. style.appendChild(document.createTextNode(css));
  75900. document.getElementsByTagName('head')[0].appendChild(style);
  75901. this.moveButtonToBottomRight();
  75902. }
  75903. // VR button click event
  75904. if (this._btnVR) {
  75905. this._btnVR.addEventListener("click", function () {
  75906. if (!_this.isInVRMode) {
  75907. _this.enterVR();
  75908. }
  75909. else {
  75910. _this.exitVR();
  75911. }
  75912. });
  75913. }
  75914. // Window events
  75915. window.addEventListener("resize", this._onResize);
  75916. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  75917. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  75918. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  75919. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  75920. // Display vr button when headset is connected
  75921. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75922. this.displayVRButton();
  75923. }
  75924. else {
  75925. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  75926. if (e.vrDisplay) {
  75927. _this.displayVRButton();
  75928. }
  75929. });
  75930. }
  75931. // Exiting VR mode using 'ESC' key on desktop
  75932. this._onKeyDown = function (event) {
  75933. if (event.keyCode === 27 && _this.isInVRMode) {
  75934. _this.exitVR();
  75935. }
  75936. };
  75937. document.addEventListener("keydown", this._onKeyDown);
  75938. // Exiting VR mode double tapping the touch screen
  75939. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  75940. if (_this.isInVRMode) {
  75941. _this.exitVR();
  75942. if (_this._fullscreenVRpresenting) {
  75943. _this._scene.getEngine().switchFullscreen(true);
  75944. }
  75945. }
  75946. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  75947. // Listen for WebVR display changes
  75948. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  75949. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  75950. this._onVRRequestPresentStart = function () {
  75951. _this._webVRrequesting = true;
  75952. _this.updateButtonVisibility();
  75953. };
  75954. this._onVRRequestPresentComplete = function (success) {
  75955. _this._webVRrequesting = false;
  75956. _this.updateButtonVisibility();
  75957. };
  75958. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  75959. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  75960. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  75961. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  75962. scene.onDisposeObservable.add(function () {
  75963. _this.dispose();
  75964. });
  75965. // Gamepad connection events
  75966. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  75967. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  75968. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  75969. this.updateButtonVisibility();
  75970. //create easing functions
  75971. this._circleEase = new BABYLON.CircleEase();
  75972. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  75973. }
  75974. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  75975. /** Return this.onEnteringVRObservable
  75976. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  75977. */
  75978. get: function () {
  75979. return this.onEnteringVRObservable;
  75980. },
  75981. enumerable: true,
  75982. configurable: true
  75983. });
  75984. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  75985. /** Return this.onExitingVRObservable
  75986. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  75987. */
  75988. get: function () {
  75989. return this.onExitingVRObservable;
  75990. },
  75991. enumerable: true,
  75992. configurable: true
  75993. });
  75994. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  75995. /** Return this.onControllerMeshLoadedObservable
  75996. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  75997. */
  75998. get: function () {
  75999. return this.onControllerMeshLoadedObservable;
  76000. },
  76001. enumerable: true,
  76002. configurable: true
  76003. });
  76004. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  76005. /**
  76006. * The mesh used to display where the user is going to teleport.
  76007. */
  76008. get: function () {
  76009. return this._teleportationTarget;
  76010. },
  76011. /**
  76012. * Sets the mesh to be used to display where the user is going to teleport.
  76013. */
  76014. set: function (value) {
  76015. if (value) {
  76016. value.name = "teleportationTarget";
  76017. this._isDefaultTeleportationTarget = false;
  76018. this._teleportationTarget = value;
  76019. }
  76020. },
  76021. enumerable: true,
  76022. configurable: true
  76023. });
  76024. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  76025. /**
  76026. * If the ray of the gaze should be displayed.
  76027. */
  76028. get: function () {
  76029. return this._displayGaze;
  76030. },
  76031. /**
  76032. * Sets if the ray of the gaze should be displayed.
  76033. */
  76034. set: function (value) {
  76035. this._displayGaze = value;
  76036. if (!value) {
  76037. this._gazeTracker.isVisible = false;
  76038. }
  76039. },
  76040. enumerable: true,
  76041. configurable: true
  76042. });
  76043. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  76044. /**
  76045. * If the ray of the LaserPointer should be displayed.
  76046. */
  76047. get: function () {
  76048. return this._displayLaserPointer;
  76049. },
  76050. /**
  76051. * Sets if the ray of the LaserPointer should be displayed.
  76052. */
  76053. set: function (value) {
  76054. this._displayLaserPointer = value;
  76055. if (!value) {
  76056. if (this._rightLaserPointer) {
  76057. this._rightLaserPointer.isVisible = false;
  76058. }
  76059. if (this._leftLaserPointer) {
  76060. this._leftLaserPointer.isVisible = false;
  76061. }
  76062. }
  76063. else {
  76064. if (this._rightLaserPointer) {
  76065. this._rightLaserPointer.isVisible = true;
  76066. }
  76067. else if (this._leftLaserPointer) {
  76068. this._leftLaserPointer.isVisible = true;
  76069. }
  76070. }
  76071. },
  76072. enumerable: true,
  76073. configurable: true
  76074. });
  76075. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  76076. /**
  76077. * The deviceOrientationCamera used as the camera when not in VR.
  76078. */
  76079. get: function () {
  76080. return this._deviceOrientationCamera;
  76081. },
  76082. enumerable: true,
  76083. configurable: true
  76084. });
  76085. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  76086. /**
  76087. * Based on the current WebVR support, returns the current VR camera used.
  76088. */
  76089. get: function () {
  76090. if (this._webVRready) {
  76091. return this._webVRCamera;
  76092. }
  76093. else {
  76094. return this._scene.activeCamera;
  76095. }
  76096. },
  76097. enumerable: true,
  76098. configurable: true
  76099. });
  76100. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  76101. /**
  76102. * The webVRCamera which is used when in VR.
  76103. */
  76104. get: function () {
  76105. return this._webVRCamera;
  76106. },
  76107. enumerable: true,
  76108. configurable: true
  76109. });
  76110. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  76111. /**
  76112. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  76113. */
  76114. get: function () {
  76115. return this._vrDeviceOrientationCamera;
  76116. },
  76117. enumerable: true,
  76118. configurable: true
  76119. });
  76120. // Raised when one of the controller has loaded successfully its associated default mesh
  76121. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  76122. this._tryEnableInteractionOnController(webVRController);
  76123. try {
  76124. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  76125. }
  76126. catch (err) {
  76127. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  76128. }
  76129. };
  76130. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  76131. /**
  76132. * Gets a value indicating if we are currently in VR mode.
  76133. */
  76134. get: function () {
  76135. return this._webVRpresenting || this._fullscreenVRpresenting;
  76136. },
  76137. enumerable: true,
  76138. configurable: true
  76139. });
  76140. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  76141. var vrDisplay = this._scene.getEngine().getVRDevice();
  76142. if (vrDisplay) {
  76143. var wasPresenting = this._webVRpresenting;
  76144. // A VR display is connected
  76145. this._webVRpresenting = vrDisplay.isPresenting;
  76146. if (wasPresenting && !this._webVRpresenting)
  76147. this.exitVR();
  76148. }
  76149. else {
  76150. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  76151. }
  76152. this.updateButtonVisibility();
  76153. };
  76154. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  76155. this._webVRsupported = eventArgs.vrSupported;
  76156. this._webVRready = !!eventArgs.vrDisplay;
  76157. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  76158. this.updateButtonVisibility();
  76159. };
  76160. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  76161. if (this._canvas && !this._useCustomVRButton) {
  76162. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  76163. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  76164. }
  76165. };
  76166. VRExperienceHelper.prototype.displayVRButton = function () {
  76167. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  76168. document.body.appendChild(this._btnVR);
  76169. this._btnVRDisplayed = true;
  76170. }
  76171. };
  76172. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  76173. if (!this._btnVR || this._useCustomVRButton) {
  76174. return;
  76175. }
  76176. this._btnVR.className = "babylonVRicon";
  76177. if (this.isInVRMode) {
  76178. this._btnVR.className += " vrdisplaypresenting";
  76179. }
  76180. else {
  76181. if (this._webVRready)
  76182. this._btnVR.className += " vrdisplayready";
  76183. if (this._webVRsupported)
  76184. this._btnVR.className += " vrdisplaysupported";
  76185. if (this._webVRrequesting)
  76186. this._btnVR.className += " vrdisplayrequesting";
  76187. }
  76188. };
  76189. /**
  76190. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  76191. * Otherwise, will use the fullscreen API.
  76192. */
  76193. VRExperienceHelper.prototype.enterVR = function () {
  76194. if (this.onEnteringVRObservable) {
  76195. try {
  76196. this.onEnteringVRObservable.notifyObservers(this);
  76197. }
  76198. catch (err) {
  76199. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  76200. }
  76201. }
  76202. if (this._scene.activeCamera) {
  76203. this._position = this._scene.activeCamera.position.clone();
  76204. // make sure that we return to the last active camera
  76205. this._existingCamera = this._scene.activeCamera;
  76206. }
  76207. if (this._webVRrequesting)
  76208. return;
  76209. // If WebVR is supported and a headset is connected
  76210. if (this._webVRready) {
  76211. if (!this._webVRpresenting) {
  76212. this._webVRCamera.position = this._position;
  76213. this._scene.activeCamera = this._webVRCamera;
  76214. }
  76215. }
  76216. else if (this._vrDeviceOrientationCamera) {
  76217. this._vrDeviceOrientationCamera.position = this._position;
  76218. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  76219. this._scene.getEngine().switchFullscreen(true);
  76220. this.updateButtonVisibility();
  76221. }
  76222. if (this._scene.activeCamera && this._canvas) {
  76223. this._scene.activeCamera.attachControl(this._canvas);
  76224. }
  76225. if (this._interactionsEnabled) {
  76226. this._scene.registerBeforeRender(this.beforeRender);
  76227. }
  76228. };
  76229. /**
  76230. * Attempt to exit VR, or fullscreen.
  76231. */
  76232. VRExperienceHelper.prototype.exitVR = function () {
  76233. if (this.onExitingVRObservable) {
  76234. try {
  76235. this.onExitingVRObservable.notifyObservers(this);
  76236. }
  76237. catch (err) {
  76238. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  76239. }
  76240. }
  76241. if (this._webVRpresenting) {
  76242. this._scene.getEngine().disableVR();
  76243. }
  76244. if (this._scene.activeCamera) {
  76245. this._position = this._scene.activeCamera.position.clone();
  76246. }
  76247. if (this._deviceOrientationCamera) {
  76248. this._deviceOrientationCamera.position = this._position;
  76249. this._scene.activeCamera = this._deviceOrientationCamera;
  76250. if (this._canvas) {
  76251. this._scene.activeCamera.attachControl(this._canvas);
  76252. }
  76253. }
  76254. else if (this._existingCamera) {
  76255. this._existingCamera.position = this._position;
  76256. this._scene.activeCamera = this._existingCamera;
  76257. }
  76258. this.updateButtonVisibility();
  76259. if (this._interactionsEnabled) {
  76260. this._scene.unregisterBeforeRender(this.beforeRender);
  76261. }
  76262. };
  76263. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  76264. /**
  76265. * The position of the vr experience helper.
  76266. */
  76267. get: function () {
  76268. return this._position;
  76269. },
  76270. /**
  76271. * Sets the position of the vr experience helper.
  76272. */
  76273. set: function (value) {
  76274. this._position = value;
  76275. if (this._scene.activeCamera) {
  76276. this._scene.activeCamera.position = value;
  76277. }
  76278. },
  76279. enumerable: true,
  76280. configurable: true
  76281. });
  76282. /**
  76283. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  76284. */
  76285. VRExperienceHelper.prototype.enableInteractions = function () {
  76286. var _this = this;
  76287. if (!this._interactionsEnabled) {
  76288. this._interactionsRequested = true;
  76289. if (this._leftControllerReady && this._webVRCamera.leftController) {
  76290. this._enableInteractionOnController(this._webVRCamera.leftController);
  76291. }
  76292. if (this._rightControllerReady && this._webVRCamera.rightController) {
  76293. this._enableInteractionOnController(this._webVRCamera.rightController);
  76294. }
  76295. this._createGazeTracker();
  76296. this.raySelectionPredicate = function (mesh) {
  76297. return mesh.isVisible;
  76298. };
  76299. this.meshSelectionPredicate = function (mesh) {
  76300. return true;
  76301. };
  76302. this._raySelectionPredicate = function (mesh) {
  76303. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  76304. && mesh.name.indexOf("teleportationTarget") === -1
  76305. && mesh.name.indexOf("torusTeleportation") === -1
  76306. && mesh.name.indexOf("laserPointer") === -1)) {
  76307. return _this.raySelectionPredicate(mesh);
  76308. }
  76309. return false;
  76310. };
  76311. this._interactionsEnabled = true;
  76312. }
  76313. };
  76314. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  76315. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  76316. if (this._floorMeshesCollection[i].id === mesh.id) {
  76317. return true;
  76318. }
  76319. }
  76320. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  76321. return true;
  76322. }
  76323. return false;
  76324. };
  76325. /**
  76326. * Adds a floor mesh to be used for teleportation.
  76327. * @param floorMesh the mesh to be used for teleportation.
  76328. */
  76329. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  76330. if (!this._floorMeshesCollection) {
  76331. return;
  76332. }
  76333. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  76334. return;
  76335. }
  76336. this._floorMeshesCollection.push(floorMesh);
  76337. };
  76338. /**
  76339. * Removes a floor mesh from being used for teleportation.
  76340. * @param floorMesh the mesh to be removed.
  76341. */
  76342. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  76343. if (!this._floorMeshesCollection) {
  76344. return;
  76345. }
  76346. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  76347. if (meshIndex !== -1) {
  76348. this._floorMeshesCollection.splice(meshIndex, 1);
  76349. }
  76350. };
  76351. /**
  76352. * Enables interactions and teleportation using the VR controllers and gaze.
  76353. * @param vrTeleportationOptions options to modify teleportation behavior.
  76354. */
  76355. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  76356. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  76357. if (!this._teleportationInitialized) {
  76358. this._teleportationRequested = true;
  76359. this.enableInteractions();
  76360. if (vrTeleportationOptions.floorMeshName) {
  76361. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  76362. }
  76363. if (vrTeleportationOptions.floorMeshes) {
  76364. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  76365. }
  76366. if (this._leftControllerReady && this._webVRCamera.leftController) {
  76367. this._enableTeleportationOnController(this._webVRCamera.leftController);
  76368. }
  76369. if (this._rightControllerReady && this._webVRCamera.rightController) {
  76370. this._enableTeleportationOnController(this._webVRCamera.rightController);
  76371. }
  76372. // Creates an image processing post process for the vignette not relying
  76373. // on the main scene configuration for image processing to reduce setup and spaces
  76374. // (gamma/linear) conflicts.
  76375. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  76376. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76377. imageProcessingConfiguration.vignetteEnabled = true;
  76378. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  76379. this._webVRCamera.detachPostProcess(this._postProcessMove);
  76380. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  76381. this._teleportationInitialized = true;
  76382. if (this._isDefaultTeleportationTarget) {
  76383. this._createTeleportationCircles();
  76384. }
  76385. }
  76386. };
  76387. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  76388. var _this = this;
  76389. var controllerMesh = webVRController.mesh;
  76390. if (controllerMesh) {
  76391. var makeNotPick = function (root) {
  76392. root.name += " laserPointer";
  76393. root.getChildMeshes().forEach(function (c) {
  76394. makeNotPick(c);
  76395. });
  76396. };
  76397. makeNotPick(controllerMesh);
  76398. var childMeshes = controllerMesh.getChildMeshes();
  76399. for (var i = 0; i < childMeshes.length; i++) {
  76400. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  76401. controllerMesh = childMeshes[i];
  76402. break;
  76403. }
  76404. }
  76405. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  76406. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  76407. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  76408. laserPointerMaterial.alpha = 0.6;
  76409. laserPointer.material = laserPointerMaterial;
  76410. laserPointer.rotation.x = Math.PI / 2;
  76411. laserPointer.parent = controllerMesh;
  76412. laserPointer.position.z = -0.5;
  76413. laserPointer.isVisible = false;
  76414. if (webVRController.hand === "left") {
  76415. this._leftLaserPointer = laserPointer;
  76416. this._interactionsEnabledOnLeftController = true;
  76417. if (!this._rightLaserPointer) {
  76418. this._leftLaserPointer.isVisible = true;
  76419. }
  76420. }
  76421. else {
  76422. this._rightLaserPointer = laserPointer;
  76423. this._interactionsEnabledOnRightController = true;
  76424. if (!this._leftLaserPointer) {
  76425. this._rightLaserPointer.isVisible = true;
  76426. }
  76427. }
  76428. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  76429. // Enabling / disabling laserPointer
  76430. if (_this._displayLaserPointer && stateObject.value === 1) {
  76431. laserPointer.isVisible = !laserPointer.isVisible;
  76432. // Laser pointer can only be active on left or right, not both at the same time
  76433. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  76434. _this._rightLaserPointer.isVisible = false;
  76435. }
  76436. else if (_this._leftLaserPointer) {
  76437. _this._leftLaserPointer.isVisible = false;
  76438. }
  76439. }
  76440. });
  76441. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  76442. if (!_this._pointerDownOnMeshAsked) {
  76443. if (stateObject.value > _this._padSensibilityUp) {
  76444. _this._selectionPointerDown();
  76445. }
  76446. }
  76447. else if (stateObject.value < _this._padSensibilityDown) {
  76448. _this._selectionPointerUp();
  76449. }
  76450. });
  76451. }
  76452. };
  76453. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  76454. if (webVRController === void 0) { webVRController = null; }
  76455. if (!this._teleportationRequestInitiated) {
  76456. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  76457. if (webVRController) {
  76458. // If laser pointer wasn't enabled yet
  76459. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  76460. this._leftLaserPointer.isVisible = true;
  76461. if (this._rightLaserPointer) {
  76462. this._rightLaserPointer.isVisible = false;
  76463. }
  76464. }
  76465. else if (this._displayLaserPointer && this._rightLaserPointer) {
  76466. this._rightLaserPointer.isVisible = true;
  76467. if (this._leftLaserPointer) {
  76468. this._leftLaserPointer.isVisible = false;
  76469. }
  76470. }
  76471. }
  76472. this._teleportationRequestInitiated = true;
  76473. }
  76474. }
  76475. else {
  76476. // Listening to the proper controller values changes to confirm teleportation
  76477. if (webVRController == null
  76478. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  76479. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  76480. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  76481. if (this._teleportationAllowed) {
  76482. this._teleportationAllowed = false;
  76483. this._teleportCamera();
  76484. }
  76485. this._teleportationRequestInitiated = false;
  76486. }
  76487. }
  76488. }
  76489. };
  76490. VRExperienceHelper.prototype._selectionPointerDown = function () {
  76491. this._pointerDownOnMeshAsked = true;
  76492. if (this._currentMeshSelected && this._currentHit) {
  76493. this._scene.simulatePointerDown(this._currentHit);
  76494. }
  76495. };
  76496. VRExperienceHelper.prototype._selectionPointerUp = function () {
  76497. if (this._currentMeshSelected && this._currentHit) {
  76498. this._scene.simulatePointerUp(this._currentHit);
  76499. }
  76500. this._pointerDownOnMeshAsked = false;
  76501. };
  76502. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  76503. // Only rotate when user is not currently selecting a teleportation location
  76504. if (this._teleportationRequestInitiated) {
  76505. return;
  76506. }
  76507. if (!this._rotationLeftAsked) {
  76508. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  76509. this._rotationLeftAsked = true;
  76510. if (this._rotationAllowed) {
  76511. this._rotateCamera(false);
  76512. }
  76513. }
  76514. }
  76515. else {
  76516. if (stateObject.x > -this._padSensibilityDown) {
  76517. this._rotationLeftAsked = false;
  76518. }
  76519. }
  76520. if (!this._rotationRightAsked) {
  76521. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  76522. this._rotationRightAsked = true;
  76523. if (this._rotationAllowed) {
  76524. this._rotateCamera(true);
  76525. }
  76526. }
  76527. }
  76528. else {
  76529. if (stateObject.x < this._padSensibilityDown) {
  76530. this._rotationRightAsked = false;
  76531. }
  76532. }
  76533. };
  76534. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  76535. // Only teleport backwards when user is not currently selecting a teleportation location
  76536. if (this._teleportationRequestInitiated) {
  76537. return;
  76538. }
  76539. // Teleport backwards
  76540. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  76541. if (!this._teleportationBackRequestInitiated) {
  76542. if (!this.currentVRCamera) {
  76543. return;
  76544. }
  76545. // Get rotation and position of the current camera
  76546. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  76547. var position = this.currentVRCamera.position;
  76548. // If the camera has device position, use that instead
  76549. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  76550. rotation = this.currentVRCamera.deviceRotationQuaternion;
  76551. position = this.currentVRCamera.devicePosition;
  76552. }
  76553. // Get matrix with only the y rotation of the device rotation
  76554. rotation.toEulerAnglesToRef(this._workingVector);
  76555. this._workingVector.z = 0;
  76556. this._workingVector.x = 0;
  76557. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  76558. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  76559. // Rotate backwards ray by device rotation to cast at the ground behind the user
  76560. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  76561. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  76562. var ray = new BABYLON.Ray(position, this._workingVector);
  76563. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  76564. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  76565. this._teleportCamera(hit.pickedPoint);
  76566. }
  76567. this._teleportationBackRequestInitiated = true;
  76568. }
  76569. }
  76570. else {
  76571. this._teleportationBackRequestInitiated = false;
  76572. }
  76573. };
  76574. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  76575. var _this = this;
  76576. var controllerMesh = webVRController.mesh;
  76577. if (controllerMesh) {
  76578. if (webVRController.hand === "left") {
  76579. if (!this._interactionsEnabledOnLeftController) {
  76580. this._enableInteractionOnController(webVRController);
  76581. }
  76582. this._teleportationEnabledOnLeftController = true;
  76583. }
  76584. else {
  76585. if (!this._interactionsEnabledOnRightController) {
  76586. this._enableInteractionOnController(webVRController);
  76587. }
  76588. this._teleportationEnabledOnRightController = true;
  76589. }
  76590. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  76591. this._dpadPressed = false;
  76592. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  76593. _this._dpadPressed = stateObject.pressed;
  76594. if (!_this._dpadPressed) {
  76595. _this._rotationLeftAsked = false;
  76596. _this._rotationRightAsked = false;
  76597. _this._teleportationBackRequestInitiated = false;
  76598. }
  76599. });
  76600. }
  76601. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  76602. if (_this.teleportationEnabled) {
  76603. _this._checkTeleportBackwards(stateObject);
  76604. _this._checkTeleportWithRay(stateObject, webVRController);
  76605. }
  76606. _this._checkRotate(stateObject);
  76607. });
  76608. }
  76609. };
  76610. // Gaze support used to point to teleport or to interact with an object
  76611. VRExperienceHelper.prototype._createGazeTracker = function () {
  76612. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  76613. this._gazeTracker.bakeCurrentTransformIntoVertices();
  76614. this._gazeTracker.isPickable = false;
  76615. this._gazeTracker.isVisible = false;
  76616. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  76617. targetMat.specularColor = BABYLON.Color3.Black();
  76618. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  76619. targetMat.backFaceCulling = false;
  76620. this._gazeTracker.material = targetMat;
  76621. };
  76622. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  76623. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  76624. this._teleportationTarget.isPickable = false;
  76625. var length = 512;
  76626. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  76627. dynamicTexture.hasAlpha = true;
  76628. var context = dynamicTexture.getContext();
  76629. var centerX = length / 2;
  76630. var centerY = length / 2;
  76631. var radius = 200;
  76632. context.beginPath();
  76633. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  76634. context.fillStyle = this._teleportationFillColor;
  76635. context.fill();
  76636. context.lineWidth = 10;
  76637. context.strokeStyle = this._teleportationBorderColor;
  76638. context.stroke();
  76639. context.closePath();
  76640. dynamicTexture.update();
  76641. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  76642. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  76643. this._teleportationTarget.material = teleportationCircleMaterial;
  76644. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  76645. torus.isPickable = false;
  76646. torus.parent = this._teleportationTarget;
  76647. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  76648. var keys = [];
  76649. keys.push({
  76650. frame: 0,
  76651. value: 0
  76652. });
  76653. keys.push({
  76654. frame: 30,
  76655. value: 0.4
  76656. });
  76657. keys.push({
  76658. frame: 60,
  76659. value: 0
  76660. });
  76661. animationInnerCircle.setKeys(keys);
  76662. var easingFunction = new BABYLON.SineEase();
  76663. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  76664. animationInnerCircle.setEasingFunction(easingFunction);
  76665. torus.animations = [];
  76666. torus.animations.push(animationInnerCircle);
  76667. this._scene.beginAnimation(torus, 0, 60, true);
  76668. this._hideTeleportationTarget();
  76669. };
  76670. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  76671. if (this._teleportationInitialized) {
  76672. this._teleportationTarget.isVisible = true;
  76673. if (this._isDefaultTeleportationTarget) {
  76674. this._teleportationTarget.getChildren()[0].isVisible = true;
  76675. }
  76676. }
  76677. };
  76678. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  76679. if (this._teleportationInitialized) {
  76680. this._teleportationTarget.isVisible = false;
  76681. if (this._isDefaultTeleportationTarget) {
  76682. this._teleportationTarget.getChildren()[0].isVisible = false;
  76683. }
  76684. }
  76685. };
  76686. VRExperienceHelper.prototype._rotateCamera = function (right) {
  76687. var _this = this;
  76688. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76689. return;
  76690. }
  76691. if (right) {
  76692. this._rotationAngle++;
  76693. }
  76694. else {
  76695. this._rotationAngle--;
  76696. }
  76697. this.currentVRCamera.animations = [];
  76698. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  76699. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76700. var animationRotationKeys = [];
  76701. animationRotationKeys.push({
  76702. frame: 0,
  76703. value: this.currentVRCamera.rotationQuaternion
  76704. });
  76705. animationRotationKeys.push({
  76706. frame: 6,
  76707. value: target
  76708. });
  76709. animationRotation.setKeys(animationRotationKeys);
  76710. animationRotation.setEasingFunction(this._circleEase);
  76711. this.currentVRCamera.animations.push(animationRotation);
  76712. this._postProcessMove.animations = [];
  76713. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76714. var vignetteWeightKeys = [];
  76715. vignetteWeightKeys.push({
  76716. frame: 0,
  76717. value: 0
  76718. });
  76719. vignetteWeightKeys.push({
  76720. frame: 3,
  76721. value: 4
  76722. });
  76723. vignetteWeightKeys.push({
  76724. frame: 6,
  76725. value: 0
  76726. });
  76727. animationPP.setKeys(vignetteWeightKeys);
  76728. animationPP.setEasingFunction(this._circleEase);
  76729. this._postProcessMove.animations.push(animationPP);
  76730. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76731. var vignetteStretchKeys = [];
  76732. vignetteStretchKeys.push({
  76733. frame: 0,
  76734. value: 0
  76735. });
  76736. vignetteStretchKeys.push({
  76737. frame: 3,
  76738. value: 10
  76739. });
  76740. vignetteStretchKeys.push({
  76741. frame: 6,
  76742. value: 0
  76743. });
  76744. animationPP2.setKeys(vignetteStretchKeys);
  76745. animationPP2.setEasingFunction(this._circleEase);
  76746. this._postProcessMove.animations.push(animationPP2);
  76747. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  76748. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  76749. this._webVRCamera.attachPostProcess(this._postProcessMove);
  76750. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  76751. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  76752. });
  76753. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  76754. };
  76755. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  76756. if (hit.pickedPoint) {
  76757. this._teleportationAllowed = true;
  76758. if (this._teleportationRequestInitiated) {
  76759. this._displayTeleportationTarget();
  76760. }
  76761. else {
  76762. this._hideTeleportationTarget();
  76763. }
  76764. this._haloCenter.copyFrom(hit.pickedPoint);
  76765. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  76766. var pickNormal = hit.getNormal(true, false);
  76767. if (pickNormal) {
  76768. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  76769. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  76770. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  76771. }
  76772. this._teleportationTarget.position.y += 0.1;
  76773. }
  76774. };
  76775. VRExperienceHelper.prototype._teleportCamera = function (location) {
  76776. var _this = this;
  76777. if (location === void 0) { location = null; }
  76778. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76779. return;
  76780. }
  76781. if (!location) {
  76782. location = this._haloCenter;
  76783. }
  76784. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  76785. // offset of the headset from the anchor.
  76786. if (this.webVRCamera.leftCamera) {
  76787. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  76788. this._workingVector.subtractInPlace(this.webVRCamera.position);
  76789. location.subtractToRef(this._workingVector, this._workingVector);
  76790. }
  76791. else {
  76792. this._workingVector.copyFrom(location);
  76793. }
  76794. // Add height to account for user's height offset
  76795. if (this.isInVRMode) {
  76796. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  76797. }
  76798. else {
  76799. this._workingVector.y += this._defaultHeight;
  76800. }
  76801. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  76802. // Create animation from the camera's position to the new location
  76803. this.currentVRCamera.animations = [];
  76804. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76805. var animationCameraTeleportationKeys = [{
  76806. frame: 0,
  76807. value: this.currentVRCamera.position
  76808. },
  76809. {
  76810. frame: 11,
  76811. value: this._workingVector
  76812. }
  76813. ];
  76814. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  76815. animationCameraTeleportation.setEasingFunction(this._circleEase);
  76816. this.currentVRCamera.animations.push(animationCameraTeleportation);
  76817. this._postProcessMove.animations = [];
  76818. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76819. var vignetteWeightKeys = [];
  76820. vignetteWeightKeys.push({
  76821. frame: 0,
  76822. value: 0
  76823. });
  76824. vignetteWeightKeys.push({
  76825. frame: 5,
  76826. value: 8
  76827. });
  76828. vignetteWeightKeys.push({
  76829. frame: 11,
  76830. value: 0
  76831. });
  76832. animationPP.setKeys(vignetteWeightKeys);
  76833. this._postProcessMove.animations.push(animationPP);
  76834. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76835. var vignetteStretchKeys = [];
  76836. vignetteStretchKeys.push({
  76837. frame: 0,
  76838. value: 0
  76839. });
  76840. vignetteStretchKeys.push({
  76841. frame: 5,
  76842. value: 10
  76843. });
  76844. vignetteStretchKeys.push({
  76845. frame: 11,
  76846. value: 0
  76847. });
  76848. animationPP2.setKeys(vignetteStretchKeys);
  76849. this._postProcessMove.animations.push(animationPP2);
  76850. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  76851. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  76852. this._webVRCamera.attachPostProcess(this._postProcessMove);
  76853. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  76854. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  76855. });
  76856. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  76857. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  76858. });
  76859. };
  76860. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  76861. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76862. return;
  76863. }
  76864. var ray;
  76865. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  76866. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  76867. }
  76868. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  76869. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  76870. }
  76871. else {
  76872. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  76873. }
  76874. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  76875. // Moving the gazeTracker on the mesh face targetted
  76876. if (hit && hit.pickedPoint) {
  76877. if (this._displayGaze) {
  76878. var multiplier = 1;
  76879. this._gazeTracker.isVisible = true;
  76880. if (this._isActionableMesh) {
  76881. multiplier = 3;
  76882. }
  76883. this._gazeTracker.scaling.x = hit.distance * multiplier;
  76884. this._gazeTracker.scaling.y = hit.distance * multiplier;
  76885. this._gazeTracker.scaling.z = hit.distance * multiplier;
  76886. var pickNormal = hit.getNormal();
  76887. // To avoid z-fighting
  76888. var deltaFighting = 0.002;
  76889. if (pickNormal) {
  76890. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  76891. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  76892. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  76893. }
  76894. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  76895. if (this._gazeTracker.position.x < 0) {
  76896. this._gazeTracker.position.x += deltaFighting;
  76897. }
  76898. else {
  76899. this._gazeTracker.position.x -= deltaFighting;
  76900. }
  76901. if (this._gazeTracker.position.y < 0) {
  76902. this._gazeTracker.position.y += deltaFighting;
  76903. }
  76904. else {
  76905. this._gazeTracker.position.y -= deltaFighting;
  76906. }
  76907. if (this._gazeTracker.position.z < 0) {
  76908. this._gazeTracker.position.z += deltaFighting;
  76909. }
  76910. else {
  76911. this._gazeTracker.position.z -= deltaFighting;
  76912. }
  76913. }
  76914. // Changing the size of the laser pointer based on the distance from the targetted point
  76915. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  76916. this._rightLaserPointer.scaling.y = hit.distance;
  76917. this._rightLaserPointer.position.z = -hit.distance / 2;
  76918. }
  76919. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  76920. this._leftLaserPointer.scaling.y = hit.distance;
  76921. this._leftLaserPointer.position.z = -hit.distance / 2;
  76922. }
  76923. }
  76924. else {
  76925. this._gazeTracker.isVisible = false;
  76926. }
  76927. if (hit && hit.pickedMesh) {
  76928. this._currentHit = hit;
  76929. if (this._pointerDownOnMeshAsked) {
  76930. this._scene.simulatePointerMove(this._currentHit);
  76931. }
  76932. // The object selected is the floor, we're in a teleportation scenario
  76933. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  76934. // Moving the teleportation area to this targetted point
  76935. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  76936. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  76937. this._notifySelectedMeshUnselected();
  76938. }
  76939. this._currentMeshSelected = null;
  76940. this._moveTeleportationSelectorTo(hit);
  76941. return;
  76942. }
  76943. // If not, we're in a selection scenario
  76944. this._hideTeleportationTarget();
  76945. this._teleportationAllowed = false;
  76946. if (hit.pickedMesh !== this._currentMeshSelected) {
  76947. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  76948. this.onNewMeshPicked.notifyObservers(hit);
  76949. this._currentMeshSelected = hit.pickedMesh;
  76950. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  76951. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  76952. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  76953. this._isActionableMesh = true;
  76954. }
  76955. else {
  76956. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76957. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76958. this._isActionableMesh = false;
  76959. }
  76960. try {
  76961. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  76962. }
  76963. catch (err) {
  76964. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  76965. }
  76966. }
  76967. else {
  76968. this._notifySelectedMeshUnselected();
  76969. this._currentMeshSelected = null;
  76970. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76971. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76972. }
  76973. }
  76974. }
  76975. else {
  76976. this._currentHit = null;
  76977. this._notifySelectedMeshUnselected();
  76978. this._currentMeshSelected = null;
  76979. this._teleportationAllowed = false;
  76980. this._hideTeleportationTarget();
  76981. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76982. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76983. }
  76984. };
  76985. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  76986. if (this._currentMeshSelected) {
  76987. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  76988. }
  76989. };
  76990. /**
  76991. * Sets the color of the laser ray from the vr controllers.
  76992. * @param color new color for the ray.
  76993. */
  76994. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  76995. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  76996. this._leftLaserPointer.material.emissiveColor = color;
  76997. }
  76998. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  76999. this._rightLaserPointer.material.emissiveColor = color;
  77000. }
  77001. };
  77002. /**
  77003. * Sets the color of the ray from the vr headsets gaze.
  77004. * @param color new color for the ray.
  77005. */
  77006. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  77007. if (this._gazeTracker.material) {
  77008. this._gazeTracker.material.emissiveColor = color;
  77009. }
  77010. };
  77011. /**
  77012. * Exits VR and disposes of the vr experience helper
  77013. */
  77014. VRExperienceHelper.prototype.dispose = function () {
  77015. if (this.isInVRMode) {
  77016. this.exitVR();
  77017. }
  77018. if (this._passProcessMove) {
  77019. this._passProcessMove.dispose();
  77020. }
  77021. if (this._postProcessMove) {
  77022. this._postProcessMove.dispose();
  77023. }
  77024. if (this._webVRCamera) {
  77025. this._webVRCamera.dispose();
  77026. }
  77027. if (this._vrDeviceOrientationCamera) {
  77028. this._vrDeviceOrientationCamera.dispose();
  77029. }
  77030. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  77031. document.body.removeChild(this._btnVR);
  77032. }
  77033. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  77034. this._deviceOrientationCamera.dispose();
  77035. }
  77036. if (this._gazeTracker) {
  77037. this._gazeTracker.dispose();
  77038. }
  77039. if (this._teleportationTarget) {
  77040. this._teleportationTarget.dispose();
  77041. }
  77042. this._floorMeshesCollection = [];
  77043. document.removeEventListener("keydown", this._onKeyDown);
  77044. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  77045. window.removeEventListener("resize", this._onResize);
  77046. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  77047. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  77048. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  77049. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  77050. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  77051. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  77052. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  77053. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  77054. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  77055. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  77056. this._scene.unregisterBeforeRender(this.beforeRender);
  77057. };
  77058. /**
  77059. * Gets the name of the VRExperienceHelper class
  77060. * @returns "VRExperienceHelper"
  77061. */
  77062. VRExperienceHelper.prototype.getClassName = function () {
  77063. return "VRExperienceHelper";
  77064. };
  77065. return VRExperienceHelper;
  77066. }());
  77067. BABYLON.VRExperienceHelper = VRExperienceHelper;
  77068. })(BABYLON || (BABYLON = {}));
  77069. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  77070. // Mainly based on these 2 articles :
  77071. // 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
  77072. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  77073. var BABYLON;
  77074. (function (BABYLON) {
  77075. var JoystickAxis;
  77076. (function (JoystickAxis) {
  77077. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  77078. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  77079. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  77080. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  77081. var VirtualJoystick = /** @class */ (function () {
  77082. function VirtualJoystick(leftJoystick) {
  77083. var _this = this;
  77084. if (leftJoystick) {
  77085. this._leftJoystick = true;
  77086. }
  77087. else {
  77088. this._leftJoystick = false;
  77089. }
  77090. VirtualJoystick._globalJoystickIndex++;
  77091. // By default left & right arrow keys are moving the X
  77092. // and up & down keys are moving the Y
  77093. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  77094. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  77095. this.reverseLeftRight = false;
  77096. this.reverseUpDown = false;
  77097. // collections of pointers
  77098. this._touches = new BABYLON.StringDictionary();
  77099. this.deltaPosition = BABYLON.Vector3.Zero();
  77100. this._joystickSensibility = 25;
  77101. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  77102. this._onResize = function (evt) {
  77103. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  77104. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  77105. if (VirtualJoystick.vjCanvas) {
  77106. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  77107. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  77108. }
  77109. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  77110. };
  77111. // injecting a canvas element on top of the canvas 3D game
  77112. if (!VirtualJoystick.vjCanvas) {
  77113. window.addEventListener("resize", this._onResize, false);
  77114. VirtualJoystick.vjCanvas = document.createElement("canvas");
  77115. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  77116. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  77117. VirtualJoystick.vjCanvas.width = window.innerWidth;
  77118. VirtualJoystick.vjCanvas.height = window.innerHeight;
  77119. VirtualJoystick.vjCanvas.style.width = "100%";
  77120. VirtualJoystick.vjCanvas.style.height = "100%";
  77121. VirtualJoystick.vjCanvas.style.position = "absolute";
  77122. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  77123. VirtualJoystick.vjCanvas.style.top = "0px";
  77124. VirtualJoystick.vjCanvas.style.left = "0px";
  77125. VirtualJoystick.vjCanvas.style.zIndex = "5";
  77126. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  77127. // Support for jQuery PEP polyfill
  77128. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  77129. var context = VirtualJoystick.vjCanvas.getContext('2d');
  77130. if (!context) {
  77131. throw new Error("Unable to create canvas for virtual joystick");
  77132. }
  77133. VirtualJoystick.vjCanvasContext = context;
  77134. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  77135. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  77136. document.body.appendChild(VirtualJoystick.vjCanvas);
  77137. }
  77138. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  77139. this.pressed = false;
  77140. // default joystick color
  77141. this._joystickColor = "cyan";
  77142. this._joystickPointerID = -1;
  77143. // current joystick position
  77144. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  77145. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  77146. // origin joystick position
  77147. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  77148. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  77149. this._onPointerDownHandlerRef = function (evt) {
  77150. _this._onPointerDown(evt);
  77151. };
  77152. this._onPointerMoveHandlerRef = function (evt) {
  77153. _this._onPointerMove(evt);
  77154. };
  77155. this._onPointerUpHandlerRef = function (evt) {
  77156. _this._onPointerUp(evt);
  77157. };
  77158. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  77159. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  77160. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  77161. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  77162. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  77163. evt.preventDefault(); // Disables system menu
  77164. }, false);
  77165. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  77166. }
  77167. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  77168. this._joystickSensibility = newJoystickSensibility;
  77169. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  77170. };
  77171. VirtualJoystick.prototype._onPointerDown = function (e) {
  77172. var positionOnScreenCondition;
  77173. e.preventDefault();
  77174. if (this._leftJoystick === true) {
  77175. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  77176. }
  77177. else {
  77178. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  77179. }
  77180. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  77181. // First contact will be dedicated to the virtual joystick
  77182. this._joystickPointerID = e.pointerId;
  77183. this._joystickPointerStartPos.x = e.clientX;
  77184. this._joystickPointerStartPos.y = e.clientY;
  77185. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  77186. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  77187. this._deltaJoystickVector.x = 0;
  77188. this._deltaJoystickVector.y = 0;
  77189. this.pressed = true;
  77190. this._touches.add(e.pointerId.toString(), e);
  77191. }
  77192. else {
  77193. // You can only trigger the action buttons with a joystick declared
  77194. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  77195. this._action();
  77196. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  77197. }
  77198. }
  77199. };
  77200. VirtualJoystick.prototype._onPointerMove = function (e) {
  77201. // If the current pointer is the one associated to the joystick (first touch contact)
  77202. if (this._joystickPointerID == e.pointerId) {
  77203. this._joystickPointerPos.x = e.clientX;
  77204. this._joystickPointerPos.y = e.clientY;
  77205. this._deltaJoystickVector = this._joystickPointerPos.clone();
  77206. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  77207. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  77208. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  77209. switch (this._axisTargetedByLeftAndRight) {
  77210. case JoystickAxis.X:
  77211. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  77212. break;
  77213. case JoystickAxis.Y:
  77214. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  77215. break;
  77216. case JoystickAxis.Z:
  77217. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  77218. break;
  77219. }
  77220. var directionUpDown = this.reverseUpDown ? 1 : -1;
  77221. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  77222. switch (this._axisTargetedByUpAndDown) {
  77223. case JoystickAxis.X:
  77224. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  77225. break;
  77226. case JoystickAxis.Y:
  77227. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  77228. break;
  77229. case JoystickAxis.Z:
  77230. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  77231. break;
  77232. }
  77233. }
  77234. else {
  77235. var data = this._touches.get(e.pointerId.toString());
  77236. if (data) {
  77237. data.x = e.clientX;
  77238. data.y = e.clientY;
  77239. }
  77240. }
  77241. };
  77242. VirtualJoystick.prototype._onPointerUp = function (e) {
  77243. if (this._joystickPointerID == e.pointerId) {
  77244. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  77245. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  77246. this._joystickPointerID = -1;
  77247. this.pressed = false;
  77248. }
  77249. else {
  77250. var touch = this._touches.get(e.pointerId.toString());
  77251. if (touch) {
  77252. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  77253. }
  77254. }
  77255. this._deltaJoystickVector.x = 0;
  77256. this._deltaJoystickVector.y = 0;
  77257. this._touches.remove(e.pointerId.toString());
  77258. };
  77259. /**
  77260. * Change the color of the virtual joystick
  77261. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  77262. */
  77263. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  77264. this._joystickColor = newColor;
  77265. };
  77266. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  77267. this._action = action;
  77268. };
  77269. // Define which axis you'd like to control for left & right
  77270. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  77271. switch (axis) {
  77272. case JoystickAxis.X:
  77273. case JoystickAxis.Y:
  77274. case JoystickAxis.Z:
  77275. this._axisTargetedByLeftAndRight = axis;
  77276. break;
  77277. default:
  77278. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  77279. break;
  77280. }
  77281. };
  77282. // Define which axis you'd like to control for up & down
  77283. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  77284. switch (axis) {
  77285. case JoystickAxis.X:
  77286. case JoystickAxis.Y:
  77287. case JoystickAxis.Z:
  77288. this._axisTargetedByUpAndDown = axis;
  77289. break;
  77290. default:
  77291. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  77292. break;
  77293. }
  77294. };
  77295. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  77296. var _this = this;
  77297. if (this.pressed) {
  77298. this._touches.forEach(function (key, touch) {
  77299. if (touch.pointerId === _this._joystickPointerID) {
  77300. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  77301. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  77302. VirtualJoystick.vjCanvasContext.beginPath();
  77303. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  77304. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77305. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  77306. VirtualJoystick.vjCanvasContext.stroke();
  77307. VirtualJoystick.vjCanvasContext.closePath();
  77308. VirtualJoystick.vjCanvasContext.beginPath();
  77309. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77310. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  77311. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  77312. VirtualJoystick.vjCanvasContext.stroke();
  77313. VirtualJoystick.vjCanvasContext.closePath();
  77314. VirtualJoystick.vjCanvasContext.beginPath();
  77315. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77316. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  77317. VirtualJoystick.vjCanvasContext.stroke();
  77318. VirtualJoystick.vjCanvasContext.closePath();
  77319. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  77320. }
  77321. else {
  77322. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  77323. VirtualJoystick.vjCanvasContext.beginPath();
  77324. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  77325. VirtualJoystick.vjCanvasContext.beginPath();
  77326. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  77327. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  77328. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  77329. VirtualJoystick.vjCanvasContext.stroke();
  77330. VirtualJoystick.vjCanvasContext.closePath();
  77331. touch.prevX = touch.x;
  77332. touch.prevY = touch.y;
  77333. }
  77334. ;
  77335. });
  77336. }
  77337. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  77338. };
  77339. VirtualJoystick.prototype.releaseCanvas = function () {
  77340. if (VirtualJoystick.vjCanvas) {
  77341. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  77342. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  77343. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  77344. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  77345. window.removeEventListener("resize", this._onResize);
  77346. document.body.removeChild(VirtualJoystick.vjCanvas);
  77347. VirtualJoystick.vjCanvas = null;
  77348. }
  77349. };
  77350. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  77351. VirtualJoystick._globalJoystickIndex = 0;
  77352. return VirtualJoystick;
  77353. }());
  77354. BABYLON.VirtualJoystick = VirtualJoystick;
  77355. })(BABYLON || (BABYLON = {}));
  77356. //# sourceMappingURL=babylon.virtualJoystick.js.map
  77357. var BABYLON;
  77358. (function (BABYLON) {
  77359. // We're mainly based on the logic defined into the FreeCamera code
  77360. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  77361. __extends(VirtualJoysticksCamera, _super);
  77362. function VirtualJoysticksCamera(name, position, scene) {
  77363. var _this = _super.call(this, name, position, scene) || this;
  77364. _this.inputs.addVirtualJoystick();
  77365. return _this;
  77366. }
  77367. VirtualJoysticksCamera.prototype.getClassName = function () {
  77368. return "VirtualJoysticksCamera";
  77369. };
  77370. return VirtualJoysticksCamera;
  77371. }(BABYLON.FreeCamera));
  77372. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  77373. })(BABYLON || (BABYLON = {}));
  77374. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  77375. var BABYLON;
  77376. (function (BABYLON) {
  77377. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  77378. function FreeCameraVirtualJoystickInput() {
  77379. }
  77380. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  77381. return this._leftjoystick;
  77382. };
  77383. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  77384. return this._rightjoystick;
  77385. };
  77386. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  77387. if (this._leftjoystick) {
  77388. var camera = this.camera;
  77389. var speed = camera._computeLocalCameraSpeed() * 50;
  77390. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  77391. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  77392. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  77393. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  77394. if (!this._leftjoystick.pressed) {
  77395. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  77396. }
  77397. if (!this._rightjoystick.pressed) {
  77398. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  77399. }
  77400. }
  77401. };
  77402. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  77403. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  77404. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  77405. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  77406. this._leftjoystick.setJoystickSensibility(0.15);
  77407. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  77408. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  77409. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  77410. this._rightjoystick.reverseUpDown = true;
  77411. this._rightjoystick.setJoystickSensibility(0.05);
  77412. this._rightjoystick.setJoystickColor("yellow");
  77413. };
  77414. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  77415. this._leftjoystick.releaseCanvas();
  77416. this._rightjoystick.releaseCanvas();
  77417. };
  77418. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  77419. return "FreeCameraVirtualJoystickInput";
  77420. };
  77421. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  77422. return "virtualJoystick";
  77423. };
  77424. return FreeCameraVirtualJoystickInput;
  77425. }());
  77426. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  77427. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  77428. })(BABYLON || (BABYLON = {}));
  77429. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  77430. var BABYLON;
  77431. (function (BABYLON) {
  77432. var SimplificationSettings = /** @class */ (function () {
  77433. function SimplificationSettings(quality, distance, optimizeMesh) {
  77434. this.quality = quality;
  77435. this.distance = distance;
  77436. this.optimizeMesh = optimizeMesh;
  77437. }
  77438. return SimplificationSettings;
  77439. }());
  77440. BABYLON.SimplificationSettings = SimplificationSettings;
  77441. var SimplificationQueue = /** @class */ (function () {
  77442. function SimplificationQueue() {
  77443. this.running = false;
  77444. this._simplificationArray = [];
  77445. }
  77446. SimplificationQueue.prototype.addTask = function (task) {
  77447. this._simplificationArray.push(task);
  77448. };
  77449. SimplificationQueue.prototype.executeNext = function () {
  77450. var task = this._simplificationArray.pop();
  77451. if (task) {
  77452. this.running = true;
  77453. this.runSimplification(task);
  77454. }
  77455. else {
  77456. this.running = false;
  77457. }
  77458. };
  77459. SimplificationQueue.prototype.runSimplification = function (task) {
  77460. var _this = this;
  77461. if (task.parallelProcessing) {
  77462. //parallel simplifier
  77463. task.settings.forEach(function (setting) {
  77464. var simplifier = _this.getSimplifier(task);
  77465. simplifier.simplify(setting, function (newMesh) {
  77466. task.mesh.addLODLevel(setting.distance, newMesh);
  77467. newMesh.isVisible = true;
  77468. //check if it is the last
  77469. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  77470. //all done, run the success callback.
  77471. task.successCallback();
  77472. }
  77473. _this.executeNext();
  77474. });
  77475. });
  77476. }
  77477. else {
  77478. //single simplifier.
  77479. var simplifier = this.getSimplifier(task);
  77480. var runDecimation = function (setting, callback) {
  77481. simplifier.simplify(setting, function (newMesh) {
  77482. task.mesh.addLODLevel(setting.distance, newMesh);
  77483. newMesh.isVisible = true;
  77484. //run the next quality level
  77485. callback();
  77486. });
  77487. };
  77488. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  77489. runDecimation(task.settings[loop.index], function () {
  77490. loop.executeNext();
  77491. });
  77492. }, function () {
  77493. //execution ended, run the success callback.
  77494. if (task.successCallback) {
  77495. task.successCallback();
  77496. }
  77497. _this.executeNext();
  77498. });
  77499. }
  77500. };
  77501. SimplificationQueue.prototype.getSimplifier = function (task) {
  77502. switch (task.simplificationType) {
  77503. case SimplificationType.QUADRATIC:
  77504. default:
  77505. return new QuadraticErrorSimplification(task.mesh);
  77506. }
  77507. };
  77508. return SimplificationQueue;
  77509. }());
  77510. BABYLON.SimplificationQueue = SimplificationQueue;
  77511. /**
  77512. * The implemented types of simplification.
  77513. * At the moment only Quadratic Error Decimation is implemented.
  77514. */
  77515. var SimplificationType;
  77516. (function (SimplificationType) {
  77517. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  77518. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  77519. var DecimationTriangle = /** @class */ (function () {
  77520. function DecimationTriangle(vertices) {
  77521. this.vertices = vertices;
  77522. this.error = new Array(4);
  77523. this.deleted = false;
  77524. this.isDirty = false;
  77525. this.deletePending = false;
  77526. this.borderFactor = 0;
  77527. }
  77528. return DecimationTriangle;
  77529. }());
  77530. BABYLON.DecimationTriangle = DecimationTriangle;
  77531. var DecimationVertex = /** @class */ (function () {
  77532. function DecimationVertex(position, id) {
  77533. this.position = position;
  77534. this.id = id;
  77535. this.isBorder = true;
  77536. this.q = new QuadraticMatrix();
  77537. this.triangleCount = 0;
  77538. this.triangleStart = 0;
  77539. this.originalOffsets = [];
  77540. }
  77541. DecimationVertex.prototype.updatePosition = function (newPosition) {
  77542. this.position.copyFrom(newPosition);
  77543. };
  77544. return DecimationVertex;
  77545. }());
  77546. BABYLON.DecimationVertex = DecimationVertex;
  77547. var QuadraticMatrix = /** @class */ (function () {
  77548. function QuadraticMatrix(data) {
  77549. this.data = new Array(10);
  77550. for (var i = 0; i < 10; ++i) {
  77551. if (data && data[i]) {
  77552. this.data[i] = data[i];
  77553. }
  77554. else {
  77555. this.data[i] = 0;
  77556. }
  77557. }
  77558. }
  77559. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  77560. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  77561. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  77562. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  77563. return det;
  77564. };
  77565. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  77566. for (var i = 0; i < 10; ++i) {
  77567. this.data[i] += matrix.data[i];
  77568. }
  77569. };
  77570. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  77571. for (var i = 0; i < 10; ++i) {
  77572. this.data[i] += data[i];
  77573. }
  77574. };
  77575. QuadraticMatrix.prototype.add = function (matrix) {
  77576. var m = new QuadraticMatrix();
  77577. for (var i = 0; i < 10; ++i) {
  77578. m.data[i] = this.data[i] + matrix.data[i];
  77579. }
  77580. return m;
  77581. };
  77582. QuadraticMatrix.FromData = function (a, b, c, d) {
  77583. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  77584. };
  77585. //returning an array to avoid garbage collection
  77586. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  77587. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  77588. };
  77589. return QuadraticMatrix;
  77590. }());
  77591. BABYLON.QuadraticMatrix = QuadraticMatrix;
  77592. var Reference = /** @class */ (function () {
  77593. function Reference(vertexId, triangleId) {
  77594. this.vertexId = vertexId;
  77595. this.triangleId = triangleId;
  77596. }
  77597. return Reference;
  77598. }());
  77599. BABYLON.Reference = Reference;
  77600. /**
  77601. * An implementation of the Quadratic Error simplification algorithm.
  77602. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  77603. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  77604. * @author RaananW
  77605. */
  77606. var QuadraticErrorSimplification = /** @class */ (function () {
  77607. function QuadraticErrorSimplification(_mesh) {
  77608. this._mesh = _mesh;
  77609. this.syncIterations = 5000;
  77610. this.aggressiveness = 7;
  77611. this.decimationIterations = 100;
  77612. this.boundingBoxEpsilon = BABYLON.Epsilon;
  77613. }
  77614. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  77615. var _this = this;
  77616. this.initDecimatedMesh();
  77617. //iterating through the submeshes array, one after the other.
  77618. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  77619. _this.initWithMesh(loop.index, function () {
  77620. _this.runDecimation(settings, loop.index, function () {
  77621. loop.executeNext();
  77622. });
  77623. }, settings.optimizeMesh);
  77624. }, function () {
  77625. setTimeout(function () {
  77626. successCallback(_this._reconstructedMesh);
  77627. }, 0);
  77628. });
  77629. };
  77630. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  77631. var _this = this;
  77632. var targetCount = ~~(this.triangles.length * settings.quality);
  77633. var deletedTriangles = 0;
  77634. var triangleCount = this.triangles.length;
  77635. var iterationFunction = function (iteration, callback) {
  77636. setTimeout(function () {
  77637. if (iteration % 5 === 0) {
  77638. _this.updateMesh(iteration === 0);
  77639. }
  77640. for (var i = 0; i < _this.triangles.length; ++i) {
  77641. _this.triangles[i].isDirty = false;
  77642. }
  77643. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  77644. var trianglesIterator = function (i) {
  77645. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  77646. var t = _this.triangles[tIdx];
  77647. if (!t)
  77648. return;
  77649. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  77650. return;
  77651. }
  77652. for (var j = 0; j < 3; ++j) {
  77653. if (t.error[j] < threshold) {
  77654. var deleted0 = [];
  77655. var deleted1 = [];
  77656. var v0 = t.vertices[j];
  77657. var v1 = t.vertices[(j + 1) % 3];
  77658. if (v0.isBorder || v1.isBorder)
  77659. continue;
  77660. var p = BABYLON.Vector3.Zero();
  77661. var n = BABYLON.Vector3.Zero();
  77662. var uv = BABYLON.Vector2.Zero();
  77663. var color = new BABYLON.Color4(0, 0, 0, 1);
  77664. _this.calculateError(v0, v1, p, n, uv, color);
  77665. var delTr = new Array();
  77666. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  77667. continue;
  77668. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  77669. continue;
  77670. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  77671. continue;
  77672. var uniqueArray = new Array();
  77673. delTr.forEach(function (deletedT) {
  77674. if (uniqueArray.indexOf(deletedT) === -1) {
  77675. deletedT.deletePending = true;
  77676. uniqueArray.push(deletedT);
  77677. }
  77678. });
  77679. if (uniqueArray.length % 2 !== 0) {
  77680. continue;
  77681. }
  77682. v0.q = v1.q.add(v0.q);
  77683. v0.updatePosition(p);
  77684. var tStart = _this.references.length;
  77685. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  77686. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  77687. var tCount = _this.references.length - tStart;
  77688. if (tCount <= v0.triangleCount) {
  77689. if (tCount) {
  77690. for (var c = 0; c < tCount; c++) {
  77691. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  77692. }
  77693. }
  77694. }
  77695. else {
  77696. v0.triangleStart = tStart;
  77697. }
  77698. v0.triangleCount = tCount;
  77699. break;
  77700. }
  77701. }
  77702. };
  77703. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  77704. }, 0);
  77705. };
  77706. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  77707. if (triangleCount - deletedTriangles <= targetCount)
  77708. loop.breakLoop();
  77709. else {
  77710. iterationFunction(loop.index, function () {
  77711. loop.executeNext();
  77712. });
  77713. }
  77714. }, function () {
  77715. setTimeout(function () {
  77716. //reconstruct this part of the mesh
  77717. _this.reconstructMesh(submeshIndex);
  77718. successCallback();
  77719. }, 0);
  77720. });
  77721. };
  77722. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  77723. var _this = this;
  77724. this.vertices = [];
  77725. this.triangles = [];
  77726. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  77727. var indices = this._mesh.getIndices();
  77728. var submesh = this._mesh.subMeshes[submeshIndex];
  77729. var findInVertices = function (positionToSearch) {
  77730. if (optimizeMesh) {
  77731. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  77732. if (_this.vertices[ii].position.equals(positionToSearch)) {
  77733. return _this.vertices[ii];
  77734. }
  77735. }
  77736. }
  77737. return null;
  77738. };
  77739. var vertexReferences = [];
  77740. var vertexInit = function (i) {
  77741. if (!positionData) {
  77742. return;
  77743. }
  77744. var offset = i + submesh.verticesStart;
  77745. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  77746. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  77747. vertex.originalOffsets.push(offset);
  77748. if (vertex.id === _this.vertices.length) {
  77749. _this.vertices.push(vertex);
  77750. }
  77751. vertexReferences.push(vertex.id);
  77752. };
  77753. //var totalVertices = mesh.getTotalVertices();
  77754. var totalVertices = submesh.verticesCount;
  77755. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  77756. var indicesInit = function (i) {
  77757. if (!indices) {
  77758. return;
  77759. }
  77760. var offset = (submesh.indexStart / 3) + i;
  77761. var pos = (offset * 3);
  77762. var i0 = indices[pos + 0];
  77763. var i1 = indices[pos + 1];
  77764. var i2 = indices[pos + 2];
  77765. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  77766. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  77767. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  77768. var triangle = new DecimationTriangle([v0, v1, v2]);
  77769. triangle.originalOffset = pos;
  77770. _this.triangles.push(triangle);
  77771. };
  77772. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  77773. _this.init(callback);
  77774. });
  77775. });
  77776. };
  77777. QuadraticErrorSimplification.prototype.init = function (callback) {
  77778. var _this = this;
  77779. var triangleInit1 = function (i) {
  77780. var t = _this.triangles[i];
  77781. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  77782. for (var j = 0; j < 3; j++) {
  77783. 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))));
  77784. }
  77785. };
  77786. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  77787. var triangleInit2 = function (i) {
  77788. var t = _this.triangles[i];
  77789. for (var j = 0; j < 3; ++j) {
  77790. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  77791. }
  77792. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  77793. };
  77794. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  77795. callback();
  77796. });
  77797. });
  77798. };
  77799. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  77800. var newTriangles = [];
  77801. var i;
  77802. for (i = 0; i < this.vertices.length; ++i) {
  77803. this.vertices[i].triangleCount = 0;
  77804. }
  77805. var t;
  77806. var j;
  77807. for (i = 0; i < this.triangles.length; ++i) {
  77808. if (!this.triangles[i].deleted) {
  77809. t = this.triangles[i];
  77810. for (j = 0; j < 3; ++j) {
  77811. t.vertices[j].triangleCount = 1;
  77812. }
  77813. newTriangles.push(t);
  77814. }
  77815. }
  77816. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  77817. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  77818. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  77819. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  77820. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  77821. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  77822. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  77823. var vertexCount = 0;
  77824. for (i = 0; i < this.vertices.length; ++i) {
  77825. var vertex = this.vertices[i];
  77826. vertex.id = vertexCount;
  77827. if (vertex.triangleCount) {
  77828. vertex.originalOffsets.forEach(function (originalOffset) {
  77829. if (!normalData) {
  77830. return;
  77831. }
  77832. newPositionData.push(vertex.position.x);
  77833. newPositionData.push(vertex.position.y);
  77834. newPositionData.push(vertex.position.z);
  77835. newNormalData.push(normalData[originalOffset * 3]);
  77836. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  77837. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  77838. if (uvs && uvs.length) {
  77839. newUVsData.push(uvs[(originalOffset * 2)]);
  77840. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  77841. }
  77842. else if (colorsData && colorsData.length) {
  77843. newColorsData.push(colorsData[(originalOffset * 4)]);
  77844. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  77845. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  77846. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  77847. }
  77848. ++vertexCount;
  77849. });
  77850. }
  77851. }
  77852. var startingIndex = this._reconstructedMesh.getTotalIndices();
  77853. var startingVertex = this._reconstructedMesh.getTotalVertices();
  77854. var submeshesArray = this._reconstructedMesh.subMeshes;
  77855. this._reconstructedMesh.subMeshes = [];
  77856. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  77857. var originalIndices = this._mesh.getIndices();
  77858. for (i = 0; i < newTriangles.length; ++i) {
  77859. t = newTriangles[i]; //now get the new referencing point for each vertex
  77860. [0, 1, 2].forEach(function (idx) {
  77861. var id = originalIndices[t.originalOffset + idx];
  77862. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  77863. if (offset < 0)
  77864. offset = 0;
  77865. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  77866. });
  77867. }
  77868. //overwriting the old vertex buffers and indices.
  77869. this._reconstructedMesh.setIndices(newIndicesArray);
  77870. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  77871. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  77872. if (newUVsData.length > 0)
  77873. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  77874. if (newColorsData.length > 0)
  77875. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  77876. //create submesh
  77877. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  77878. if (submeshIndex > 0) {
  77879. this._reconstructedMesh.subMeshes = [];
  77880. submeshesArray.forEach(function (submesh) {
  77881. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  77882. });
  77883. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  77884. }
  77885. };
  77886. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  77887. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  77888. this._reconstructedMesh.material = this._mesh.material;
  77889. this._reconstructedMesh.parent = this._mesh.parent;
  77890. this._reconstructedMesh.isVisible = false;
  77891. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  77892. };
  77893. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  77894. for (var i = 0; i < vertex1.triangleCount; ++i) {
  77895. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  77896. if (t.deleted)
  77897. continue;
  77898. var s = this.references[vertex1.triangleStart + i].vertexId;
  77899. var v1 = t.vertices[(s + 1) % 3];
  77900. var v2 = t.vertices[(s + 2) % 3];
  77901. if ((v1 === vertex2 || v2 === vertex2)) {
  77902. deletedArray[i] = true;
  77903. delTr.push(t);
  77904. continue;
  77905. }
  77906. var d1 = v1.position.subtract(point);
  77907. d1 = d1.normalize();
  77908. var d2 = v2.position.subtract(point);
  77909. d2 = d2.normalize();
  77910. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  77911. return true;
  77912. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  77913. deletedArray[i] = false;
  77914. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  77915. return true;
  77916. }
  77917. return false;
  77918. };
  77919. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  77920. var newDeleted = deletedTriangles;
  77921. for (var i = 0; i < vertex.triangleCount; ++i) {
  77922. var ref = this.references[vertex.triangleStart + i];
  77923. var t = this.triangles[ref.triangleId];
  77924. if (t.deleted)
  77925. continue;
  77926. if (deletedArray[i] && t.deletePending) {
  77927. t.deleted = true;
  77928. newDeleted++;
  77929. continue;
  77930. }
  77931. t.vertices[ref.vertexId] = origVertex;
  77932. t.isDirty = true;
  77933. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  77934. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  77935. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  77936. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  77937. this.references.push(ref);
  77938. }
  77939. return newDeleted;
  77940. };
  77941. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  77942. for (var i = 0; i < this.vertices.length; ++i) {
  77943. var vCount = [];
  77944. var vId = [];
  77945. var v = this.vertices[i];
  77946. var j;
  77947. for (j = 0; j < v.triangleCount; ++j) {
  77948. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  77949. for (var ii = 0; ii < 3; ii++) {
  77950. var ofs = 0;
  77951. var vv = triangle.vertices[ii];
  77952. while (ofs < vCount.length) {
  77953. if (vId[ofs] === vv.id)
  77954. break;
  77955. ++ofs;
  77956. }
  77957. if (ofs === vCount.length) {
  77958. vCount.push(1);
  77959. vId.push(vv.id);
  77960. }
  77961. else {
  77962. vCount[ofs]++;
  77963. }
  77964. }
  77965. }
  77966. for (j = 0; j < vCount.length; ++j) {
  77967. if (vCount[j] === 1) {
  77968. this.vertices[vId[j]].isBorder = true;
  77969. }
  77970. else {
  77971. this.vertices[vId[j]].isBorder = false;
  77972. }
  77973. }
  77974. }
  77975. };
  77976. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  77977. if (identifyBorders === void 0) { identifyBorders = false; }
  77978. var i;
  77979. if (!identifyBorders) {
  77980. var newTrianglesVector = [];
  77981. for (i = 0; i < this.triangles.length; ++i) {
  77982. if (!this.triangles[i].deleted) {
  77983. newTrianglesVector.push(this.triangles[i]);
  77984. }
  77985. }
  77986. this.triangles = newTrianglesVector;
  77987. }
  77988. for (i = 0; i < this.vertices.length; ++i) {
  77989. this.vertices[i].triangleCount = 0;
  77990. this.vertices[i].triangleStart = 0;
  77991. }
  77992. var t;
  77993. var j;
  77994. var v;
  77995. for (i = 0; i < this.triangles.length; ++i) {
  77996. t = this.triangles[i];
  77997. for (j = 0; j < 3; ++j) {
  77998. v = t.vertices[j];
  77999. v.triangleCount++;
  78000. }
  78001. }
  78002. var tStart = 0;
  78003. for (i = 0; i < this.vertices.length; ++i) {
  78004. this.vertices[i].triangleStart = tStart;
  78005. tStart += this.vertices[i].triangleCount;
  78006. this.vertices[i].triangleCount = 0;
  78007. }
  78008. var newReferences = new Array(this.triangles.length * 3);
  78009. for (i = 0; i < this.triangles.length; ++i) {
  78010. t = this.triangles[i];
  78011. for (j = 0; j < 3; ++j) {
  78012. v = t.vertices[j];
  78013. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  78014. v.triangleCount++;
  78015. }
  78016. }
  78017. this.references = newReferences;
  78018. if (identifyBorders) {
  78019. this.identifyBorder();
  78020. }
  78021. };
  78022. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  78023. var x = point.x;
  78024. var y = point.y;
  78025. var z = point.z;
  78026. 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
  78027. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  78028. };
  78029. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  78030. var q = vertex1.q.add(vertex2.q);
  78031. var border = vertex1.isBorder && vertex2.isBorder;
  78032. var error = 0;
  78033. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  78034. if (qDet !== 0 && !border) {
  78035. if (!pointResult) {
  78036. pointResult = BABYLON.Vector3.Zero();
  78037. }
  78038. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  78039. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  78040. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  78041. error = this.vertexError(q, pointResult);
  78042. }
  78043. else {
  78044. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  78045. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  78046. var error1 = this.vertexError(q, vertex1.position);
  78047. var error2 = this.vertexError(q, vertex2.position);
  78048. var error3 = this.vertexError(q, p3);
  78049. error = Math.min(error1, error2, error3);
  78050. if (error === error1) {
  78051. if (pointResult) {
  78052. pointResult.copyFrom(vertex1.position);
  78053. }
  78054. }
  78055. else if (error === error2) {
  78056. if (pointResult) {
  78057. pointResult.copyFrom(vertex2.position);
  78058. }
  78059. }
  78060. else {
  78061. if (pointResult) {
  78062. pointResult.copyFrom(p3);
  78063. }
  78064. }
  78065. }
  78066. return error;
  78067. };
  78068. return QuadraticErrorSimplification;
  78069. }());
  78070. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  78071. })(BABYLON || (BABYLON = {}));
  78072. //# sourceMappingURL=babylon.meshSimplification.js.map
  78073. var BABYLON;
  78074. (function (BABYLON) {
  78075. var MeshLODLevel = /** @class */ (function () {
  78076. function MeshLODLevel(distance, mesh) {
  78077. this.distance = distance;
  78078. this.mesh = mesh;
  78079. }
  78080. return MeshLODLevel;
  78081. }());
  78082. BABYLON.MeshLODLevel = MeshLODLevel;
  78083. })(BABYLON || (BABYLON = {}));
  78084. //# sourceMappingURL=babylon.meshLODLevel.js.map
  78085. var BABYLON;
  78086. (function (BABYLON) {
  78087. /**
  78088. * Defines the root class used to create scene optimization to use with SceneOptimizer
  78089. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78090. */
  78091. var SceneOptimization = /** @class */ (function () {
  78092. /**
  78093. * Creates the SceneOptimization object
  78094. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78095. * @param desc defines the description associated with the optimization
  78096. */
  78097. function SceneOptimization(
  78098. /**
  78099. * Defines the priority of this optimization (0 by default which means first in the list)
  78100. */
  78101. priority) {
  78102. if (priority === void 0) { priority = 0; }
  78103. this.priority = priority;
  78104. }
  78105. /**
  78106. * Gets a string describing the action executed by the current optimization
  78107. * @returns description string
  78108. */
  78109. SceneOptimization.prototype.getDescription = function () {
  78110. return "";
  78111. };
  78112. /**
  78113. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78114. * @param scene defines the current scene where to apply this optimization
  78115. * @param optimizer defines the current optimizer
  78116. * @returns true if everything that can be done was applied
  78117. */
  78118. SceneOptimization.prototype.apply = function (scene, optimizer) {
  78119. return true;
  78120. };
  78121. ;
  78122. return SceneOptimization;
  78123. }());
  78124. BABYLON.SceneOptimization = SceneOptimization;
  78125. /**
  78126. * Defines an optimization used to reduce the size of render target textures
  78127. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78128. */
  78129. var TextureOptimization = /** @class */ (function (_super) {
  78130. __extends(TextureOptimization, _super);
  78131. /**
  78132. * Creates the TextureOptimization object
  78133. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78134. * @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
  78135. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  78136. */
  78137. function TextureOptimization(
  78138. /**
  78139. * Defines the priority of this optimization (0 by default which means first in the list)
  78140. */
  78141. priority,
  78142. /**
  78143. * 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
  78144. */
  78145. maximumSize,
  78146. /**
  78147. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  78148. */
  78149. step) {
  78150. if (priority === void 0) { priority = 0; }
  78151. if (maximumSize === void 0) { maximumSize = 1024; }
  78152. if (step === void 0) { step = 0.5; }
  78153. var _this = _super.call(this, priority) || this;
  78154. _this.priority = priority;
  78155. _this.maximumSize = maximumSize;
  78156. _this.step = step;
  78157. return _this;
  78158. }
  78159. /**
  78160. * Gets a string describing the action executed by the current optimization
  78161. * @returns description string
  78162. */
  78163. TextureOptimization.prototype.getDescription = function () {
  78164. return "Reducing render target texture size to " + this.maximumSize;
  78165. };
  78166. /**
  78167. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78168. * @param scene defines the current scene where to apply this optimization
  78169. * @param optimizer defines the current optimizer
  78170. * @returns true if everything that can be done was applied
  78171. */
  78172. TextureOptimization.prototype.apply = function (scene, optimizer) {
  78173. var allDone = true;
  78174. for (var index = 0; index < scene.textures.length; index++) {
  78175. var texture = scene.textures[index];
  78176. if (!texture.canRescale || texture.getContext) {
  78177. continue;
  78178. }
  78179. var currentSize = texture.getSize();
  78180. var maxDimension = Math.max(currentSize.width, currentSize.height);
  78181. if (maxDimension > this.maximumSize) {
  78182. texture.scale(this.step);
  78183. allDone = false;
  78184. }
  78185. }
  78186. return allDone;
  78187. };
  78188. return TextureOptimization;
  78189. }(SceneOptimization));
  78190. BABYLON.TextureOptimization = TextureOptimization;
  78191. /**
  78192. * Defines an optimization used to increase or decrease the rendering resolution
  78193. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78194. */
  78195. var HardwareScalingOptimization = /** @class */ (function (_super) {
  78196. __extends(HardwareScalingOptimization, _super);
  78197. /**
  78198. * Creates the HardwareScalingOptimization object
  78199. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78200. * @param maximumScale defines the maximum scale to use (2 by default)
  78201. * @param step defines the step to use between two passes (0.5 by default)
  78202. */
  78203. function HardwareScalingOptimization(
  78204. /**
  78205. * Defines the priority of this optimization (0 by default which means first in the list)
  78206. */
  78207. priority,
  78208. /**
  78209. * Defines the maximum scale to use (2 by default)
  78210. */
  78211. maximumScale,
  78212. /**
  78213. * Defines the step to use between two passes (0.5 by default)
  78214. */
  78215. step) {
  78216. if (priority === void 0) { priority = 0; }
  78217. if (maximumScale === void 0) { maximumScale = 2; }
  78218. if (step === void 0) { step = 0.25; }
  78219. var _this = _super.call(this, priority) || this;
  78220. _this.priority = priority;
  78221. _this.maximumScale = maximumScale;
  78222. _this.step = step;
  78223. _this._currentScale = -1;
  78224. _this._directionOffset = 1;
  78225. return _this;
  78226. }
  78227. /**
  78228. * Gets a string describing the action executed by the current optimization
  78229. * @return description string
  78230. */
  78231. HardwareScalingOptimization.prototype.getDescription = function () {
  78232. return "Setting hardware scaling level to " + this._currentScale;
  78233. };
  78234. /**
  78235. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78236. * @param scene defines the current scene where to apply this optimization
  78237. * @param optimizer defines the current optimizer
  78238. * @returns true if everything that can be done was applied
  78239. */
  78240. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  78241. if (this._currentScale === -1) {
  78242. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  78243. if (this._currentScale > this.maximumScale) {
  78244. this._directionOffset = -1;
  78245. }
  78246. }
  78247. this._currentScale += this._directionOffset * this.step;
  78248. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  78249. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  78250. };
  78251. ;
  78252. return HardwareScalingOptimization;
  78253. }(SceneOptimization));
  78254. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  78255. /**
  78256. * Defines an optimization used to remove shadows
  78257. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78258. */
  78259. var ShadowsOptimization = /** @class */ (function (_super) {
  78260. __extends(ShadowsOptimization, _super);
  78261. function ShadowsOptimization() {
  78262. return _super !== null && _super.apply(this, arguments) || this;
  78263. }
  78264. /**
  78265. * Gets a string describing the action executed by the current optimization
  78266. * @return description string
  78267. */
  78268. ShadowsOptimization.prototype.getDescription = function () {
  78269. return "Turning shadows on/off";
  78270. };
  78271. /**
  78272. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78273. * @param scene defines the current scene where to apply this optimization
  78274. * @param optimizer defines the current optimizer
  78275. * @returns true if everything that can be done was applied
  78276. */
  78277. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  78278. scene.shadowsEnabled = optimizer.isInImprovementMode;
  78279. return true;
  78280. };
  78281. ;
  78282. return ShadowsOptimization;
  78283. }(SceneOptimization));
  78284. BABYLON.ShadowsOptimization = ShadowsOptimization;
  78285. /**
  78286. * Defines an optimization used to turn post-processes off
  78287. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78288. */
  78289. var PostProcessesOptimization = /** @class */ (function (_super) {
  78290. __extends(PostProcessesOptimization, _super);
  78291. function PostProcessesOptimization() {
  78292. return _super !== null && _super.apply(this, arguments) || this;
  78293. }
  78294. /**
  78295. * Gets a string describing the action executed by the current optimization
  78296. * @return description string
  78297. */
  78298. PostProcessesOptimization.prototype.getDescription = function () {
  78299. return "Turning post-processes on/off";
  78300. };
  78301. /**
  78302. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78303. * @param scene defines the current scene where to apply this optimization
  78304. * @param optimizer defines the current optimizer
  78305. * @returns true if everything that can be done was applied
  78306. */
  78307. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  78308. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  78309. return true;
  78310. };
  78311. ;
  78312. return PostProcessesOptimization;
  78313. }(SceneOptimization));
  78314. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  78315. /**
  78316. * Defines an optimization used to turn lens flares off
  78317. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78318. */
  78319. var LensFlaresOptimization = /** @class */ (function (_super) {
  78320. __extends(LensFlaresOptimization, _super);
  78321. function LensFlaresOptimization() {
  78322. return _super !== null && _super.apply(this, arguments) || this;
  78323. }
  78324. /**
  78325. * Gets a string describing the action executed by the current optimization
  78326. * @return description string
  78327. */
  78328. LensFlaresOptimization.prototype.getDescription = function () {
  78329. return "Turning lens flares on/off";
  78330. };
  78331. /**
  78332. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78333. * @param scene defines the current scene where to apply this optimization
  78334. * @param optimizer defines the current optimizer
  78335. * @returns true if everything that can be done was applied
  78336. */
  78337. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  78338. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  78339. return true;
  78340. };
  78341. ;
  78342. return LensFlaresOptimization;
  78343. }(SceneOptimization));
  78344. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  78345. /**
  78346. * Defines an optimization based on user defined callback.
  78347. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78348. */
  78349. var CustomOptimization = /** @class */ (function (_super) {
  78350. __extends(CustomOptimization, _super);
  78351. function CustomOptimization() {
  78352. return _super !== null && _super.apply(this, arguments) || this;
  78353. }
  78354. /**
  78355. * Gets a string describing the action executed by the current optimization
  78356. * @returns description string
  78357. */
  78358. CustomOptimization.prototype.getDescription = function () {
  78359. if (this.onGetDescription) {
  78360. return this.onGetDescription();
  78361. }
  78362. return "Running user defined callback";
  78363. };
  78364. /**
  78365. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78366. * @param scene defines the current scene where to apply this optimization
  78367. * @param optimizer defines the current optimizer
  78368. * @returns true if everything that can be done was applied
  78369. */
  78370. CustomOptimization.prototype.apply = function (scene, optimizer) {
  78371. if (this.onApply) {
  78372. return this.onApply(scene, optimizer);
  78373. }
  78374. return true;
  78375. };
  78376. ;
  78377. return CustomOptimization;
  78378. }(SceneOptimization));
  78379. BABYLON.CustomOptimization = CustomOptimization;
  78380. /**
  78381. * Defines an optimization used to turn particles off
  78382. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78383. */
  78384. var ParticlesOptimization = /** @class */ (function (_super) {
  78385. __extends(ParticlesOptimization, _super);
  78386. function ParticlesOptimization() {
  78387. return _super !== null && _super.apply(this, arguments) || this;
  78388. }
  78389. /**
  78390. * Gets a string describing the action executed by the current optimization
  78391. * @return description string
  78392. */
  78393. ParticlesOptimization.prototype.getDescription = function () {
  78394. return "Turning particles on/off";
  78395. };
  78396. /**
  78397. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78398. * @param scene defines the current scene where to apply this optimization
  78399. * @param optimizer defines the current optimizer
  78400. * @returns true if everything that can be done was applied
  78401. */
  78402. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  78403. scene.particlesEnabled = optimizer.isInImprovementMode;
  78404. return true;
  78405. };
  78406. ;
  78407. return ParticlesOptimization;
  78408. }(SceneOptimization));
  78409. BABYLON.ParticlesOptimization = ParticlesOptimization;
  78410. /**
  78411. * Defines an optimization used to turn render targets off
  78412. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78413. */
  78414. var RenderTargetsOptimization = /** @class */ (function (_super) {
  78415. __extends(RenderTargetsOptimization, _super);
  78416. function RenderTargetsOptimization() {
  78417. return _super !== null && _super.apply(this, arguments) || this;
  78418. }
  78419. /**
  78420. * Gets a string describing the action executed by the current optimization
  78421. * @return description string
  78422. */
  78423. RenderTargetsOptimization.prototype.getDescription = function () {
  78424. return "Turning render targets off";
  78425. };
  78426. /**
  78427. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78428. * @param scene defines the current scene where to apply this optimization
  78429. * @param optimizer defines the current optimizer
  78430. * @returns true if everything that can be done was applied
  78431. */
  78432. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  78433. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  78434. return true;
  78435. };
  78436. ;
  78437. return RenderTargetsOptimization;
  78438. }(SceneOptimization));
  78439. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  78440. /**
  78441. * Defines an optimization used to merge meshes with compatible materials
  78442. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78443. */
  78444. var MergeMeshesOptimization = /** @class */ (function (_super) {
  78445. __extends(MergeMeshesOptimization, _super);
  78446. function MergeMeshesOptimization() {
  78447. var _this = _super !== null && _super.apply(this, arguments) || this;
  78448. _this._canBeMerged = function (abstractMesh) {
  78449. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  78450. return false;
  78451. }
  78452. var mesh = abstractMesh;
  78453. if (!mesh.isVisible || !mesh.isEnabled()) {
  78454. return false;
  78455. }
  78456. if (mesh.instances.length > 0) {
  78457. return false;
  78458. }
  78459. if (mesh.skeleton || mesh.hasLODLevels) {
  78460. return false;
  78461. }
  78462. if (mesh.parent) {
  78463. return false;
  78464. }
  78465. return true;
  78466. };
  78467. return _this;
  78468. }
  78469. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  78470. /**
  78471. * Gets or sets a boolean which defines if optimization octree has to be updated
  78472. */
  78473. get: function () {
  78474. return MergeMeshesOptimization._UpdateSelectionTree;
  78475. },
  78476. /**
  78477. * Gets or sets a boolean which defines if optimization octree has to be updated
  78478. */
  78479. set: function (value) {
  78480. MergeMeshesOptimization._UpdateSelectionTree = value;
  78481. },
  78482. enumerable: true,
  78483. configurable: true
  78484. });
  78485. /**
  78486. * Gets a string describing the action executed by the current optimization
  78487. * @return description string
  78488. */
  78489. MergeMeshesOptimization.prototype.getDescription = function () {
  78490. return "Merging similar meshes together";
  78491. };
  78492. /**
  78493. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78494. * @param scene defines the current scene where to apply this optimization
  78495. * @param optimizer defines the current optimizer
  78496. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  78497. * @returns true if everything that can be done was applied
  78498. */
  78499. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  78500. var globalPool = scene.meshes.slice(0);
  78501. var globalLength = globalPool.length;
  78502. for (var index = 0; index < globalLength; index++) {
  78503. var currentPool = new Array();
  78504. var current = globalPool[index];
  78505. // Checks
  78506. if (!this._canBeMerged(current)) {
  78507. continue;
  78508. }
  78509. currentPool.push(current);
  78510. // Find compatible meshes
  78511. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  78512. var otherMesh = globalPool[subIndex];
  78513. if (!this._canBeMerged(otherMesh)) {
  78514. continue;
  78515. }
  78516. if (otherMesh.material !== current.material) {
  78517. continue;
  78518. }
  78519. if (otherMesh.checkCollisions !== current.checkCollisions) {
  78520. continue;
  78521. }
  78522. currentPool.push(otherMesh);
  78523. globalLength--;
  78524. globalPool.splice(subIndex, 1);
  78525. subIndex--;
  78526. }
  78527. if (currentPool.length < 2) {
  78528. continue;
  78529. }
  78530. // Merge meshes
  78531. BABYLON.Mesh.MergeMeshes(currentPool);
  78532. }
  78533. if (updateSelectionTree != undefined) {
  78534. if (updateSelectionTree) {
  78535. scene.createOrUpdateSelectionOctree();
  78536. }
  78537. }
  78538. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  78539. scene.createOrUpdateSelectionOctree();
  78540. }
  78541. return true;
  78542. };
  78543. ;
  78544. MergeMeshesOptimization._UpdateSelectionTree = false;
  78545. return MergeMeshesOptimization;
  78546. }(SceneOptimization));
  78547. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  78548. /**
  78549. * Defines a list of options used by SceneOptimizer
  78550. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78551. */
  78552. var SceneOptimizerOptions = /** @class */ (function () {
  78553. /**
  78554. * Creates a new list of options used by SceneOptimizer
  78555. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  78556. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  78557. */
  78558. function SceneOptimizerOptions(
  78559. /**
  78560. * Defines the target frame rate to reach (60 by default)
  78561. */
  78562. targetFrameRate,
  78563. /**
  78564. * Defines the interval between two checkes (2000ms by default)
  78565. */
  78566. trackerDuration) {
  78567. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  78568. if (trackerDuration === void 0) { trackerDuration = 2000; }
  78569. this.targetFrameRate = targetFrameRate;
  78570. this.trackerDuration = trackerDuration;
  78571. /**
  78572. * Gets the list of optimizations to apply
  78573. */
  78574. this.optimizations = new Array();
  78575. }
  78576. /**
  78577. * Add a new optimization
  78578. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  78579. * @returns the current SceneOptimizerOptions
  78580. */
  78581. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  78582. this.optimizations.push(optimization);
  78583. return this;
  78584. };
  78585. /**
  78586. * Add a new custom optimization
  78587. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  78588. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  78589. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78590. * @returns the current SceneOptimizerOptions
  78591. */
  78592. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  78593. if (priority === void 0) { priority = 0; }
  78594. var optimization = new CustomOptimization(priority);
  78595. optimization.onApply = onApply;
  78596. optimization.onGetDescription = onGetDescription;
  78597. this.optimizations.push(optimization);
  78598. return this;
  78599. };
  78600. /**
  78601. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  78602. * @param targetFrameRate defines the target frame rate (60 by default)
  78603. * @returns a SceneOptimizerOptions object
  78604. */
  78605. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  78606. var result = new SceneOptimizerOptions(targetFrameRate);
  78607. var priority = 0;
  78608. result.addOptimization(new MergeMeshesOptimization(priority));
  78609. result.addOptimization(new ShadowsOptimization(priority));
  78610. result.addOptimization(new LensFlaresOptimization(priority));
  78611. // Next priority
  78612. priority++;
  78613. result.addOptimization(new PostProcessesOptimization(priority));
  78614. result.addOptimization(new ParticlesOptimization(priority));
  78615. // Next priority
  78616. priority++;
  78617. result.addOptimization(new TextureOptimization(priority, 1024));
  78618. return result;
  78619. };
  78620. /**
  78621. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  78622. * @param targetFrameRate defines the target frame rate (60 by default)
  78623. * @returns a SceneOptimizerOptions object
  78624. */
  78625. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  78626. var result = new SceneOptimizerOptions(targetFrameRate);
  78627. var priority = 0;
  78628. result.addOptimization(new MergeMeshesOptimization(priority));
  78629. result.addOptimization(new ShadowsOptimization(priority));
  78630. result.addOptimization(new LensFlaresOptimization(priority));
  78631. // Next priority
  78632. priority++;
  78633. result.addOptimization(new PostProcessesOptimization(priority));
  78634. result.addOptimization(new ParticlesOptimization(priority));
  78635. // Next priority
  78636. priority++;
  78637. result.addOptimization(new TextureOptimization(priority, 512));
  78638. // Next priority
  78639. priority++;
  78640. result.addOptimization(new RenderTargetsOptimization(priority));
  78641. // Next priority
  78642. priority++;
  78643. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  78644. return result;
  78645. };
  78646. /**
  78647. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  78648. * @param targetFrameRate defines the target frame rate (60 by default)
  78649. * @returns a SceneOptimizerOptions object
  78650. */
  78651. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  78652. var result = new SceneOptimizerOptions(targetFrameRate);
  78653. var priority = 0;
  78654. result.addOptimization(new MergeMeshesOptimization(priority));
  78655. result.addOptimization(new ShadowsOptimization(priority));
  78656. result.addOptimization(new LensFlaresOptimization(priority));
  78657. // Next priority
  78658. priority++;
  78659. result.addOptimization(new PostProcessesOptimization(priority));
  78660. result.addOptimization(new ParticlesOptimization(priority));
  78661. // Next priority
  78662. priority++;
  78663. result.addOptimization(new TextureOptimization(priority, 256));
  78664. // Next priority
  78665. priority++;
  78666. result.addOptimization(new RenderTargetsOptimization(priority));
  78667. // Next priority
  78668. priority++;
  78669. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  78670. return result;
  78671. };
  78672. return SceneOptimizerOptions;
  78673. }());
  78674. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  78675. /**
  78676. * Class used to run optimizations in order to reach a target frame rate
  78677. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78678. */
  78679. var SceneOptimizer = /** @class */ (function () {
  78680. /**
  78681. * Creates a new SceneOptimizer
  78682. * @param scene defines the scene to work on
  78683. * @param options defines the options to use with the SceneOptimizer
  78684. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  78685. * @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)
  78686. */
  78687. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  78688. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  78689. if (improvementMode === void 0) { improvementMode = false; }
  78690. var _this = this;
  78691. this._isRunning = false;
  78692. this._currentPriorityLevel = 0;
  78693. this._targetFrameRate = 60;
  78694. this._trackerDuration = 2000;
  78695. this._currentFrameRate = 0;
  78696. this._improvementMode = false;
  78697. /**
  78698. * Defines an observable called when the optimizer reaches the target frame rate
  78699. */
  78700. this.onSuccessObservable = new BABYLON.Observable();
  78701. /**
  78702. * Defines an observable called when the optimizer enables an optimization
  78703. */
  78704. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  78705. /**
  78706. * Defines an observable called when the optimizer is not able to reach the target frame rate
  78707. */
  78708. this.onFailureObservable = new BABYLON.Observable();
  78709. if (!options) {
  78710. this._options = new SceneOptimizerOptions();
  78711. }
  78712. else {
  78713. this._options = options;
  78714. }
  78715. if (this._options.targetFrameRate) {
  78716. this._targetFrameRate = this._options.targetFrameRate;
  78717. }
  78718. if (this._options.trackerDuration) {
  78719. this._trackerDuration = this._options.trackerDuration;
  78720. }
  78721. if (autoGeneratePriorities) {
  78722. var priority = 0;
  78723. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  78724. var optim = _a[_i];
  78725. optim.priority = priority++;
  78726. }
  78727. }
  78728. this._improvementMode = improvementMode;
  78729. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78730. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  78731. _this._sceneDisposeObserver = null;
  78732. _this.dispose();
  78733. });
  78734. }
  78735. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  78736. /**
  78737. * Gets a boolean indicating if the optimizer is in improvement mode
  78738. */
  78739. get: function () {
  78740. return this._improvementMode;
  78741. },
  78742. enumerable: true,
  78743. configurable: true
  78744. });
  78745. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  78746. /**
  78747. * Gets the current priority level (0 at start)
  78748. */
  78749. get: function () {
  78750. return this._currentPriorityLevel;
  78751. },
  78752. enumerable: true,
  78753. configurable: true
  78754. });
  78755. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  78756. /**
  78757. * Gets the current frame rate checked by the SceneOptimizer
  78758. */
  78759. get: function () {
  78760. return this._currentFrameRate;
  78761. },
  78762. enumerable: true,
  78763. configurable: true
  78764. });
  78765. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  78766. /**
  78767. * Gets or sets the current target frame rate (60 by default)
  78768. */
  78769. get: function () {
  78770. return this._targetFrameRate;
  78771. },
  78772. /**
  78773. * Gets or sets the current target frame rate (60 by default)
  78774. */
  78775. set: function (value) {
  78776. this._targetFrameRate = value;
  78777. },
  78778. enumerable: true,
  78779. configurable: true
  78780. });
  78781. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  78782. /**
  78783. * Gets or sets the current interval between two checks (every 2000ms by default)
  78784. */
  78785. get: function () {
  78786. return this._trackerDuration;
  78787. },
  78788. /**
  78789. * Gets or sets the current interval between two checks (every 2000ms by default)
  78790. */
  78791. set: function (value) {
  78792. this._trackerDuration = value;
  78793. },
  78794. enumerable: true,
  78795. configurable: true
  78796. });
  78797. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  78798. /**
  78799. * Gets the list of active optimizations
  78800. */
  78801. get: function () {
  78802. return this._options.optimizations;
  78803. },
  78804. enumerable: true,
  78805. configurable: true
  78806. });
  78807. /**
  78808. * Stops the current optimizer
  78809. */
  78810. SceneOptimizer.prototype.stop = function () {
  78811. this._isRunning = false;
  78812. };
  78813. /**
  78814. * Reset the optimizer to initial step (current priority level = 0)
  78815. */
  78816. SceneOptimizer.prototype.reset = function () {
  78817. this._currentPriorityLevel = 0;
  78818. };
  78819. /**
  78820. * Start the optimizer. By default it will try to reach a specific framerate
  78821. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  78822. */
  78823. SceneOptimizer.prototype.start = function () {
  78824. var _this = this;
  78825. if (this._isRunning) {
  78826. return;
  78827. }
  78828. this._isRunning = true;
  78829. // Let's wait for the scene to be ready before running our check
  78830. this._scene.executeWhenReady(function () {
  78831. setTimeout(function () {
  78832. _this._checkCurrentState();
  78833. }, _this._trackerDuration);
  78834. });
  78835. };
  78836. SceneOptimizer.prototype._checkCurrentState = function () {
  78837. var _this = this;
  78838. if (!this._isRunning) {
  78839. return;
  78840. }
  78841. var scene = this._scene;
  78842. var options = this._options;
  78843. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  78844. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  78845. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  78846. this._isRunning = false;
  78847. this.onSuccessObservable.notifyObservers(this);
  78848. return;
  78849. }
  78850. // Apply current level of optimizations
  78851. var allDone = true;
  78852. var noOptimizationApplied = true;
  78853. for (var index = 0; index < options.optimizations.length; index++) {
  78854. var optimization = options.optimizations[index];
  78855. if (optimization.priority === this._currentPriorityLevel) {
  78856. noOptimizationApplied = false;
  78857. allDone = allDone && optimization.apply(scene, this);
  78858. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  78859. }
  78860. }
  78861. // If no optimization was applied, this is a failure :(
  78862. if (noOptimizationApplied) {
  78863. this._isRunning = false;
  78864. this.onFailureObservable.notifyObservers(this);
  78865. return;
  78866. }
  78867. // If all optimizations were done, move to next level
  78868. if (allDone) {
  78869. this._currentPriorityLevel++;
  78870. }
  78871. // Let's the system running for a specific amount of time before checking FPS
  78872. scene.executeWhenReady(function () {
  78873. setTimeout(function () {
  78874. _this._checkCurrentState();
  78875. }, _this._trackerDuration);
  78876. });
  78877. };
  78878. /**
  78879. * Release all resources
  78880. */
  78881. SceneOptimizer.prototype.dispose = function () {
  78882. this.stop();
  78883. this.onSuccessObservable.clear();
  78884. this.onFailureObservable.clear();
  78885. this.onNewOptimizationAppliedObservable.clear();
  78886. if (this._sceneDisposeObserver) {
  78887. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  78888. }
  78889. };
  78890. /**
  78891. * Helper function to create a SceneOptimizer with one single line of code
  78892. * @param scene defines the scene to work on
  78893. * @param options defines the options to use with the SceneOptimizer
  78894. * @param onSuccess defines a callback to call on success
  78895. * @param onFailure defines a callback to call on failure
  78896. * @returns the new SceneOptimizer object
  78897. */
  78898. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  78899. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  78900. if (onSuccess) {
  78901. optimizer.onSuccessObservable.add(function () {
  78902. onSuccess();
  78903. });
  78904. }
  78905. if (onFailure) {
  78906. optimizer.onFailureObservable.add(function () {
  78907. onFailure();
  78908. });
  78909. }
  78910. optimizer.start();
  78911. return optimizer;
  78912. };
  78913. return SceneOptimizer;
  78914. }());
  78915. BABYLON.SceneOptimizer = SceneOptimizer;
  78916. })(BABYLON || (BABYLON = {}));
  78917. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  78918. var BABYLON;
  78919. (function (BABYLON) {
  78920. var OutlineRenderer = /** @class */ (function () {
  78921. function OutlineRenderer(scene) {
  78922. this.zOffset = 1;
  78923. this._scene = scene;
  78924. }
  78925. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  78926. var _this = this;
  78927. if (useOverlay === void 0) { useOverlay = false; }
  78928. var scene = this._scene;
  78929. var engine = this._scene.getEngine();
  78930. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  78931. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  78932. return;
  78933. }
  78934. var mesh = subMesh.getRenderingMesh();
  78935. var material = subMesh.getMaterial();
  78936. if (!material || !scene.activeCamera) {
  78937. return;
  78938. }
  78939. engine.enableEffect(this._effect);
  78940. // Logarithmic depth
  78941. if (material.useLogarithmicDepth) {
  78942. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  78943. }
  78944. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  78945. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  78946. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78947. // Bones
  78948. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78949. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78950. }
  78951. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  78952. // Alpha test
  78953. if (material && material.needAlphaTesting()) {
  78954. var alphaTexture = material.getAlphaTestTexture();
  78955. if (alphaTexture) {
  78956. this._effect.setTexture("diffuseSampler", alphaTexture);
  78957. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78958. }
  78959. }
  78960. engine.setZOffset(-this.zOffset);
  78961. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  78962. engine.setZOffset(0);
  78963. };
  78964. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  78965. var defines = [];
  78966. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78967. var mesh = subMesh.getMesh();
  78968. var material = subMesh.getMaterial();
  78969. if (material) {
  78970. // Alpha test
  78971. if (material.needAlphaTesting()) {
  78972. defines.push("#define ALPHATEST");
  78973. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78974. attribs.push(BABYLON.VertexBuffer.UVKind);
  78975. defines.push("#define UV1");
  78976. }
  78977. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78978. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78979. defines.push("#define UV2");
  78980. }
  78981. }
  78982. //Logarithmic depth
  78983. if (material.useLogarithmicDepth) {
  78984. defines.push("#define LOGARITHMICDEPTH");
  78985. }
  78986. }
  78987. // Bones
  78988. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78989. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78990. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78991. if (mesh.numBoneInfluencers > 4) {
  78992. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78993. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78994. }
  78995. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78996. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78997. }
  78998. else {
  78999. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79000. }
  79001. // Instances
  79002. if (useInstances) {
  79003. defines.push("#define INSTANCES");
  79004. attribs.push("world0");
  79005. attribs.push("world1");
  79006. attribs.push("world2");
  79007. attribs.push("world3");
  79008. }
  79009. // Get correct effect
  79010. var join = defines.join("\n");
  79011. if (this._cachedDefines !== join) {
  79012. this._cachedDefines = join;
  79013. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  79014. }
  79015. return this._effect.isReady();
  79016. };
  79017. return OutlineRenderer;
  79018. }());
  79019. BABYLON.OutlineRenderer = OutlineRenderer;
  79020. })(BABYLON || (BABYLON = {}));
  79021. //# sourceMappingURL=babylon.outlineRenderer.js.map
  79022. var BABYLON;
  79023. (function (BABYLON) {
  79024. var FaceAdjacencies = /** @class */ (function () {
  79025. function FaceAdjacencies() {
  79026. this.edges = new Array();
  79027. this.edgesConnectedCount = 0;
  79028. }
  79029. return FaceAdjacencies;
  79030. }());
  79031. var EdgesRenderer = /** @class */ (function () {
  79032. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  79033. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  79034. if (epsilon === void 0) { epsilon = 0.95; }
  79035. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  79036. this.edgesWidthScalerForOrthographic = 1000.0;
  79037. this.edgesWidthScalerForPerspective = 50.0;
  79038. this._linesPositions = new Array();
  79039. this._linesNormals = new Array();
  79040. this._linesIndices = new Array();
  79041. this._buffers = {};
  79042. this._checkVerticesInsteadOfIndices = false;
  79043. this._source = source;
  79044. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  79045. this._epsilon = epsilon;
  79046. this._prepareRessources();
  79047. this._generateEdgesLines();
  79048. }
  79049. EdgesRenderer.prototype._prepareRessources = function () {
  79050. if (this._lineShader) {
  79051. return;
  79052. }
  79053. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  79054. attributes: ["position", "normal"],
  79055. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  79056. });
  79057. this._lineShader.disableDepthWrite = true;
  79058. this._lineShader.backFaceCulling = false;
  79059. };
  79060. EdgesRenderer.prototype._rebuild = function () {
  79061. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  79062. if (buffer) {
  79063. buffer._rebuild();
  79064. }
  79065. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  79066. if (buffer) {
  79067. buffer._rebuild();
  79068. }
  79069. var scene = this._source.getScene();
  79070. var engine = scene.getEngine();
  79071. this._ib = engine.createIndexBuffer(this._linesIndices);
  79072. };
  79073. EdgesRenderer.prototype.dispose = function () {
  79074. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  79075. if (buffer) {
  79076. buffer.dispose();
  79077. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  79078. }
  79079. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  79080. if (buffer) {
  79081. buffer.dispose();
  79082. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  79083. }
  79084. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  79085. this._lineShader.dispose();
  79086. };
  79087. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  79088. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  79089. return 0;
  79090. }
  79091. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  79092. return 1;
  79093. }
  79094. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  79095. return 2;
  79096. }
  79097. return -1;
  79098. };
  79099. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  79100. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  79101. return 0;
  79102. }
  79103. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  79104. return 1;
  79105. }
  79106. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  79107. return 2;
  79108. }
  79109. return -1;
  79110. };
  79111. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  79112. var needToCreateLine;
  79113. if (edge === undefined) {
  79114. needToCreateLine = true;
  79115. }
  79116. else {
  79117. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  79118. needToCreateLine = dotProduct < this._epsilon;
  79119. }
  79120. if (needToCreateLine) {
  79121. var offset = this._linesPositions.length / 3;
  79122. var normal = p0.subtract(p1);
  79123. normal.normalize();
  79124. // Positions
  79125. this._linesPositions.push(p0.x);
  79126. this._linesPositions.push(p0.y);
  79127. this._linesPositions.push(p0.z);
  79128. this._linesPositions.push(p0.x);
  79129. this._linesPositions.push(p0.y);
  79130. this._linesPositions.push(p0.z);
  79131. this._linesPositions.push(p1.x);
  79132. this._linesPositions.push(p1.y);
  79133. this._linesPositions.push(p1.z);
  79134. this._linesPositions.push(p1.x);
  79135. this._linesPositions.push(p1.y);
  79136. this._linesPositions.push(p1.z);
  79137. // Normals
  79138. this._linesNormals.push(p1.x);
  79139. this._linesNormals.push(p1.y);
  79140. this._linesNormals.push(p1.z);
  79141. this._linesNormals.push(-1);
  79142. this._linesNormals.push(p1.x);
  79143. this._linesNormals.push(p1.y);
  79144. this._linesNormals.push(p1.z);
  79145. this._linesNormals.push(1);
  79146. this._linesNormals.push(p0.x);
  79147. this._linesNormals.push(p0.y);
  79148. this._linesNormals.push(p0.z);
  79149. this._linesNormals.push(-1);
  79150. this._linesNormals.push(p0.x);
  79151. this._linesNormals.push(p0.y);
  79152. this._linesNormals.push(p0.z);
  79153. this._linesNormals.push(1);
  79154. // Indices
  79155. this._linesIndices.push(offset);
  79156. this._linesIndices.push(offset + 1);
  79157. this._linesIndices.push(offset + 2);
  79158. this._linesIndices.push(offset);
  79159. this._linesIndices.push(offset + 2);
  79160. this._linesIndices.push(offset + 3);
  79161. }
  79162. };
  79163. EdgesRenderer.prototype._generateEdgesLines = function () {
  79164. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  79165. var indices = this._source.getIndices();
  79166. if (!indices || !positions) {
  79167. return;
  79168. }
  79169. // First let's find adjacencies
  79170. var adjacencies = new Array();
  79171. var faceNormals = new Array();
  79172. var index;
  79173. var faceAdjacencies;
  79174. // Prepare faces
  79175. for (index = 0; index < indices.length; index += 3) {
  79176. faceAdjacencies = new FaceAdjacencies();
  79177. var p0Index = indices[index];
  79178. var p1Index = indices[index + 1];
  79179. var p2Index = indices[index + 2];
  79180. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  79181. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  79182. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  79183. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  79184. faceNormal.normalize();
  79185. faceNormals.push(faceNormal);
  79186. adjacencies.push(faceAdjacencies);
  79187. }
  79188. // Scan
  79189. for (index = 0; index < adjacencies.length; index++) {
  79190. faceAdjacencies = adjacencies[index];
  79191. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  79192. var otherFaceAdjacencies = adjacencies[otherIndex];
  79193. if (faceAdjacencies.edgesConnectedCount === 3) {
  79194. break;
  79195. }
  79196. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  79197. continue;
  79198. }
  79199. var otherP0 = indices[otherIndex * 3];
  79200. var otherP1 = indices[otherIndex * 3 + 1];
  79201. var otherP2 = indices[otherIndex * 3 + 2];
  79202. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  79203. var otherEdgeIndex = 0;
  79204. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  79205. continue;
  79206. }
  79207. switch (edgeIndex) {
  79208. case 0:
  79209. if (this._checkVerticesInsteadOfIndices) {
  79210. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79211. }
  79212. else {
  79213. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  79214. }
  79215. break;
  79216. case 1:
  79217. if (this._checkVerticesInsteadOfIndices) {
  79218. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79219. }
  79220. else {
  79221. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  79222. }
  79223. break;
  79224. case 2:
  79225. if (this._checkVerticesInsteadOfIndices) {
  79226. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  79227. }
  79228. else {
  79229. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  79230. }
  79231. break;
  79232. }
  79233. if (otherEdgeIndex === -1) {
  79234. continue;
  79235. }
  79236. faceAdjacencies.edges[edgeIndex] = otherIndex;
  79237. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  79238. faceAdjacencies.edgesConnectedCount++;
  79239. otherFaceAdjacencies.edgesConnectedCount++;
  79240. if (faceAdjacencies.edgesConnectedCount === 3) {
  79241. break;
  79242. }
  79243. }
  79244. }
  79245. }
  79246. // Create lines
  79247. for (index = 0; index < adjacencies.length; index++) {
  79248. // 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
  79249. var current = adjacencies[index];
  79250. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  79251. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  79252. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  79253. }
  79254. // Merge into a single mesh
  79255. var engine = this._source.getScene().getEngine();
  79256. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  79257. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  79258. this._ib = engine.createIndexBuffer(this._linesIndices);
  79259. this._indicesCount = this._linesIndices.length;
  79260. };
  79261. EdgesRenderer.prototype.render = function () {
  79262. var scene = this._source.getScene();
  79263. if (!this._lineShader.isReady() || !scene.activeCamera) {
  79264. return;
  79265. }
  79266. var engine = scene.getEngine();
  79267. this._lineShader._preBind();
  79268. // VBOs
  79269. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  79270. scene.resetCachedMaterial();
  79271. this._lineShader.setColor4("color", this._source.edgesColor);
  79272. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  79273. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  79274. }
  79275. else {
  79276. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  79277. }
  79278. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  79279. this._lineShader.bind(this._source.getWorldMatrix());
  79280. // Draw order
  79281. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  79282. this._lineShader.unbind();
  79283. engine.setDepthWrite(true);
  79284. };
  79285. return EdgesRenderer;
  79286. }());
  79287. BABYLON.EdgesRenderer = EdgesRenderer;
  79288. })(BABYLON || (BABYLON = {}));
  79289. //# sourceMappingURL=babylon.edgesRenderer.js.map
  79290. var BABYLON;
  79291. (function (BABYLON) {
  79292. /**
  79293. * Special Glow Blur post process only blurring the alpha channel
  79294. * It enforces keeping the most luminous color in the color channel.
  79295. */
  79296. var GlowBlurPostProcess = /** @class */ (function (_super) {
  79297. __extends(GlowBlurPostProcess, _super);
  79298. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  79299. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79300. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  79301. _this.direction = direction;
  79302. _this.kernel = kernel;
  79303. _this.onApplyObservable.add(function (effect) {
  79304. effect.setFloat2("screenSize", _this.width, _this.height);
  79305. effect.setVector2("direction", _this.direction);
  79306. effect.setFloat("blurWidth", _this.kernel);
  79307. });
  79308. return _this;
  79309. }
  79310. return GlowBlurPostProcess;
  79311. }(BABYLON.PostProcess));
  79312. /**
  79313. * The highlight layer Helps adding a glow effect around a mesh.
  79314. *
  79315. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  79316. * glowy meshes to your scene.
  79317. *
  79318. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  79319. */
  79320. var HighlightLayer = /** @class */ (function () {
  79321. /**
  79322. * Instantiates a new highlight Layer and references it to the scene..
  79323. * @param name The name of the layer
  79324. * @param scene The scene to use the layer in
  79325. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  79326. */
  79327. function HighlightLayer(name, scene, options) {
  79328. this.name = name;
  79329. this._vertexBuffers = {};
  79330. this._mainTextureDesiredSize = { width: 0, height: 0 };
  79331. this._meshes = {};
  79332. this._maxSize = 0;
  79333. this._shouldRender = false;
  79334. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  79335. this._excludedMeshes = {};
  79336. /**
  79337. * Specifies whether or not the inner glow is ACTIVE in the layer.
  79338. */
  79339. this.innerGlow = true;
  79340. /**
  79341. * Specifies whether or not the outer glow is ACTIVE in the layer.
  79342. */
  79343. this.outerGlow = true;
  79344. /**
  79345. * Specifies wether the highlight layer is enabled or not.
  79346. */
  79347. this.isEnabled = true;
  79348. /**
  79349. * An event triggered when the highlight layer has been disposed.
  79350. * @type {BABYLON.Observable}
  79351. */
  79352. this.onDisposeObservable = new BABYLON.Observable();
  79353. /**
  79354. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  79355. * @type {BABYLON.Observable}
  79356. */
  79357. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  79358. /**
  79359. * An event triggered when the highlight layer is being blurred.
  79360. * @type {BABYLON.Observable}
  79361. */
  79362. this.onBeforeBlurObservable = new BABYLON.Observable();
  79363. /**
  79364. * An event triggered when the highlight layer has been blurred.
  79365. * @type {BABYLON.Observable}
  79366. */
  79367. this.onAfterBlurObservable = new BABYLON.Observable();
  79368. /**
  79369. * An event triggered when the glowing blurred texture is being merged in the scene.
  79370. * @type {BABYLON.Observable}
  79371. */
  79372. this.onBeforeComposeObservable = new BABYLON.Observable();
  79373. /**
  79374. * An event triggered when the glowing blurred texture has been merged in the scene.
  79375. * @type {BABYLON.Observable}
  79376. */
  79377. this.onAfterComposeObservable = new BABYLON.Observable();
  79378. /**
  79379. * An event triggered when the highlight layer changes its size.
  79380. * @type {BABYLON.Observable}
  79381. */
  79382. this.onSizeChangedObservable = new BABYLON.Observable();
  79383. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79384. var engine = scene.getEngine();
  79385. this._engine = engine;
  79386. this._maxSize = this._engine.getCaps().maxTextureSize;
  79387. this._scene.highlightLayers.push(this);
  79388. // Warn on stencil.
  79389. if (!this._engine.isStencilEnable) {
  79390. 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 }");
  79391. }
  79392. // Adapt options
  79393. this._options = options || {
  79394. mainTextureRatio: 0.5,
  79395. blurTextureSizeRatio: 0.5,
  79396. blurHorizontalSize: 1.0,
  79397. blurVerticalSize: 1.0,
  79398. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  79399. camera: null
  79400. };
  79401. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  79402. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  79403. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  79404. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  79405. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  79406. // VBO
  79407. var vertices = [];
  79408. vertices.push(1, 1);
  79409. vertices.push(-1, 1);
  79410. vertices.push(-1, -1);
  79411. vertices.push(1, -1);
  79412. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79413. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  79414. this._createIndexBuffer();
  79415. // Effect
  79416. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  79417. // Render target
  79418. this.setMainTextureSize();
  79419. // Create Textures and post processes
  79420. this.createTextureAndPostProcesses();
  79421. }
  79422. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  79423. /**
  79424. * Gets the horizontal size of the blur.
  79425. */
  79426. get: function () {
  79427. return this._horizontalBlurPostprocess.kernel;
  79428. },
  79429. /**
  79430. * Specifies the horizontal size of the blur.
  79431. */
  79432. set: function (value) {
  79433. this._horizontalBlurPostprocess.kernel = value;
  79434. },
  79435. enumerable: true,
  79436. configurable: true
  79437. });
  79438. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  79439. /**
  79440. * Gets the vertical size of the blur.
  79441. */
  79442. get: function () {
  79443. return this._verticalBlurPostprocess.kernel;
  79444. },
  79445. /**
  79446. * Specifies the vertical size of the blur.
  79447. */
  79448. set: function (value) {
  79449. this._verticalBlurPostprocess.kernel = value;
  79450. },
  79451. enumerable: true,
  79452. configurable: true
  79453. });
  79454. Object.defineProperty(HighlightLayer.prototype, "camera", {
  79455. /**
  79456. * Gets the camera attached to the layer.
  79457. */
  79458. get: function () {
  79459. return this._options.camera;
  79460. },
  79461. enumerable: true,
  79462. configurable: true
  79463. });
  79464. HighlightLayer.prototype._createIndexBuffer = function () {
  79465. var engine = this._scene.getEngine();
  79466. // Indices
  79467. var indices = [];
  79468. indices.push(0);
  79469. indices.push(1);
  79470. indices.push(2);
  79471. indices.push(0);
  79472. indices.push(2);
  79473. indices.push(3);
  79474. this._indexBuffer = engine.createIndexBuffer(indices);
  79475. };
  79476. HighlightLayer.prototype._rebuild = function () {
  79477. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79478. if (vb) {
  79479. vb._rebuild();
  79480. }
  79481. this._createIndexBuffer();
  79482. };
  79483. /**
  79484. * Creates the render target textures and post processes used in the highlight layer.
  79485. */
  79486. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  79487. var _this = this;
  79488. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  79489. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  79490. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  79491. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  79492. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  79493. width: this._mainTextureDesiredSize.width,
  79494. height: this._mainTextureDesiredSize.height
  79495. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79496. this._mainTexture.activeCamera = this._options.camera;
  79497. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79498. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79499. this._mainTexture.anisotropicFilteringLevel = 1;
  79500. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79501. this._mainTexture.renderParticles = false;
  79502. this._mainTexture.renderList = null;
  79503. this._mainTexture.ignoreCameraViewport = true;
  79504. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  79505. width: blurTextureWidth,
  79506. height: blurTextureHeight
  79507. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79508. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79509. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79510. this._blurTexture.anisotropicFilteringLevel = 16;
  79511. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79512. this._blurTexture.renderParticles = false;
  79513. this._blurTexture.ignoreCameraViewport = true;
  79514. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79515. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  79516. effect.setTexture("textureSampler", _this._mainTexture);
  79517. });
  79518. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  79519. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79520. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  79521. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79522. });
  79523. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79524. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  79525. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79526. });
  79527. }
  79528. else {
  79529. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79530. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  79531. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79532. });
  79533. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79534. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  79535. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79536. });
  79537. }
  79538. this._mainTexture.onAfterUnbindObservable.add(function () {
  79539. _this.onBeforeBlurObservable.notifyObservers(_this);
  79540. var internalTexture = _this._blurTexture.getInternalTexture();
  79541. if (internalTexture) {
  79542. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  79543. }
  79544. _this.onAfterBlurObservable.notifyObservers(_this);
  79545. });
  79546. // Custom render function
  79547. var renderSubMesh = function (subMesh) {
  79548. if (!_this._meshes) {
  79549. return;
  79550. }
  79551. var material = subMesh.getMaterial();
  79552. var mesh = subMesh.getRenderingMesh();
  79553. var scene = _this._scene;
  79554. var engine = scene.getEngine();
  79555. if (!material) {
  79556. return;
  79557. }
  79558. // Do not block in blend mode.
  79559. if (material.needAlphaBlendingForMesh(mesh)) {
  79560. return;
  79561. }
  79562. // Culling
  79563. engine.setState(material.backFaceCulling);
  79564. // Managing instances
  79565. var batch = mesh._getInstancesRenderList(subMesh._id);
  79566. if (batch.mustReturn) {
  79567. return;
  79568. }
  79569. // Excluded Mesh
  79570. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  79571. return;
  79572. }
  79573. ;
  79574. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  79575. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  79576. var emissiveTexture = null;
  79577. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  79578. emissiveTexture = material.emissiveTexture;
  79579. }
  79580. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  79581. engine.enableEffect(_this._glowMapGenerationEffect);
  79582. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  79583. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  79584. if (highlightLayerMesh) {
  79585. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  79586. }
  79587. else {
  79588. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  79589. }
  79590. // Alpha test
  79591. if (material && material.needAlphaTesting()) {
  79592. var alphaTexture = material.getAlphaTestTexture();
  79593. if (alphaTexture) {
  79594. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  79595. var textureMatrix = alphaTexture.getTextureMatrix();
  79596. if (textureMatrix) {
  79597. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  79598. }
  79599. }
  79600. }
  79601. // Glow emissive only
  79602. if (emissiveTexture) {
  79603. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  79604. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  79605. }
  79606. // Bones
  79607. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79608. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79609. }
  79610. // Draw
  79611. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  79612. }
  79613. else {
  79614. // Need to reset refresh rate of the shadowMap
  79615. _this._mainTexture.resetRefreshCounter();
  79616. }
  79617. };
  79618. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79619. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  79620. var index;
  79621. var engine = _this._scene.getEngine();
  79622. if (depthOnlySubMeshes.length) {
  79623. engine.setColorWrite(false);
  79624. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79625. renderSubMesh(depthOnlySubMeshes.data[index]);
  79626. }
  79627. engine.setColorWrite(true);
  79628. }
  79629. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79630. renderSubMesh(opaqueSubMeshes.data[index]);
  79631. }
  79632. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79633. renderSubMesh(alphaTestSubMeshes.data[index]);
  79634. }
  79635. for (index = 0; index < transparentSubMeshes.length; index++) {
  79636. renderSubMesh(transparentSubMeshes.data[index]);
  79637. }
  79638. };
  79639. this._mainTexture.onClearObservable.add(function (engine) {
  79640. engine.clear(HighlightLayer.neutralColor, true, true, true);
  79641. });
  79642. };
  79643. /**
  79644. * Checks for the readiness of the element composing the layer.
  79645. * @param subMesh the mesh to check for
  79646. * @param useInstances specify wether or not to use instances to render the mesh
  79647. * @param emissiveTexture the associated emissive texture used to generate the glow
  79648. * @return true if ready otherwise, false
  79649. */
  79650. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  79651. var material = subMesh.getMaterial();
  79652. var mesh = subMesh.getRenderingMesh();
  79653. if (!material || !mesh || !this._meshes) {
  79654. return false;
  79655. }
  79656. var emissiveTexture = null;
  79657. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  79658. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  79659. emissiveTexture = material.emissiveTexture;
  79660. }
  79661. return this._isReady(subMesh, useInstances, emissiveTexture);
  79662. };
  79663. /**
  79664. * Checks for the readiness of the element composing the layer.
  79665. * @param subMesh the mesh to check for
  79666. * @param useInstances specify wether or not to use instances to render the mesh
  79667. * @param emissiveTexture the associated emissive texture used to generate the glow
  79668. * @return true if ready otherwise, false
  79669. */
  79670. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  79671. var material = subMesh.getMaterial();
  79672. if (!material) {
  79673. return false;
  79674. }
  79675. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  79676. return false;
  79677. }
  79678. var defines = [];
  79679. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79680. var mesh = subMesh.getMesh();
  79681. var uv1 = false;
  79682. var uv2 = false;
  79683. // Alpha test
  79684. if (material && material.needAlphaTesting()) {
  79685. var alphaTexture = material.getAlphaTestTexture();
  79686. if (alphaTexture) {
  79687. defines.push("#define ALPHATEST");
  79688. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  79689. alphaTexture.coordinatesIndex === 1) {
  79690. defines.push("#define DIFFUSEUV2");
  79691. uv2 = true;
  79692. }
  79693. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79694. defines.push("#define DIFFUSEUV1");
  79695. uv1 = true;
  79696. }
  79697. }
  79698. }
  79699. // Emissive
  79700. if (emissiveTexture) {
  79701. defines.push("#define EMISSIVE");
  79702. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  79703. emissiveTexture.coordinatesIndex === 1) {
  79704. defines.push("#define EMISSIVEUV2");
  79705. uv2 = true;
  79706. }
  79707. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79708. defines.push("#define EMISSIVEUV1");
  79709. uv1 = true;
  79710. }
  79711. }
  79712. if (uv1) {
  79713. attribs.push(BABYLON.VertexBuffer.UVKind);
  79714. defines.push("#define UV1");
  79715. }
  79716. if (uv2) {
  79717. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79718. defines.push("#define UV2");
  79719. }
  79720. // Bones
  79721. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79722. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79723. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79724. if (mesh.numBoneInfluencers > 4) {
  79725. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79726. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79727. }
  79728. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79729. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  79730. }
  79731. else {
  79732. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79733. }
  79734. // Instances
  79735. if (useInstances) {
  79736. defines.push("#define INSTANCES");
  79737. attribs.push("world0");
  79738. attribs.push("world1");
  79739. attribs.push("world2");
  79740. attribs.push("world3");
  79741. }
  79742. // Get correct effect
  79743. var join = defines.join("\n");
  79744. if (this._cachedDefines !== join) {
  79745. this._cachedDefines = join;
  79746. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  79747. }
  79748. return this._glowMapGenerationEffect.isReady();
  79749. };
  79750. /**
  79751. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  79752. */
  79753. HighlightLayer.prototype.render = function () {
  79754. var currentEffect = this._glowMapMergeEffect;
  79755. // Check
  79756. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  79757. return;
  79758. var engine = this._scene.getEngine();
  79759. this.onBeforeComposeObservable.notifyObservers(this);
  79760. // Render
  79761. engine.enableEffect(currentEffect);
  79762. engine.setState(false);
  79763. // Cache
  79764. var previousStencilBuffer = engine.getStencilBuffer();
  79765. var previousStencilFunction = engine.getStencilFunction();
  79766. var previousStencilMask = engine.getStencilMask();
  79767. var previousStencilOperationPass = engine.getStencilOperationPass();
  79768. var previousStencilOperationFail = engine.getStencilOperationFail();
  79769. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  79770. var previousAlphaMode = engine.getAlphaMode();
  79771. // Texture
  79772. currentEffect.setTexture("textureSampler", this._blurTexture);
  79773. // VBOs
  79774. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  79775. // Stencil operations
  79776. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  79777. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  79778. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  79779. // Draw order
  79780. engine.setAlphaMode(this._options.alphaBlendingMode);
  79781. engine.setStencilMask(0x00);
  79782. engine.setStencilBuffer(true);
  79783. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  79784. if (this.outerGlow) {
  79785. currentEffect.setFloat("offset", 0);
  79786. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  79787. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79788. }
  79789. if (this.innerGlow) {
  79790. currentEffect.setFloat("offset", 1);
  79791. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  79792. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79793. }
  79794. // Restore Cache
  79795. engine.setStencilFunction(previousStencilFunction);
  79796. engine.setStencilMask(previousStencilMask);
  79797. engine.setAlphaMode(previousAlphaMode);
  79798. engine.setStencilBuffer(previousStencilBuffer);
  79799. engine.setStencilOperationPass(previousStencilOperationPass);
  79800. engine.setStencilOperationFail(previousStencilOperationFail);
  79801. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  79802. engine._stencilState.reset();
  79803. this.onAfterComposeObservable.notifyObservers(this);
  79804. // Handle size changes.
  79805. var size = this._mainTexture.getSize();
  79806. this.setMainTextureSize();
  79807. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  79808. // Recreate RTT and post processes on size change.
  79809. this.onSizeChangedObservable.notifyObservers(this);
  79810. this.disposeTextureAndPostProcesses();
  79811. this.createTextureAndPostProcesses();
  79812. }
  79813. };
  79814. /**
  79815. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  79816. * @param mesh The mesh to exclude from the highlight layer
  79817. */
  79818. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  79819. if (!this._excludedMeshes) {
  79820. return;
  79821. }
  79822. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  79823. if (!meshExcluded) {
  79824. this._excludedMeshes[mesh.uniqueId] = {
  79825. mesh: mesh,
  79826. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  79827. mesh.getEngine().setStencilBuffer(false);
  79828. }),
  79829. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  79830. mesh.getEngine().setStencilBuffer(true);
  79831. }),
  79832. };
  79833. }
  79834. };
  79835. /**
  79836. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  79837. * @param mesh The mesh to highlight
  79838. */
  79839. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  79840. if (!this._excludedMeshes) {
  79841. return;
  79842. }
  79843. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  79844. if (meshExcluded) {
  79845. if (meshExcluded.beforeRender) {
  79846. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  79847. }
  79848. if (meshExcluded.afterRender) {
  79849. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  79850. }
  79851. }
  79852. this._excludedMeshes[mesh.uniqueId] = null;
  79853. };
  79854. /**
  79855. * Determine if a given mesh will be highlighted by the current HighlightLayer
  79856. * @param mesh mesh to test
  79857. * @returns true if the mesh will be highlighted by the current HighlightLayer
  79858. */
  79859. HighlightLayer.prototype.hasMesh = function (mesh) {
  79860. if (!this._meshes) {
  79861. return false;
  79862. }
  79863. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  79864. };
  79865. /**
  79866. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  79867. * @param mesh The mesh to highlight
  79868. * @param color The color of the highlight
  79869. * @param glowEmissiveOnly Extract the glow from the emissive texture
  79870. */
  79871. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  79872. var _this = this;
  79873. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  79874. if (!this._meshes) {
  79875. return;
  79876. }
  79877. var meshHighlight = this._meshes[mesh.uniqueId];
  79878. if (meshHighlight) {
  79879. meshHighlight.color = color;
  79880. }
  79881. else {
  79882. this._meshes[mesh.uniqueId] = {
  79883. mesh: mesh,
  79884. color: color,
  79885. // Lambda required for capture due to Observable this context
  79886. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  79887. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  79888. _this.defaultStencilReference(mesh);
  79889. }
  79890. else {
  79891. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  79892. }
  79893. }),
  79894. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  79895. glowEmissiveOnly: glowEmissiveOnly
  79896. };
  79897. }
  79898. this._shouldRender = true;
  79899. };
  79900. /**
  79901. * Remove a mesh from the highlight layer in order to make it stop glowing.
  79902. * @param mesh The mesh to highlight
  79903. */
  79904. HighlightLayer.prototype.removeMesh = function (mesh) {
  79905. if (!this._meshes) {
  79906. return;
  79907. }
  79908. var meshHighlight = this._meshes[mesh.uniqueId];
  79909. if (meshHighlight) {
  79910. if (meshHighlight.observerHighlight) {
  79911. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  79912. }
  79913. if (meshHighlight.observerDefault) {
  79914. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  79915. }
  79916. delete this._meshes[mesh.uniqueId];
  79917. }
  79918. this._shouldRender = false;
  79919. for (var meshHighlightToCheck in this._meshes) {
  79920. if (this._meshes[meshHighlightToCheck]) {
  79921. this._shouldRender = true;
  79922. break;
  79923. }
  79924. }
  79925. };
  79926. /**
  79927. * Returns true if the layer contains information to display, otherwise false.
  79928. */
  79929. HighlightLayer.prototype.shouldRender = function () {
  79930. return this.isEnabled && this._shouldRender;
  79931. };
  79932. /**
  79933. * Sets the main texture desired size which is the closest power of two
  79934. * of the engine canvas size.
  79935. */
  79936. HighlightLayer.prototype.setMainTextureSize = function () {
  79937. if (this._options.mainTextureFixedSize) {
  79938. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  79939. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  79940. }
  79941. else {
  79942. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  79943. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  79944. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  79945. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  79946. }
  79947. };
  79948. /**
  79949. * Force the stencil to the normal expected value for none glowing parts
  79950. */
  79951. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  79952. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  79953. };
  79954. /**
  79955. * Dispose only the render target textures and post process.
  79956. */
  79957. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  79958. this._blurTexture.dispose();
  79959. this._mainTexture.dispose();
  79960. this._downSamplePostprocess.dispose();
  79961. this._horizontalBlurPostprocess.dispose();
  79962. this._verticalBlurPostprocess.dispose();
  79963. };
  79964. /**
  79965. * Dispose the highlight layer and free resources.
  79966. */
  79967. HighlightLayer.prototype.dispose = function () {
  79968. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79969. if (vertexBuffer) {
  79970. vertexBuffer.dispose();
  79971. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79972. }
  79973. if (this._indexBuffer) {
  79974. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79975. this._indexBuffer = null;
  79976. }
  79977. // Clean textures and post processes
  79978. this.disposeTextureAndPostProcesses();
  79979. if (this._meshes) {
  79980. // Clean mesh references
  79981. for (var id in this._meshes) {
  79982. var meshHighlight = this._meshes[id];
  79983. if (meshHighlight && meshHighlight.mesh) {
  79984. if (meshHighlight.observerHighlight) {
  79985. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  79986. }
  79987. if (meshHighlight.observerDefault) {
  79988. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  79989. }
  79990. }
  79991. }
  79992. this._meshes = null;
  79993. }
  79994. if (this._excludedMeshes) {
  79995. for (var id in this._excludedMeshes) {
  79996. var meshHighlight = this._excludedMeshes[id];
  79997. if (meshHighlight) {
  79998. if (meshHighlight.beforeRender) {
  79999. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  80000. }
  80001. if (meshHighlight.afterRender) {
  80002. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  80003. }
  80004. }
  80005. }
  80006. this._excludedMeshes = null;
  80007. }
  80008. // Remove from scene
  80009. var index = this._scene.highlightLayers.indexOf(this, 0);
  80010. if (index > -1) {
  80011. this._scene.highlightLayers.splice(index, 1);
  80012. }
  80013. // Callback
  80014. this.onDisposeObservable.notifyObservers(this);
  80015. this.onDisposeObservable.clear();
  80016. this.onBeforeRenderMainTextureObservable.clear();
  80017. this.onBeforeBlurObservable.clear();
  80018. this.onBeforeComposeObservable.clear();
  80019. this.onAfterComposeObservable.clear();
  80020. this.onSizeChangedObservable.clear();
  80021. };
  80022. /**
  80023. * The neutral color used during the preparation of the glow effect.
  80024. * This is black by default as the blend operation is a blend operation.
  80025. */
  80026. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  80027. /**
  80028. * Stencil value used for glowing meshes.
  80029. */
  80030. HighlightLayer.glowingMeshStencilReference = 0x02;
  80031. /**
  80032. * Stencil value used for the other meshes in the scene.
  80033. */
  80034. HighlightLayer.normalMeshStencilReference = 0x01;
  80035. return HighlightLayer;
  80036. }());
  80037. BABYLON.HighlightLayer = HighlightLayer;
  80038. })(BABYLON || (BABYLON = {}));
  80039. //# sourceMappingURL=babylon.highlightlayer.js.map
  80040. var BABYLON;
  80041. (function (BABYLON) {
  80042. /**
  80043. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  80044. */
  80045. var AssetTaskState;
  80046. (function (AssetTaskState) {
  80047. /**
  80048. * Initialization
  80049. */
  80050. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  80051. /**
  80052. * Running
  80053. */
  80054. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  80055. /**
  80056. * Done
  80057. */
  80058. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  80059. /**
  80060. * Error
  80061. */
  80062. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  80063. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  80064. /**
  80065. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  80066. */
  80067. var AbstractAssetTask = /** @class */ (function () {
  80068. /**
  80069. * Creates a new {BABYLON.AssetsManager}
  80070. * @param name defines the name of the task
  80071. */
  80072. function AbstractAssetTask(
  80073. /**
  80074. * Task name
  80075. */ name) {
  80076. this.name = name;
  80077. this._isCompleted = false;
  80078. this._taskState = AssetTaskState.INIT;
  80079. }
  80080. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  80081. /**
  80082. * Get if the task is completed
  80083. */
  80084. get: function () {
  80085. return this._isCompleted;
  80086. },
  80087. enumerable: true,
  80088. configurable: true
  80089. });
  80090. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  80091. /**
  80092. * Gets the current state of the task
  80093. */
  80094. get: function () {
  80095. return this._taskState;
  80096. },
  80097. enumerable: true,
  80098. configurable: true
  80099. });
  80100. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  80101. /**
  80102. * Gets the current error object (if task is in error)
  80103. */
  80104. get: function () {
  80105. return this._errorObject;
  80106. },
  80107. enumerable: true,
  80108. configurable: true
  80109. });
  80110. /**
  80111. * Internal only
  80112. * @ignore
  80113. */
  80114. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  80115. if (this._errorObject) {
  80116. return;
  80117. }
  80118. this._errorObject = {
  80119. message: message,
  80120. exception: exception
  80121. };
  80122. };
  80123. /**
  80124. * Execute the current task
  80125. * @param scene defines the scene where you want your assets to be loaded
  80126. * @param onSuccess is a callback called when the task is successfully executed
  80127. * @param onError is a callback called if an error occurs
  80128. */
  80129. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  80130. var _this = this;
  80131. this._taskState = AssetTaskState.RUNNING;
  80132. this.runTask(scene, function () {
  80133. _this.onDoneCallback(onSuccess, onError);
  80134. }, function (msg, exception) {
  80135. _this.onErrorCallback(onError, msg, exception);
  80136. });
  80137. };
  80138. /**
  80139. * Execute the current task
  80140. * @param scene defines the scene where you want your assets to be loaded
  80141. * @param onSuccess is a callback called when the task is successfully executed
  80142. * @param onError is a callback called if an error occurs
  80143. */
  80144. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80145. throw new Error("runTask is not implemented");
  80146. };
  80147. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  80148. this._taskState = AssetTaskState.ERROR;
  80149. this._errorObject = {
  80150. message: message,
  80151. exception: exception
  80152. };
  80153. if (this.onError) {
  80154. this.onError(this, message, exception);
  80155. }
  80156. onError();
  80157. };
  80158. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  80159. try {
  80160. this._taskState = AssetTaskState.DONE;
  80161. this._isCompleted = true;
  80162. if (this.onSuccess) {
  80163. this.onSuccess(this);
  80164. }
  80165. onSuccess();
  80166. }
  80167. catch (e) {
  80168. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  80169. }
  80170. };
  80171. return AbstractAssetTask;
  80172. }());
  80173. BABYLON.AbstractAssetTask = AbstractAssetTask;
  80174. /**
  80175. * Class used to share progress information about assets loading
  80176. */
  80177. var AssetsProgressEvent = /** @class */ (function () {
  80178. /**
  80179. * Creates a {BABYLON.AssetsProgressEvent}
  80180. * @param remainingCount defines the number of remaining tasks to process
  80181. * @param totalCount defines the total number of tasks
  80182. * @param task defines the task that was just processed
  80183. */
  80184. function AssetsProgressEvent(remainingCount, totalCount, task) {
  80185. this.remainingCount = remainingCount;
  80186. this.totalCount = totalCount;
  80187. this.task = task;
  80188. }
  80189. return AssetsProgressEvent;
  80190. }());
  80191. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  80192. /**
  80193. * Define a task used by {BABYLON.AssetsManager} to load meshes
  80194. */
  80195. var MeshAssetTask = /** @class */ (function (_super) {
  80196. __extends(MeshAssetTask, _super);
  80197. /**
  80198. * Creates a new {BABYLON.MeshAssetTask}
  80199. * @param name defines the name of the task
  80200. * @param meshesNames defines the list of mesh's names you want to load
  80201. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  80202. * @param sceneFilename defines the filename of the scene to load from
  80203. */
  80204. function MeshAssetTask(
  80205. /**
  80206. * Defines the name of the task
  80207. */
  80208. name,
  80209. /**
  80210. * Defines the list of mesh's names you want to load
  80211. */
  80212. meshesNames,
  80213. /**
  80214. * Defines the root url to use as a base to load your meshes and associated resources
  80215. */
  80216. rootUrl,
  80217. /**
  80218. * Defines the filename of the scene to load from
  80219. */
  80220. sceneFilename) {
  80221. var _this = _super.call(this, name) || this;
  80222. _this.name = name;
  80223. _this.meshesNames = meshesNames;
  80224. _this.rootUrl = rootUrl;
  80225. _this.sceneFilename = sceneFilename;
  80226. return _this;
  80227. }
  80228. /**
  80229. * Execute the current task
  80230. * @param scene defines the scene where you want your assets to be loaded
  80231. * @param onSuccess is a callback called when the task is successfully executed
  80232. * @param onError is a callback called if an error occurs
  80233. */
  80234. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80235. var _this = this;
  80236. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  80237. _this.loadedMeshes = meshes;
  80238. _this.loadedParticleSystems = particleSystems;
  80239. _this.loadedSkeletons = skeletons;
  80240. onSuccess();
  80241. }, null, function (scene, message, exception) {
  80242. onError(message, exception);
  80243. });
  80244. };
  80245. return MeshAssetTask;
  80246. }(AbstractAssetTask));
  80247. BABYLON.MeshAssetTask = MeshAssetTask;
  80248. /**
  80249. * Define a task used by {BABYLON.AssetsManager} to load text content
  80250. */
  80251. var TextFileAssetTask = /** @class */ (function (_super) {
  80252. __extends(TextFileAssetTask, _super);
  80253. /**
  80254. * Creates a new TextFileAssetTask object
  80255. * @param name defines the name of the task
  80256. * @param url defines the location of the file to load
  80257. */
  80258. function TextFileAssetTask(
  80259. /**
  80260. * Defines the name of the task
  80261. */
  80262. name,
  80263. /**
  80264. * Defines the location of the file to load
  80265. */
  80266. url) {
  80267. var _this = _super.call(this, name) || this;
  80268. _this.name = name;
  80269. _this.url = url;
  80270. return _this;
  80271. }
  80272. /**
  80273. * Execute the current task
  80274. * @param scene defines the scene where you want your assets to be loaded
  80275. * @param onSuccess is a callback called when the task is successfully executed
  80276. * @param onError is a callback called if an error occurs
  80277. */
  80278. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80279. var _this = this;
  80280. scene._loadFile(this.url, function (data) {
  80281. _this.text = data;
  80282. onSuccess();
  80283. }, undefined, false, true, function (request, exception) {
  80284. if (request) {
  80285. onError(request.status + " " + request.statusText, exception);
  80286. }
  80287. });
  80288. };
  80289. return TextFileAssetTask;
  80290. }(AbstractAssetTask));
  80291. BABYLON.TextFileAssetTask = TextFileAssetTask;
  80292. /**
  80293. * Define a task used by {BABYLON.AssetsManager} to load binary data
  80294. */
  80295. var BinaryFileAssetTask = /** @class */ (function (_super) {
  80296. __extends(BinaryFileAssetTask, _super);
  80297. /**
  80298. * Creates a new BinaryFileAssetTask object
  80299. * @param name defines the name of the new task
  80300. * @param url defines the location of the file to load
  80301. */
  80302. function BinaryFileAssetTask(
  80303. /**
  80304. * Defines the name of the task
  80305. */
  80306. name,
  80307. /**
  80308. * Defines the location of the file to load
  80309. */
  80310. url) {
  80311. var _this = _super.call(this, name) || this;
  80312. _this.name = name;
  80313. _this.url = url;
  80314. return _this;
  80315. }
  80316. /**
  80317. * Execute the current task
  80318. * @param scene defines the scene where you want your assets to be loaded
  80319. * @param onSuccess is a callback called when the task is successfully executed
  80320. * @param onError is a callback called if an error occurs
  80321. */
  80322. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80323. var _this = this;
  80324. scene._loadFile(this.url, function (data) {
  80325. _this.data = data;
  80326. onSuccess();
  80327. }, undefined, true, true, function (request, exception) {
  80328. if (request) {
  80329. onError(request.status + " " + request.statusText, exception);
  80330. }
  80331. });
  80332. };
  80333. return BinaryFileAssetTask;
  80334. }(AbstractAssetTask));
  80335. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  80336. /**
  80337. * Define a task used by {BABYLON.AssetsManager} to load images
  80338. */
  80339. var ImageAssetTask = /** @class */ (function (_super) {
  80340. __extends(ImageAssetTask, _super);
  80341. /**
  80342. * Creates a new ImageAssetTask
  80343. * @param name defines the name of the task
  80344. * @param url defines the location of the image to load
  80345. */
  80346. function ImageAssetTask(
  80347. /**
  80348. * Defines the name of the task
  80349. */
  80350. name,
  80351. /**
  80352. * Defines the location of the image to load
  80353. */
  80354. url) {
  80355. var _this = _super.call(this, name) || this;
  80356. _this.name = name;
  80357. _this.url = url;
  80358. return _this;
  80359. }
  80360. /**
  80361. * Execute the current task
  80362. * @param scene defines the scene where you want your assets to be loaded
  80363. * @param onSuccess is a callback called when the task is successfully executed
  80364. * @param onError is a callback called if an error occurs
  80365. */
  80366. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80367. var _this = this;
  80368. var img = new Image();
  80369. BABYLON.Tools.SetCorsBehavior(this.url, img);
  80370. img.onload = function () {
  80371. _this.image = img;
  80372. onSuccess();
  80373. };
  80374. img.onerror = function (err) {
  80375. onError("Error loading image", err);
  80376. };
  80377. img.src = this.url;
  80378. };
  80379. return ImageAssetTask;
  80380. }(AbstractAssetTask));
  80381. BABYLON.ImageAssetTask = ImageAssetTask;
  80382. /**
  80383. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  80384. */
  80385. var TextureAssetTask = /** @class */ (function (_super) {
  80386. __extends(TextureAssetTask, _super);
  80387. /**
  80388. * Creates a new TextureAssetTask object
  80389. * @param name defines the name of the task
  80390. * @param url defines the location of the file to load
  80391. * @param noMipmap defines if mipmap should not be generated (default is false)
  80392. * @param invertY defines if texture must be inverted on Y axis (default is false)
  80393. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  80394. */
  80395. function TextureAssetTask(
  80396. /**
  80397. * Defines the name of the task
  80398. */
  80399. name,
  80400. /**
  80401. * Defines the location of the file to load
  80402. */
  80403. url,
  80404. /**
  80405. * Defines if mipmap should not be generated (default is false)
  80406. */
  80407. noMipmap,
  80408. /**
  80409. * Defines if texture must be inverted on Y axis (default is false)
  80410. */
  80411. invertY,
  80412. /**
  80413. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  80414. */
  80415. samplingMode) {
  80416. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  80417. var _this = _super.call(this, name) || this;
  80418. _this.name = name;
  80419. _this.url = url;
  80420. _this.noMipmap = noMipmap;
  80421. _this.invertY = invertY;
  80422. _this.samplingMode = samplingMode;
  80423. return _this;
  80424. }
  80425. /**
  80426. * Execute the current task
  80427. * @param scene defines the scene where you want your assets to be loaded
  80428. * @param onSuccess is a callback called when the task is successfully executed
  80429. * @param onError is a callback called if an error occurs
  80430. */
  80431. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80432. var onload = function () {
  80433. onSuccess();
  80434. };
  80435. var onerror = function (message, exception) {
  80436. onError(message, exception);
  80437. };
  80438. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  80439. };
  80440. return TextureAssetTask;
  80441. }(AbstractAssetTask));
  80442. BABYLON.TextureAssetTask = TextureAssetTask;
  80443. /**
  80444. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  80445. */
  80446. var CubeTextureAssetTask = /** @class */ (function (_super) {
  80447. __extends(CubeTextureAssetTask, _super);
  80448. /**
  80449. * Creates a new CubeTextureAssetTask
  80450. * @param name defines the name of the task
  80451. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  80452. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  80453. * @param noMipmap defines if mipmaps should not be generated (default is false)
  80454. * @param files defines the explicit list of files (undefined by default)
  80455. */
  80456. function CubeTextureAssetTask(
  80457. /**
  80458. * Defines the name of the task
  80459. */
  80460. name,
  80461. /**
  80462. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  80463. */
  80464. url,
  80465. /**
  80466. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  80467. */
  80468. extensions,
  80469. /**
  80470. * Defines if mipmaps should not be generated (default is false)
  80471. */
  80472. noMipmap,
  80473. /**
  80474. * Defines the explicit list of files (undefined by default)
  80475. */
  80476. files) {
  80477. var _this = _super.call(this, name) || this;
  80478. _this.name = name;
  80479. _this.url = url;
  80480. _this.extensions = extensions;
  80481. _this.noMipmap = noMipmap;
  80482. _this.files = files;
  80483. return _this;
  80484. }
  80485. /**
  80486. * Execute the current task
  80487. * @param scene defines the scene where you want your assets to be loaded
  80488. * @param onSuccess is a callback called when the task is successfully executed
  80489. * @param onError is a callback called if an error occurs
  80490. */
  80491. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80492. var onload = function () {
  80493. onSuccess();
  80494. };
  80495. var onerror = function (message, exception) {
  80496. onError(message, exception);
  80497. };
  80498. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  80499. };
  80500. return CubeTextureAssetTask;
  80501. }(AbstractAssetTask));
  80502. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  80503. /**
  80504. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  80505. */
  80506. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  80507. __extends(HDRCubeTextureAssetTask, _super);
  80508. /**
  80509. * Creates a new HDRCubeTextureAssetTask object
  80510. * @param name defines the name of the task
  80511. * @param url defines the location of the file to load
  80512. * @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.
  80513. * @param noMipmap defines if mipmaps should not be generated (default is false)
  80514. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  80515. * @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)
  80516. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  80517. */
  80518. function HDRCubeTextureAssetTask(
  80519. /**
  80520. * Defines the name of the task
  80521. */
  80522. name,
  80523. /**
  80524. * Defines the location of the file to load
  80525. */
  80526. url,
  80527. /**
  80528. * 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.
  80529. */
  80530. size,
  80531. /**
  80532. * Defines if mipmaps should not be generated (default is false)
  80533. */
  80534. noMipmap,
  80535. /**
  80536. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  80537. */
  80538. generateHarmonics,
  80539. /**
  80540. * 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)
  80541. */
  80542. useInGammaSpace,
  80543. /**
  80544. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  80545. */
  80546. usePMREMGenerator) {
  80547. if (noMipmap === void 0) { noMipmap = false; }
  80548. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80549. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  80550. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  80551. var _this = _super.call(this, name) || this;
  80552. _this.name = name;
  80553. _this.url = url;
  80554. _this.size = size;
  80555. _this.noMipmap = noMipmap;
  80556. _this.generateHarmonics = generateHarmonics;
  80557. _this.useInGammaSpace = useInGammaSpace;
  80558. _this.usePMREMGenerator = usePMREMGenerator;
  80559. return _this;
  80560. }
  80561. /**
  80562. * Execute the current task
  80563. * @param scene defines the scene where you want your assets to be loaded
  80564. * @param onSuccess is a callback called when the task is successfully executed
  80565. * @param onError is a callback called if an error occurs
  80566. */
  80567. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  80568. var onload = function () {
  80569. onSuccess();
  80570. };
  80571. var onerror = function (message, exception) {
  80572. onError(message, exception);
  80573. };
  80574. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  80575. };
  80576. return HDRCubeTextureAssetTask;
  80577. }(AbstractAssetTask));
  80578. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  80579. /**
  80580. * This class can be used to easily import assets into a scene
  80581. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  80582. */
  80583. var AssetsManager = /** @class */ (function () {
  80584. /**
  80585. * Creates a new AssetsManager
  80586. * @param scene defines the scene to work on
  80587. */
  80588. function AssetsManager(scene) {
  80589. this._isLoading = false;
  80590. this._tasks = new Array();
  80591. this._waitingTasksCount = 0;
  80592. this._totalTasksCount = 0;
  80593. /**
  80594. * Observable called when all tasks are processed
  80595. */
  80596. this.onTaskSuccessObservable = new BABYLON.Observable();
  80597. /**
  80598. * Observable called when a task had an error
  80599. */
  80600. this.onTaskErrorObservable = new BABYLON.Observable();
  80601. /**
  80602. * Observable called when a task is successful
  80603. */
  80604. this.onTasksDoneObservable = new BABYLON.Observable();
  80605. /**
  80606. * Observable called when a task is done (whatever the result is)
  80607. */
  80608. this.onProgressObservable = new BABYLON.Observable();
  80609. /**
  80610. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  80611. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  80612. */
  80613. this.useDefaultLoadingScreen = true;
  80614. this._scene = scene;
  80615. }
  80616. /**
  80617. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  80618. * @param taskName defines the name of the new task
  80619. * @param meshesNames defines the name of meshes to load
  80620. * @param rootUrl defines the root url to use to locate files
  80621. * @param sceneFilename defines the filename of the scene file
  80622. * @returns a new {BABYLON.MeshAssetTask} object
  80623. */
  80624. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  80625. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  80626. this._tasks.push(task);
  80627. return task;
  80628. };
  80629. /**
  80630. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  80631. * @param taskName defines the name of the new task
  80632. * @param url defines the url of the file to load
  80633. * @returns a new {BABYLON.TextFileAssetTask} object
  80634. */
  80635. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  80636. var task = new TextFileAssetTask(taskName, url);
  80637. this._tasks.push(task);
  80638. return task;
  80639. };
  80640. /**
  80641. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  80642. * @param taskName defines the name of the new task
  80643. * @param url defines the url of the file to load
  80644. * @returns a new {BABYLON.BinaryFileAssetTask} object
  80645. */
  80646. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  80647. var task = new BinaryFileAssetTask(taskName, url);
  80648. this._tasks.push(task);
  80649. return task;
  80650. };
  80651. /**
  80652. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  80653. * @param taskName defines the name of the new task
  80654. * @param url defines the url of the file to load
  80655. * @returns a new {BABYLON.ImageAssetTask} object
  80656. */
  80657. AssetsManager.prototype.addImageTask = function (taskName, url) {
  80658. var task = new ImageAssetTask(taskName, url);
  80659. this._tasks.push(task);
  80660. return task;
  80661. };
  80662. /**
  80663. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  80664. * @param taskName defines the name of the new task
  80665. * @param url defines the url of the file to load
  80666. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80667. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  80668. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  80669. * @returns a new {BABYLON.TextureAssetTask} object
  80670. */
  80671. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  80672. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  80673. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  80674. this._tasks.push(task);
  80675. return task;
  80676. };
  80677. /**
  80678. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  80679. * @param taskName defines the name of the new task
  80680. * @param url defines the url of the file to load
  80681. * @param extensions defines the extension to use to load the cube map (can be null)
  80682. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80683. * @param files defines the list of files to load (can be null)
  80684. * @returns a new {BABYLON.CubeTextureAssetTask} object
  80685. */
  80686. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  80687. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  80688. this._tasks.push(task);
  80689. return task;
  80690. };
  80691. /**
  80692. *
  80693. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  80694. * @param taskName defines the name of the new task
  80695. * @param url defines the url of the file to load
  80696. * @param size defines the size you want for the cubemap (can be null)
  80697. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80698. * @param generateHarmonics defines if you want to automatically generate (true by default)
  80699. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  80700. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  80701. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  80702. */
  80703. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  80704. if (noMipmap === void 0) { noMipmap = false; }
  80705. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80706. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  80707. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  80708. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  80709. this._tasks.push(task);
  80710. return task;
  80711. };
  80712. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  80713. var _this = this;
  80714. this._waitingTasksCount--;
  80715. try {
  80716. if (task.taskState === AssetTaskState.DONE) {
  80717. // Let's remove successfull tasks
  80718. BABYLON.Tools.SetImmediate(function () {
  80719. var index = _this._tasks.indexOf(task);
  80720. if (index > -1) {
  80721. _this._tasks.splice(index, 1);
  80722. }
  80723. });
  80724. }
  80725. if (this.onProgress) {
  80726. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  80727. }
  80728. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  80729. }
  80730. catch (e) {
  80731. BABYLON.Tools.Error("Error running progress callbacks.");
  80732. console.log(e);
  80733. }
  80734. if (this._waitingTasksCount === 0) {
  80735. try {
  80736. if (this.onFinish) {
  80737. this.onFinish(this._tasks);
  80738. }
  80739. this.onTasksDoneObservable.notifyObservers(this._tasks);
  80740. }
  80741. catch (e) {
  80742. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  80743. console.log(e);
  80744. }
  80745. this._isLoading = false;
  80746. this._scene.getEngine().hideLoadingUI();
  80747. }
  80748. };
  80749. AssetsManager.prototype._runTask = function (task) {
  80750. var _this = this;
  80751. var done = function () {
  80752. try {
  80753. if (_this.onTaskSuccess) {
  80754. _this.onTaskSuccess(task);
  80755. }
  80756. _this.onTaskSuccessObservable.notifyObservers(task);
  80757. _this._decreaseWaitingTasksCount(task);
  80758. }
  80759. catch (e) {
  80760. error("Error executing task success callbacks", e);
  80761. }
  80762. };
  80763. var error = function (message, exception) {
  80764. task._setErrorObject(message, exception);
  80765. if (_this.onTaskError) {
  80766. _this.onTaskError(task);
  80767. }
  80768. _this.onTaskErrorObservable.notifyObservers(task);
  80769. _this._decreaseWaitingTasksCount(task);
  80770. };
  80771. task.run(this._scene, done, error);
  80772. };
  80773. /**
  80774. * Reset the {BABYLON.AssetsManager} and remove all tasks
  80775. * @return the current instance of the {BABYLON.AssetsManager}
  80776. */
  80777. AssetsManager.prototype.reset = function () {
  80778. this._isLoading = false;
  80779. this._tasks = new Array();
  80780. return this;
  80781. };
  80782. /**
  80783. * Start the loading process
  80784. * @return the current instance of the {BABYLON.AssetsManager}
  80785. */
  80786. AssetsManager.prototype.load = function () {
  80787. if (this._isLoading) {
  80788. return this;
  80789. }
  80790. this._isLoading = true;
  80791. this._waitingTasksCount = this._tasks.length;
  80792. this._totalTasksCount = this._tasks.length;
  80793. if (this._waitingTasksCount === 0) {
  80794. if (this.onFinish) {
  80795. this.onFinish(this._tasks);
  80796. }
  80797. this.onTasksDoneObservable.notifyObservers(this._tasks);
  80798. return this;
  80799. }
  80800. if (this.useDefaultLoadingScreen) {
  80801. this._scene.getEngine().displayLoadingUI();
  80802. }
  80803. for (var index = 0; index < this._tasks.length; index++) {
  80804. var task = this._tasks[index];
  80805. this._runTask(task);
  80806. }
  80807. return this;
  80808. };
  80809. return AssetsManager;
  80810. }());
  80811. BABYLON.AssetsManager = AssetsManager;
  80812. })(BABYLON || (BABYLON = {}));
  80813. //# sourceMappingURL=babylon.assetsManager.js.map
  80814. var BABYLON;
  80815. (function (BABYLON) {
  80816. var serializedGeometries = [];
  80817. var serializeGeometry = function (geometry, serializationGeometries) {
  80818. if (serializedGeometries[geometry.id]) {
  80819. return;
  80820. }
  80821. if (geometry.doNotSerialize) {
  80822. return;
  80823. }
  80824. if (geometry instanceof BABYLON.BoxGeometry) {
  80825. serializationGeometries.boxes.push(geometry.serialize());
  80826. }
  80827. else if (geometry instanceof BABYLON.SphereGeometry) {
  80828. serializationGeometries.spheres.push(geometry.serialize());
  80829. }
  80830. else if (geometry instanceof BABYLON.CylinderGeometry) {
  80831. serializationGeometries.cylinders.push(geometry.serialize());
  80832. }
  80833. else if (geometry instanceof BABYLON.TorusGeometry) {
  80834. serializationGeometries.toruses.push(geometry.serialize());
  80835. }
  80836. else if (geometry instanceof BABYLON.GroundGeometry) {
  80837. serializationGeometries.grounds.push(geometry.serialize());
  80838. }
  80839. else if (geometry instanceof BABYLON.Plane) {
  80840. serializationGeometries.planes.push(geometry.serialize());
  80841. }
  80842. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  80843. serializationGeometries.torusKnots.push(geometry.serialize());
  80844. }
  80845. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  80846. throw new Error("Unknown primitive type");
  80847. }
  80848. else {
  80849. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  80850. }
  80851. serializedGeometries[geometry.id] = true;
  80852. };
  80853. var serializeMesh = function (mesh, serializationScene) {
  80854. var serializationObject = {};
  80855. // Geometry
  80856. var geometry = mesh._geometry;
  80857. if (geometry) {
  80858. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  80859. // 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
  80860. serializeGeometry(geometry, serializationScene.geometries);
  80861. }
  80862. }
  80863. // Custom
  80864. if (mesh.serialize) {
  80865. mesh.serialize(serializationObject);
  80866. }
  80867. return serializationObject;
  80868. };
  80869. var finalizeSingleMesh = function (mesh, serializationObject) {
  80870. //only works if the mesh is already loaded
  80871. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  80872. //serialize material
  80873. if (mesh.material) {
  80874. if (mesh.material instanceof BABYLON.StandardMaterial) {
  80875. serializationObject.materials = serializationObject.materials || [];
  80876. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  80877. serializationObject.materials.push(mesh.material.serialize());
  80878. }
  80879. }
  80880. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  80881. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  80882. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  80883. serializationObject.multiMaterials.push(mesh.material.serialize());
  80884. }
  80885. }
  80886. }
  80887. //serialize geometry
  80888. var geometry = mesh._geometry;
  80889. if (geometry) {
  80890. if (!serializationObject.geometries) {
  80891. serializationObject.geometries = {};
  80892. serializationObject.geometries.boxes = [];
  80893. serializationObject.geometries.spheres = [];
  80894. serializationObject.geometries.cylinders = [];
  80895. serializationObject.geometries.toruses = [];
  80896. serializationObject.geometries.grounds = [];
  80897. serializationObject.geometries.planes = [];
  80898. serializationObject.geometries.torusKnots = [];
  80899. serializationObject.geometries.vertexData = [];
  80900. }
  80901. serializeGeometry(geometry, serializationObject.geometries);
  80902. }
  80903. // Skeletons
  80904. if (mesh.skeleton) {
  80905. serializationObject.skeletons = serializationObject.skeletons || [];
  80906. serializationObject.skeletons.push(mesh.skeleton.serialize());
  80907. }
  80908. //serialize the actual mesh
  80909. serializationObject.meshes = serializationObject.meshes || [];
  80910. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  80911. }
  80912. };
  80913. var SceneSerializer = /** @class */ (function () {
  80914. function SceneSerializer() {
  80915. }
  80916. SceneSerializer.ClearCache = function () {
  80917. serializedGeometries = [];
  80918. };
  80919. SceneSerializer.Serialize = function (scene) {
  80920. var serializationObject = {};
  80921. SceneSerializer.ClearCache();
  80922. // Scene
  80923. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  80924. serializationObject.autoClear = scene.autoClear;
  80925. serializationObject.clearColor = scene.clearColor.asArray();
  80926. serializationObject.ambientColor = scene.ambientColor.asArray();
  80927. serializationObject.gravity = scene.gravity.asArray();
  80928. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  80929. serializationObject.workerCollisions = scene.workerCollisions;
  80930. // Fog
  80931. if (scene.fogMode && scene.fogMode !== 0) {
  80932. serializationObject.fogMode = scene.fogMode;
  80933. serializationObject.fogColor = scene.fogColor.asArray();
  80934. serializationObject.fogStart = scene.fogStart;
  80935. serializationObject.fogEnd = scene.fogEnd;
  80936. serializationObject.fogDensity = scene.fogDensity;
  80937. }
  80938. //Physics
  80939. if (scene.isPhysicsEnabled()) {
  80940. var physicEngine = scene.getPhysicsEngine();
  80941. if (physicEngine) {
  80942. serializationObject.physicsEnabled = true;
  80943. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  80944. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  80945. }
  80946. }
  80947. // Metadata
  80948. if (scene.metadata) {
  80949. serializationObject.metadata = scene.metadata;
  80950. }
  80951. // Morph targets
  80952. serializationObject.morphTargetManagers = [];
  80953. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  80954. var abstractMesh = _a[_i];
  80955. var manager = abstractMesh.morphTargetManager;
  80956. if (manager) {
  80957. serializationObject.morphTargetManagers.push(manager.serialize());
  80958. }
  80959. }
  80960. // Lights
  80961. serializationObject.lights = [];
  80962. var index;
  80963. var light;
  80964. for (index = 0; index < scene.lights.length; index++) {
  80965. light = scene.lights[index];
  80966. if (!light.doNotSerialize) {
  80967. serializationObject.lights.push(light.serialize());
  80968. }
  80969. }
  80970. // Cameras
  80971. serializationObject.cameras = [];
  80972. for (index = 0; index < scene.cameras.length; index++) {
  80973. var camera = scene.cameras[index];
  80974. if (!camera.doNotSerialize) {
  80975. serializationObject.cameras.push(camera.serialize());
  80976. }
  80977. }
  80978. if (scene.activeCamera) {
  80979. serializationObject.activeCameraID = scene.activeCamera.id;
  80980. }
  80981. // Animations
  80982. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  80983. // Materials
  80984. serializationObject.materials = [];
  80985. serializationObject.multiMaterials = [];
  80986. var material;
  80987. for (index = 0; index < scene.materials.length; index++) {
  80988. material = scene.materials[index];
  80989. if (!material.doNotSerialize) {
  80990. serializationObject.materials.push(material.serialize());
  80991. }
  80992. }
  80993. // MultiMaterials
  80994. serializationObject.multiMaterials = [];
  80995. for (index = 0; index < scene.multiMaterials.length; index++) {
  80996. var multiMaterial = scene.multiMaterials[index];
  80997. serializationObject.multiMaterials.push(multiMaterial.serialize());
  80998. }
  80999. // Environment texture
  81000. if (scene.environmentTexture) {
  81001. serializationObject.environmentTexture = scene.environmentTexture.name;
  81002. }
  81003. // Skeletons
  81004. serializationObject.skeletons = [];
  81005. for (index = 0; index < scene.skeletons.length; index++) {
  81006. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  81007. }
  81008. // Transform nodes
  81009. serializationObject.transformNodes = [];
  81010. for (index = 0; index < scene.transformNodes.length; index++) {
  81011. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  81012. }
  81013. // Geometries
  81014. serializationObject.geometries = {};
  81015. serializationObject.geometries.boxes = [];
  81016. serializationObject.geometries.spheres = [];
  81017. serializationObject.geometries.cylinders = [];
  81018. serializationObject.geometries.toruses = [];
  81019. serializationObject.geometries.grounds = [];
  81020. serializationObject.geometries.planes = [];
  81021. serializationObject.geometries.torusKnots = [];
  81022. serializationObject.geometries.vertexData = [];
  81023. serializedGeometries = [];
  81024. var geometries = scene.getGeometries();
  81025. for (index = 0; index < geometries.length; index++) {
  81026. var geometry = geometries[index];
  81027. if (geometry.isReady()) {
  81028. serializeGeometry(geometry, serializationObject.geometries);
  81029. }
  81030. }
  81031. // Meshes
  81032. serializationObject.meshes = [];
  81033. for (index = 0; index < scene.meshes.length; index++) {
  81034. var abstractMesh = scene.meshes[index];
  81035. if (abstractMesh instanceof BABYLON.Mesh) {
  81036. var mesh = abstractMesh;
  81037. if (!mesh.doNotSerialize) {
  81038. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  81039. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  81040. }
  81041. }
  81042. }
  81043. }
  81044. // Particles Systems
  81045. serializationObject.particleSystems = [];
  81046. for (index = 0; index < scene.particleSystems.length; index++) {
  81047. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  81048. }
  81049. // Lens flares
  81050. serializationObject.lensFlareSystems = [];
  81051. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  81052. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  81053. }
  81054. // Shadows
  81055. serializationObject.shadowGenerators = [];
  81056. for (index = 0; index < scene.lights.length; index++) {
  81057. light = scene.lights[index];
  81058. var shadowGenerator = light.getShadowGenerator();
  81059. if (shadowGenerator) {
  81060. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  81061. }
  81062. }
  81063. // Action Manager
  81064. if (scene.actionManager) {
  81065. serializationObject.actions = scene.actionManager.serialize("scene");
  81066. }
  81067. // Audio
  81068. serializationObject.sounds = [];
  81069. for (index = 0; index < scene.soundTracks.length; index++) {
  81070. var soundtrack = scene.soundTracks[index];
  81071. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  81072. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  81073. }
  81074. }
  81075. return serializationObject;
  81076. };
  81077. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  81078. if (withParents === void 0) { withParents = false; }
  81079. if (withChildren === void 0) { withChildren = false; }
  81080. var serializationObject = {};
  81081. SceneSerializer.ClearCache();
  81082. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  81083. if (withParents || withChildren) {
  81084. //deliberate for loop! not for each, appended should be processed as well.
  81085. for (var i = 0; i < toSerialize.length; ++i) {
  81086. if (withChildren) {
  81087. toSerialize[i].getDescendants().forEach(function (node) {
  81088. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  81089. toSerialize.push(node);
  81090. }
  81091. });
  81092. }
  81093. //make sure the array doesn't contain the object already
  81094. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  81095. toSerialize.push(toSerialize[i].parent);
  81096. }
  81097. }
  81098. }
  81099. toSerialize.forEach(function (mesh) {
  81100. finalizeSingleMesh(mesh, serializationObject);
  81101. });
  81102. return serializationObject;
  81103. };
  81104. return SceneSerializer;
  81105. }());
  81106. BABYLON.SceneSerializer = SceneSerializer;
  81107. })(BABYLON || (BABYLON = {}));
  81108. //# sourceMappingURL=babylon.sceneSerializer.js.map
  81109. var BABYLON;
  81110. (function (BABYLON) {
  81111. var ReflectionProbe = /** @class */ (function () {
  81112. function ReflectionProbe(name, size, scene, generateMipMaps) {
  81113. if (generateMipMaps === void 0) { generateMipMaps = true; }
  81114. var _this = this;
  81115. this.name = name;
  81116. this._viewMatrix = BABYLON.Matrix.Identity();
  81117. this._target = BABYLON.Vector3.Zero();
  81118. this._add = BABYLON.Vector3.Zero();
  81119. this.invertYAxis = false;
  81120. this.position = BABYLON.Vector3.Zero();
  81121. this._scene = scene;
  81122. this._scene.reflectionProbes.push(this);
  81123. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  81124. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  81125. switch (faceIndex) {
  81126. case 0:
  81127. _this._add.copyFromFloats(1, 0, 0);
  81128. break;
  81129. case 1:
  81130. _this._add.copyFromFloats(-1, 0, 0);
  81131. break;
  81132. case 2:
  81133. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  81134. break;
  81135. case 3:
  81136. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  81137. break;
  81138. case 4:
  81139. _this._add.copyFromFloats(0, 0, 1);
  81140. break;
  81141. case 5:
  81142. _this._add.copyFromFloats(0, 0, -1);
  81143. break;
  81144. }
  81145. if (_this._attachedMesh) {
  81146. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  81147. }
  81148. _this.position.addToRef(_this._add, _this._target);
  81149. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  81150. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  81151. scene._forcedViewPosition = _this.position;
  81152. });
  81153. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  81154. scene._forcedViewPosition = null;
  81155. scene.updateTransformMatrix(true);
  81156. });
  81157. if (scene.activeCamera) {
  81158. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  81159. }
  81160. }
  81161. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  81162. get: function () {
  81163. return this._renderTargetTexture.samples;
  81164. },
  81165. set: function (value) {
  81166. this._renderTargetTexture.samples = value;
  81167. },
  81168. enumerable: true,
  81169. configurable: true
  81170. });
  81171. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  81172. get: function () {
  81173. return this._renderTargetTexture.refreshRate;
  81174. },
  81175. set: function (value) {
  81176. this._renderTargetTexture.refreshRate = value;
  81177. },
  81178. enumerable: true,
  81179. configurable: true
  81180. });
  81181. ReflectionProbe.prototype.getScene = function () {
  81182. return this._scene;
  81183. };
  81184. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  81185. get: function () {
  81186. return this._renderTargetTexture;
  81187. },
  81188. enumerable: true,
  81189. configurable: true
  81190. });
  81191. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  81192. get: function () {
  81193. return this._renderTargetTexture.renderList;
  81194. },
  81195. enumerable: true,
  81196. configurable: true
  81197. });
  81198. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  81199. this._attachedMesh = mesh;
  81200. };
  81201. /**
  81202. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  81203. *
  81204. * @param renderingGroupId The rendering group id corresponding to its index
  81205. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  81206. */
  81207. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  81208. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  81209. };
  81210. ReflectionProbe.prototype.dispose = function () {
  81211. var index = this._scene.reflectionProbes.indexOf(this);
  81212. if (index !== -1) {
  81213. // Remove from the scene if found
  81214. this._scene.reflectionProbes.splice(index, 1);
  81215. }
  81216. if (this._renderTargetTexture) {
  81217. this._renderTargetTexture.dispose();
  81218. this._renderTargetTexture = null;
  81219. }
  81220. };
  81221. return ReflectionProbe;
  81222. }());
  81223. BABYLON.ReflectionProbe = ReflectionProbe;
  81224. })(BABYLON || (BABYLON = {}));
  81225. //# sourceMappingURL=babylon.reflectionProbe.js.map
  81226. var BABYLON;
  81227. (function (BABYLON) {
  81228. var Layer = /** @class */ (function () {
  81229. function Layer(name, imgUrl, scene, isBackground, color) {
  81230. this.name = name;
  81231. this.scale = new BABYLON.Vector2(1, 1);
  81232. this.offset = new BABYLON.Vector2(0, 0);
  81233. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  81234. this.layerMask = 0x0FFFFFFF;
  81235. this._vertexBuffers = {};
  81236. // Events
  81237. /**
  81238. * An event triggered when the layer is disposed.
  81239. * @type {BABYLON.Observable}
  81240. */
  81241. this.onDisposeObservable = new BABYLON.Observable();
  81242. /**
  81243. * An event triggered before rendering the scene
  81244. * @type {BABYLON.Observable}
  81245. */
  81246. this.onBeforeRenderObservable = new BABYLON.Observable();
  81247. /**
  81248. * An event triggered after rendering the scene
  81249. * @type {BABYLON.Observable}
  81250. */
  81251. this.onAfterRenderObservable = new BABYLON.Observable();
  81252. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  81253. this.isBackground = isBackground === undefined ? true : isBackground;
  81254. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  81255. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  81256. this._scene.layers.push(this);
  81257. var engine = this._scene.getEngine();
  81258. // VBO
  81259. var vertices = [];
  81260. vertices.push(1, 1);
  81261. vertices.push(-1, 1);
  81262. vertices.push(-1, -1);
  81263. vertices.push(1, -1);
  81264. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81265. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  81266. this._createIndexBuffer();
  81267. // Effects
  81268. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  81269. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  81270. }
  81271. Object.defineProperty(Layer.prototype, "onDispose", {
  81272. set: function (callback) {
  81273. if (this._onDisposeObserver) {
  81274. this.onDisposeObservable.remove(this._onDisposeObserver);
  81275. }
  81276. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  81277. },
  81278. enumerable: true,
  81279. configurable: true
  81280. });
  81281. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  81282. set: function (callback) {
  81283. if (this._onBeforeRenderObserver) {
  81284. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  81285. }
  81286. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  81287. },
  81288. enumerable: true,
  81289. configurable: true
  81290. });
  81291. Object.defineProperty(Layer.prototype, "onAfterRender", {
  81292. set: function (callback) {
  81293. if (this._onAfterRenderObserver) {
  81294. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  81295. }
  81296. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  81297. },
  81298. enumerable: true,
  81299. configurable: true
  81300. });
  81301. Layer.prototype._createIndexBuffer = function () {
  81302. var engine = this._scene.getEngine();
  81303. // Indices
  81304. var indices = [];
  81305. indices.push(0);
  81306. indices.push(1);
  81307. indices.push(2);
  81308. indices.push(0);
  81309. indices.push(2);
  81310. indices.push(3);
  81311. this._indexBuffer = engine.createIndexBuffer(indices);
  81312. };
  81313. Layer.prototype._rebuild = function () {
  81314. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81315. if (vb) {
  81316. vb._rebuild();
  81317. }
  81318. this._createIndexBuffer();
  81319. };
  81320. Layer.prototype.render = function () {
  81321. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  81322. // Check
  81323. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  81324. return;
  81325. var engine = this._scene.getEngine();
  81326. this.onBeforeRenderObservable.notifyObservers(this);
  81327. // Render
  81328. engine.enableEffect(currentEffect);
  81329. engine.setState(false);
  81330. // Texture
  81331. currentEffect.setTexture("textureSampler", this.texture);
  81332. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  81333. // Color
  81334. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  81335. // Scale / offset
  81336. currentEffect.setVector2("offset", this.offset);
  81337. currentEffect.setVector2("scale", this.scale);
  81338. // VBOs
  81339. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  81340. // Draw order
  81341. if (!this.alphaTest) {
  81342. engine.setAlphaMode(this.alphaBlendingMode);
  81343. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81344. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81345. }
  81346. else {
  81347. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81348. }
  81349. this.onAfterRenderObservable.notifyObservers(this);
  81350. };
  81351. Layer.prototype.dispose = function () {
  81352. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81353. if (vertexBuffer) {
  81354. vertexBuffer.dispose();
  81355. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81356. }
  81357. if (this._indexBuffer) {
  81358. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81359. this._indexBuffer = null;
  81360. }
  81361. if (this.texture) {
  81362. this.texture.dispose();
  81363. this.texture = null;
  81364. }
  81365. // Remove from scene
  81366. var index = this._scene.layers.indexOf(this);
  81367. this._scene.layers.splice(index, 1);
  81368. // Callback
  81369. this.onDisposeObservable.notifyObservers(this);
  81370. this.onDisposeObservable.clear();
  81371. this.onAfterRenderObservable.clear();
  81372. this.onBeforeRenderObservable.clear();
  81373. };
  81374. return Layer;
  81375. }());
  81376. BABYLON.Layer = Layer;
  81377. })(BABYLON || (BABYLON = {}));
  81378. //# sourceMappingURL=babylon.layer.js.map
  81379. var BABYLON;
  81380. (function (BABYLON) {
  81381. var TextureTools = /** @class */ (function () {
  81382. function TextureTools() {
  81383. }
  81384. /**
  81385. * Uses the GPU to create a copy texture rescaled at a given size
  81386. * @param texture Texture to copy from
  81387. * @param width Desired width
  81388. * @param height Desired height
  81389. * @return Generated texture
  81390. */
  81391. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  81392. if (useBilinearMode === void 0) { useBilinearMode = true; }
  81393. var scene = texture.getScene();
  81394. var engine = scene.getEngine();
  81395. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  81396. rtt.wrapU = texture.wrapU;
  81397. rtt.wrapV = texture.wrapV;
  81398. rtt.uOffset = texture.uOffset;
  81399. rtt.vOffset = texture.vOffset;
  81400. rtt.uScale = texture.uScale;
  81401. rtt.vScale = texture.vScale;
  81402. rtt.uAng = texture.uAng;
  81403. rtt.vAng = texture.vAng;
  81404. rtt.wAng = texture.wAng;
  81405. rtt.coordinatesIndex = texture.coordinatesIndex;
  81406. rtt.level = texture.level;
  81407. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  81408. rtt._texture.isReady = false;
  81409. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81410. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81411. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81412. passPostProcess.getEffect().executeWhenCompiled(function () {
  81413. passPostProcess.onApply = function (effect) {
  81414. effect.setTexture("textureSampler", texture);
  81415. };
  81416. var internalTexture = rtt.getInternalTexture();
  81417. if (internalTexture) {
  81418. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  81419. engine.unBindFramebuffer(internalTexture);
  81420. rtt.disposeFramebufferObjects();
  81421. passPostProcess.dispose();
  81422. internalTexture.isReady = true;
  81423. }
  81424. });
  81425. return rtt;
  81426. };
  81427. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  81428. if (!scene._environmentBRDFTexture) {
  81429. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81430. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81431. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81432. scene._environmentBRDFTexture = texture;
  81433. }
  81434. return scene._environmentBRDFTexture;
  81435. };
  81436. 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=";
  81437. return TextureTools;
  81438. }());
  81439. BABYLON.TextureTools = TextureTools;
  81440. })(BABYLON || (BABYLON = {}));
  81441. //# sourceMappingURL=babylon.textureTools.js.map
  81442. var BABYLON;
  81443. (function (BABYLON) {
  81444. var FramingBehavior = /** @class */ (function () {
  81445. function FramingBehavior() {
  81446. this._mode = FramingBehavior.FitFrustumSidesMode;
  81447. this._radiusScale = 1.0;
  81448. this._positionScale = 0.5;
  81449. this._defaultElevation = 0.3;
  81450. this._elevationReturnTime = 1500;
  81451. this._elevationReturnWaitTime = 1000;
  81452. this._zoomStopsAnimation = false;
  81453. this._framingTime = 1500;
  81454. this._isPointerDown = false;
  81455. this._lastInteractionTime = -Infinity;
  81456. // Framing control
  81457. this._animatables = new Array();
  81458. this._betaIsAnimating = false;
  81459. }
  81460. Object.defineProperty(FramingBehavior.prototype, "name", {
  81461. get: function () {
  81462. return "Framing";
  81463. },
  81464. enumerable: true,
  81465. configurable: true
  81466. });
  81467. Object.defineProperty(FramingBehavior.prototype, "mode", {
  81468. /**
  81469. * Gets current mode used by the behavior.
  81470. */
  81471. get: function () {
  81472. return this._mode;
  81473. },
  81474. /**
  81475. * Sets the current mode used by the behavior
  81476. */
  81477. set: function (mode) {
  81478. this._mode = mode;
  81479. },
  81480. enumerable: true,
  81481. configurable: true
  81482. });
  81483. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  81484. /**
  81485. * Gets the scale applied to the radius
  81486. */
  81487. get: function () {
  81488. return this._radiusScale;
  81489. },
  81490. /**
  81491. * Sets the scale applied to the radius (1 by default)
  81492. */
  81493. set: function (radius) {
  81494. this._radiusScale = radius;
  81495. },
  81496. enumerable: true,
  81497. configurable: true
  81498. });
  81499. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  81500. /**
  81501. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  81502. */
  81503. get: function () {
  81504. return this._positionScale;
  81505. },
  81506. /**
  81507. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  81508. */
  81509. set: function (scale) {
  81510. this._positionScale = scale;
  81511. },
  81512. enumerable: true,
  81513. configurable: true
  81514. });
  81515. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  81516. /**
  81517. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  81518. * behaviour is triggered, in radians.
  81519. */
  81520. get: function () {
  81521. return this._defaultElevation;
  81522. },
  81523. /**
  81524. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  81525. * behaviour is triggered, in radians.
  81526. */
  81527. set: function (elevation) {
  81528. this._defaultElevation = elevation;
  81529. },
  81530. enumerable: true,
  81531. configurable: true
  81532. });
  81533. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  81534. /**
  81535. * Gets the time (in milliseconds) taken to return to the default beta position.
  81536. * Negative value indicates camera should not return to default.
  81537. */
  81538. get: function () {
  81539. return this._elevationReturnTime;
  81540. },
  81541. /**
  81542. * Sets the time (in milliseconds) taken to return to the default beta position.
  81543. * Negative value indicates camera should not return to default.
  81544. */
  81545. set: function (speed) {
  81546. this._elevationReturnTime = speed;
  81547. },
  81548. enumerable: true,
  81549. configurable: true
  81550. });
  81551. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  81552. /**
  81553. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  81554. */
  81555. get: function () {
  81556. return this._elevationReturnWaitTime;
  81557. },
  81558. /**
  81559. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  81560. */
  81561. set: function (time) {
  81562. this._elevationReturnWaitTime = time;
  81563. },
  81564. enumerable: true,
  81565. configurable: true
  81566. });
  81567. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  81568. /**
  81569. * Gets the flag that indicates if user zooming should stop animation.
  81570. */
  81571. get: function () {
  81572. return this._zoomStopsAnimation;
  81573. },
  81574. /**
  81575. * Sets the flag that indicates if user zooming should stop animation.
  81576. */
  81577. set: function (flag) {
  81578. this._zoomStopsAnimation = flag;
  81579. },
  81580. enumerable: true,
  81581. configurable: true
  81582. });
  81583. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  81584. /**
  81585. * Gets the transition time when framing the mesh, in milliseconds
  81586. */
  81587. get: function () {
  81588. return this._framingTime;
  81589. },
  81590. /**
  81591. * Sets the transition time when framing the mesh, in milliseconds
  81592. */
  81593. set: function (time) {
  81594. this._framingTime = time;
  81595. },
  81596. enumerable: true,
  81597. configurable: true
  81598. });
  81599. FramingBehavior.prototype.init = function () {
  81600. // Do notihng
  81601. };
  81602. FramingBehavior.prototype.attach = function (camera) {
  81603. var _this = this;
  81604. this._attachedCamera = camera;
  81605. var scene = this._attachedCamera.getScene();
  81606. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  81607. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  81608. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  81609. _this._isPointerDown = true;
  81610. return;
  81611. }
  81612. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  81613. _this._isPointerDown = false;
  81614. }
  81615. });
  81616. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  81617. if (mesh) {
  81618. _this.zoomOnMesh(mesh);
  81619. }
  81620. });
  81621. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81622. // Stop the animation if there is user interaction and the animation should stop for this interaction
  81623. _this._applyUserInteraction();
  81624. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  81625. // back to the default position after a given timeout
  81626. _this._maintainCameraAboveGround();
  81627. });
  81628. };
  81629. FramingBehavior.prototype.detach = function () {
  81630. if (!this._attachedCamera) {
  81631. return;
  81632. }
  81633. var scene = this._attachedCamera.getScene();
  81634. if (this._onPrePointerObservableObserver) {
  81635. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  81636. }
  81637. if (this._onAfterCheckInputsObserver) {
  81638. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81639. }
  81640. if (this._onMeshTargetChangedObserver) {
  81641. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81642. }
  81643. this._attachedCamera = null;
  81644. };
  81645. /**
  81646. * Targets the given mesh and updates zoom level accordingly.
  81647. * @param mesh The mesh to target.
  81648. * @param radius Optional. If a cached radius position already exists, overrides default.
  81649. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81650. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81651. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81652. */
  81653. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  81654. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81655. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81656. mesh.computeWorldMatrix(true);
  81657. var boundingBox = mesh.getBoundingInfo().boundingBox;
  81658. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  81659. };
  81660. /**
  81661. * Targets the given mesh with its children and updates zoom level accordingly.
  81662. * @param mesh The mesh to target.
  81663. * @param radius Optional. If a cached radius position already exists, overrides default.
  81664. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81665. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81666. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81667. */
  81668. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  81669. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81670. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81671. mesh.computeWorldMatrix(true);
  81672. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  81673. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  81674. };
  81675. /**
  81676. * Targets the given meshes with their children and updates zoom level accordingly.
  81677. * @param meshes The mesh to target.
  81678. * @param radius Optional. If a cached radius position already exists, overrides default.
  81679. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81680. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81681. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81682. */
  81683. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  81684. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81685. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81686. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  81687. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  81688. for (var i = 0; i < meshes.length; i++) {
  81689. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  81690. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  81691. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  81692. }
  81693. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  81694. };
  81695. /**
  81696. * Targets the given mesh and updates zoom level accordingly.
  81697. * @param mesh The mesh to target.
  81698. * @param radius Optional. If a cached radius position already exists, overrides default.
  81699. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81700. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81701. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81702. */
  81703. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  81704. var _this = this;
  81705. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81706. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81707. var zoomTarget;
  81708. if (!this._attachedCamera) {
  81709. return;
  81710. }
  81711. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  81712. var bottom = minimumWorld.y;
  81713. var top = maximumWorld.y;
  81714. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  81715. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  81716. if (focusOnOriginXZ) {
  81717. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  81718. }
  81719. else {
  81720. var centerWorld = minimumWorld.add(radiusWorld);
  81721. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  81722. }
  81723. if (!this._vectorTransition) {
  81724. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  81725. }
  81726. this._betaIsAnimating = true;
  81727. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  81728. if (animatable) {
  81729. this._animatables.push(animatable);
  81730. }
  81731. // sets the radius and lower radius bounds
  81732. // Small delta ensures camera is not always at lower zoom limit.
  81733. var radius = 0;
  81734. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  81735. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  81736. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  81737. radius = position;
  81738. }
  81739. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  81740. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  81741. if (this._attachedCamera.lowerRadiusLimit === null) {
  81742. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  81743. }
  81744. }
  81745. // Set sensibilities
  81746. var extend = maximumWorld.subtract(minimumWorld).length();
  81747. this._attachedCamera.panningSensibility = 5000 / extend;
  81748. this._attachedCamera.wheelPrecision = 100 / radius;
  81749. // transition to new radius
  81750. if (!this._radiusTransition) {
  81751. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  81752. }
  81753. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  81754. if (onAnimationEnd) {
  81755. onAnimationEnd();
  81756. }
  81757. if (_this._attachedCamera) {
  81758. _this._attachedCamera.storeState();
  81759. }
  81760. });
  81761. if (animatable) {
  81762. this._animatables.push(animatable);
  81763. }
  81764. };
  81765. /**
  81766. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  81767. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  81768. * frustum width.
  81769. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  81770. * to fully enclose the mesh in the viewing frustum.
  81771. */
  81772. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  81773. var size = maximumWorld.subtract(minimumWorld);
  81774. var boxVectorGlobalDiagonal = size.length();
  81775. var frustumSlope = this._getFrustumSlope();
  81776. // Formula for setting distance
  81777. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  81778. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  81779. // Horizon distance
  81780. var radius = radiusWithoutFraming * this._radiusScale;
  81781. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  81782. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  81783. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  81784. var camera = this._attachedCamera;
  81785. if (!camera) {
  81786. return 0;
  81787. }
  81788. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  81789. // Don't exceed the requested limit
  81790. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  81791. }
  81792. // Don't exceed the upper radius limit
  81793. if (camera.upperRadiusLimit) {
  81794. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  81795. }
  81796. return distance;
  81797. };
  81798. /**
  81799. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  81800. * is automatically returned to its default position (expected to be above ground plane).
  81801. */
  81802. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  81803. var _this = this;
  81804. if (this._elevationReturnTime < 0) {
  81805. return;
  81806. }
  81807. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  81808. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  81809. var limitBeta = Math.PI * 0.5;
  81810. // Bring the camera back up if below the ground plane
  81811. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  81812. this._betaIsAnimating = true;
  81813. //Transition to new position
  81814. this.stopAllAnimations();
  81815. if (!this._betaTransition) {
  81816. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  81817. }
  81818. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  81819. _this._clearAnimationLocks();
  81820. _this.stopAllAnimations();
  81821. });
  81822. if (animatabe) {
  81823. this._animatables.push(animatabe);
  81824. }
  81825. }
  81826. };
  81827. /**
  81828. * Returns the frustum slope based on the canvas ratio and camera FOV
  81829. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  81830. */
  81831. FramingBehavior.prototype._getFrustumSlope = function () {
  81832. // Calculate the viewport ratio
  81833. // Aspect Ratio is Height/Width.
  81834. var camera = this._attachedCamera;
  81835. if (!camera) {
  81836. return BABYLON.Vector2.Zero();
  81837. }
  81838. var engine = camera.getScene().getEngine();
  81839. var aspectRatio = engine.getAspectRatio(camera);
  81840. // Camera FOV is the vertical field of view (top-bottom) in radians.
  81841. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  81842. var frustumSlopeY = Math.tan(camera.fov / 2);
  81843. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  81844. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  81845. // along the forward vector.
  81846. var frustumSlopeX = frustumSlopeY * aspectRatio;
  81847. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  81848. };
  81849. /**
  81850. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  81851. */
  81852. FramingBehavior.prototype._clearAnimationLocks = function () {
  81853. this._betaIsAnimating = false;
  81854. };
  81855. /**
  81856. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  81857. */
  81858. FramingBehavior.prototype._applyUserInteraction = function () {
  81859. if (this.isUserIsMoving) {
  81860. this._lastInteractionTime = BABYLON.Tools.Now;
  81861. this.stopAllAnimations();
  81862. this._clearAnimationLocks();
  81863. }
  81864. };
  81865. /**
  81866. * Stops and removes all animations that have been applied to the camera
  81867. */
  81868. FramingBehavior.prototype.stopAllAnimations = function () {
  81869. if (this._attachedCamera) {
  81870. this._attachedCamera.animations = [];
  81871. }
  81872. while (this._animatables.length) {
  81873. if (this._animatables[0]) {
  81874. this._animatables[0].onAnimationEnd = null;
  81875. this._animatables[0].stop();
  81876. }
  81877. this._animatables.shift();
  81878. }
  81879. };
  81880. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  81881. /**
  81882. * Gets a value indicating if the user is moving the camera
  81883. */
  81884. get: function () {
  81885. if (!this._attachedCamera) {
  81886. return false;
  81887. }
  81888. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  81889. this._attachedCamera.inertialBetaOffset !== 0 ||
  81890. this._attachedCamera.inertialRadiusOffset !== 0 ||
  81891. this._attachedCamera.inertialPanningX !== 0 ||
  81892. this._attachedCamera.inertialPanningY !== 0 ||
  81893. this._isPointerDown;
  81894. },
  81895. enumerable: true,
  81896. configurable: true
  81897. });
  81898. /**
  81899. * The easing function used by animations
  81900. */
  81901. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  81902. /**
  81903. * The easing mode used by animations
  81904. */
  81905. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  81906. // Statics
  81907. /**
  81908. * The camera can move all the way towards the mesh.
  81909. */
  81910. FramingBehavior.IgnoreBoundsSizeMode = 0;
  81911. /**
  81912. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  81913. */
  81914. FramingBehavior.FitFrustumSidesMode = 1;
  81915. return FramingBehavior;
  81916. }());
  81917. BABYLON.FramingBehavior = FramingBehavior;
  81918. })(BABYLON || (BABYLON = {}));
  81919. //# sourceMappingURL=babylon.framingBehavior.js.map
  81920. var BABYLON;
  81921. (function (BABYLON) {
  81922. /**
  81923. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  81924. */
  81925. var BouncingBehavior = /** @class */ (function () {
  81926. function BouncingBehavior() {
  81927. /**
  81928. * The duration of the animation, in milliseconds
  81929. */
  81930. this.transitionDuration = 450;
  81931. /**
  81932. * Length of the distance animated by the transition when lower radius is reached
  81933. */
  81934. this.lowerRadiusTransitionRange = 2;
  81935. /**
  81936. * Length of the distance animated by the transition when upper radius is reached
  81937. */
  81938. this.upperRadiusTransitionRange = -2;
  81939. this._autoTransitionRange = false;
  81940. // Animations
  81941. this._radiusIsAnimating = false;
  81942. this._radiusBounceTransition = null;
  81943. this._animatables = new Array();
  81944. }
  81945. Object.defineProperty(BouncingBehavior.prototype, "name", {
  81946. get: function () {
  81947. return "Bouncing";
  81948. },
  81949. enumerable: true,
  81950. configurable: true
  81951. });
  81952. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  81953. /**
  81954. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81955. */
  81956. get: function () {
  81957. return this._autoTransitionRange;
  81958. },
  81959. /**
  81960. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81961. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  81962. */
  81963. set: function (value) {
  81964. var _this = this;
  81965. if (this._autoTransitionRange === value) {
  81966. return;
  81967. }
  81968. this._autoTransitionRange = value;
  81969. var camera = this._attachedCamera;
  81970. if (!camera) {
  81971. return;
  81972. }
  81973. if (value) {
  81974. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  81975. if (!mesh) {
  81976. return;
  81977. }
  81978. mesh.computeWorldMatrix(true);
  81979. var diagonal = mesh.getBoundingInfo().diagonalLength;
  81980. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  81981. _this.upperRadiusTransitionRange = diagonal * 0.05;
  81982. });
  81983. }
  81984. else if (this._onMeshTargetChangedObserver) {
  81985. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81986. }
  81987. },
  81988. enumerable: true,
  81989. configurable: true
  81990. });
  81991. BouncingBehavior.prototype.init = function () {
  81992. // Do notihng
  81993. };
  81994. BouncingBehavior.prototype.attach = function (camera) {
  81995. var _this = this;
  81996. this._attachedCamera = camera;
  81997. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81998. if (!_this._attachedCamera) {
  81999. return;
  82000. }
  82001. // Add the bounce animation to the lower radius limit
  82002. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  82003. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  82004. }
  82005. // Add the bounce animation to the upper radius limit
  82006. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  82007. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  82008. }
  82009. });
  82010. };
  82011. BouncingBehavior.prototype.detach = function () {
  82012. if (!this._attachedCamera) {
  82013. return;
  82014. }
  82015. if (this._onAfterCheckInputsObserver) {
  82016. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82017. }
  82018. if (this._onMeshTargetChangedObserver) {
  82019. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  82020. }
  82021. this._attachedCamera = null;
  82022. };
  82023. /**
  82024. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  82025. * @param radiusLimit The limit to check against.
  82026. * @return Bool to indicate if at limit.
  82027. */
  82028. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  82029. if (!this._attachedCamera) {
  82030. return false;
  82031. }
  82032. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  82033. return true;
  82034. }
  82035. return false;
  82036. };
  82037. /**
  82038. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  82039. * @param radiusDelta The delta by which to animate to. Can be negative.
  82040. */
  82041. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  82042. var _this = this;
  82043. if (!this._attachedCamera) {
  82044. return;
  82045. }
  82046. if (!this._radiusBounceTransition) {
  82047. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  82048. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  82049. }
  82050. // Prevent zoom until bounce has completed
  82051. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  82052. this._attachedCamera.wheelPrecision = Infinity;
  82053. this._attachedCamera.inertialRadiusOffset = 0;
  82054. // Animate to the radius limit
  82055. this.stopAllAnimations();
  82056. this._radiusIsAnimating = true;
  82057. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  82058. if (animatable) {
  82059. this._animatables.push(animatable);
  82060. }
  82061. };
  82062. /**
  82063. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  82064. */
  82065. BouncingBehavior.prototype._clearAnimationLocks = function () {
  82066. this._radiusIsAnimating = false;
  82067. if (this._attachedCamera) {
  82068. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  82069. }
  82070. };
  82071. /**
  82072. * Stops and removes all animations that have been applied to the camera
  82073. */
  82074. BouncingBehavior.prototype.stopAllAnimations = function () {
  82075. if (this._attachedCamera) {
  82076. this._attachedCamera.animations = [];
  82077. }
  82078. while (this._animatables.length) {
  82079. this._animatables[0].onAnimationEnd = null;
  82080. this._animatables[0].stop();
  82081. this._animatables.shift();
  82082. }
  82083. };
  82084. /**
  82085. * The easing function used by animations
  82086. */
  82087. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  82088. /**
  82089. * The easing mode used by animations
  82090. */
  82091. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  82092. return BouncingBehavior;
  82093. }());
  82094. BABYLON.BouncingBehavior = BouncingBehavior;
  82095. })(BABYLON || (BABYLON = {}));
  82096. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  82097. var BABYLON;
  82098. (function (BABYLON) {
  82099. var AutoRotationBehavior = /** @class */ (function () {
  82100. function AutoRotationBehavior() {
  82101. this._zoomStopsAnimation = false;
  82102. this._idleRotationSpeed = 0.05;
  82103. this._idleRotationWaitTime = 2000;
  82104. this._idleRotationSpinupTime = 2000;
  82105. this._isPointerDown = false;
  82106. this._lastFrameTime = null;
  82107. this._lastInteractionTime = -Infinity;
  82108. this._cameraRotationSpeed = 0;
  82109. this._lastFrameRadius = 0;
  82110. }
  82111. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  82112. get: function () {
  82113. return "AutoRotation";
  82114. },
  82115. enumerable: true,
  82116. configurable: true
  82117. });
  82118. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  82119. /**
  82120. * Gets the flag that indicates if user zooming should stop animation.
  82121. */
  82122. get: function () {
  82123. return this._zoomStopsAnimation;
  82124. },
  82125. /**
  82126. * Sets the flag that indicates if user zooming should stop animation.
  82127. */
  82128. set: function (flag) {
  82129. this._zoomStopsAnimation = flag;
  82130. },
  82131. enumerable: true,
  82132. configurable: true
  82133. });
  82134. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  82135. /**
  82136. * Gets the default speed at which the camera rotates around the model.
  82137. */
  82138. get: function () {
  82139. return this._idleRotationSpeed;
  82140. },
  82141. /**
  82142. * Sets the default speed at which the camera rotates around the model.
  82143. */
  82144. set: function (speed) {
  82145. this._idleRotationSpeed = speed;
  82146. },
  82147. enumerable: true,
  82148. configurable: true
  82149. });
  82150. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  82151. /**
  82152. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  82153. */
  82154. get: function () {
  82155. return this._idleRotationWaitTime;
  82156. },
  82157. /**
  82158. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  82159. */
  82160. set: function (time) {
  82161. this._idleRotationWaitTime = time;
  82162. },
  82163. enumerable: true,
  82164. configurable: true
  82165. });
  82166. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  82167. /**
  82168. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  82169. */
  82170. get: function () {
  82171. return this._idleRotationSpinupTime;
  82172. },
  82173. /**
  82174. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  82175. */
  82176. set: function (time) {
  82177. this._idleRotationSpinupTime = time;
  82178. },
  82179. enumerable: true,
  82180. configurable: true
  82181. });
  82182. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  82183. /**
  82184. * Gets a value indicating if the camera is currently rotating because of this behavior
  82185. */
  82186. get: function () {
  82187. return Math.abs(this._cameraRotationSpeed) > 0;
  82188. },
  82189. enumerable: true,
  82190. configurable: true
  82191. });
  82192. AutoRotationBehavior.prototype.init = function () {
  82193. // Do notihng
  82194. };
  82195. AutoRotationBehavior.prototype.attach = function (camera) {
  82196. var _this = this;
  82197. this._attachedCamera = camera;
  82198. var scene = this._attachedCamera.getScene();
  82199. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  82200. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  82201. _this._isPointerDown = true;
  82202. return;
  82203. }
  82204. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  82205. _this._isPointerDown = false;
  82206. }
  82207. });
  82208. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  82209. var now = BABYLON.Tools.Now;
  82210. var dt = 0;
  82211. if (_this._lastFrameTime != null) {
  82212. dt = now - _this._lastFrameTime;
  82213. }
  82214. _this._lastFrameTime = now;
  82215. // Stop the animation if there is user interaction and the animation should stop for this interaction
  82216. _this._applyUserInteraction();
  82217. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  82218. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  82219. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  82220. // Step camera rotation by rotation speed
  82221. if (_this._attachedCamera) {
  82222. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  82223. }
  82224. });
  82225. };
  82226. AutoRotationBehavior.prototype.detach = function () {
  82227. if (!this._attachedCamera) {
  82228. return;
  82229. }
  82230. var scene = this._attachedCamera.getScene();
  82231. if (this._onPrePointerObservableObserver) {
  82232. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  82233. }
  82234. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82235. this._attachedCamera = null;
  82236. };
  82237. /**
  82238. * Returns true if user is scrolling.
  82239. * @return true if user is scrolling.
  82240. */
  82241. AutoRotationBehavior.prototype._userIsZooming = function () {
  82242. if (!this._attachedCamera) {
  82243. return false;
  82244. }
  82245. return this._attachedCamera.inertialRadiusOffset !== 0;
  82246. };
  82247. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  82248. if (!this._attachedCamera) {
  82249. return false;
  82250. }
  82251. var zoomHasHitLimit = false;
  82252. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  82253. zoomHasHitLimit = true;
  82254. }
  82255. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  82256. this._lastFrameRadius = this._attachedCamera.radius;
  82257. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  82258. };
  82259. /**
  82260. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  82261. */
  82262. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  82263. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  82264. this._lastInteractionTime = BABYLON.Tools.Now;
  82265. }
  82266. };
  82267. // Tools
  82268. AutoRotationBehavior.prototype._userIsMoving = function () {
  82269. if (!this._attachedCamera) {
  82270. return false;
  82271. }
  82272. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  82273. this._attachedCamera.inertialBetaOffset !== 0 ||
  82274. this._attachedCamera.inertialRadiusOffset !== 0 ||
  82275. this._attachedCamera.inertialPanningX !== 0 ||
  82276. this._attachedCamera.inertialPanningY !== 0 ||
  82277. this._isPointerDown;
  82278. };
  82279. return AutoRotationBehavior;
  82280. }());
  82281. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  82282. })(BABYLON || (BABYLON = {}));
  82283. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  82284. var BABYLON;
  82285. (function (BABYLON) {
  82286. var NullEngineOptions = /** @class */ (function () {
  82287. function NullEngineOptions() {
  82288. this.renderWidth = 512;
  82289. this.renderHeight = 256;
  82290. this.textureSize = 512;
  82291. this.deterministicLockstep = false;
  82292. this.lockstepMaxSteps = 4;
  82293. }
  82294. return NullEngineOptions;
  82295. }());
  82296. BABYLON.NullEngineOptions = NullEngineOptions;
  82297. /**
  82298. * The null engine class provides support for headless version of babylon.js.
  82299. * This can be used in server side scenario or for testing purposes
  82300. */
  82301. var NullEngine = /** @class */ (function (_super) {
  82302. __extends(NullEngine, _super);
  82303. function NullEngine(options) {
  82304. if (options === void 0) { options = new NullEngineOptions(); }
  82305. var _this = _super.call(this, null) || this;
  82306. if (options.deterministicLockstep === undefined) {
  82307. options.deterministicLockstep = false;
  82308. }
  82309. if (options.lockstepMaxSteps === undefined) {
  82310. options.lockstepMaxSteps = 4;
  82311. }
  82312. _this._options = options;
  82313. // Init caps
  82314. // We consider we are on a webgl1 capable device
  82315. _this._caps = new BABYLON.EngineCapabilities();
  82316. _this._caps.maxTexturesImageUnits = 16;
  82317. _this._caps.maxVertexTextureImageUnits = 16;
  82318. _this._caps.maxTextureSize = 512;
  82319. _this._caps.maxCubemapTextureSize = 512;
  82320. _this._caps.maxRenderTextureSize = 512;
  82321. _this._caps.maxVertexAttribs = 16;
  82322. _this._caps.maxVaryingVectors = 16;
  82323. _this._caps.maxFragmentUniformVectors = 16;
  82324. _this._caps.maxVertexUniformVectors = 16;
  82325. // Extensions
  82326. _this._caps.standardDerivatives = false;
  82327. _this._caps.astc = null;
  82328. _this._caps.s3tc = null;
  82329. _this._caps.pvrtc = null;
  82330. _this._caps.etc1 = null;
  82331. _this._caps.etc2 = null;
  82332. _this._caps.textureAnisotropicFilterExtension = null;
  82333. _this._caps.maxAnisotropy = 0;
  82334. _this._caps.uintIndices = false;
  82335. _this._caps.fragmentDepthSupported = false;
  82336. _this._caps.highPrecisionShaderSupported = true;
  82337. _this._caps.colorBufferFloat = false;
  82338. _this._caps.textureFloat = false;
  82339. _this._caps.textureFloatLinearFiltering = false;
  82340. _this._caps.textureFloatRender = false;
  82341. _this._caps.textureHalfFloat = false;
  82342. _this._caps.textureHalfFloatLinearFiltering = false;
  82343. _this._caps.textureHalfFloatRender = false;
  82344. _this._caps.textureLOD = false;
  82345. _this._caps.drawBuffersExtension = false;
  82346. _this._caps.depthTextureExtension = false;
  82347. _this._caps.vertexArrayObject = false;
  82348. _this._caps.instancedArrays = false;
  82349. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  82350. // Wrappers
  82351. if (typeof URL === "undefined") {
  82352. URL = {
  82353. createObjectURL: function () { },
  82354. revokeObjectURL: function () { }
  82355. };
  82356. }
  82357. if (typeof Blob === "undefined") {
  82358. Blob = function () { };
  82359. }
  82360. return _this;
  82361. }
  82362. NullEngine.prototype.isDeterministicLockStep = function () {
  82363. return this._options.deterministicLockstep;
  82364. };
  82365. NullEngine.prototype.getLockstepMaxSteps = function () {
  82366. return this._options.lockstepMaxSteps;
  82367. };
  82368. NullEngine.prototype.createVertexBuffer = function (vertices) {
  82369. return {
  82370. capacity: 0,
  82371. references: 1,
  82372. is32Bits: false
  82373. };
  82374. };
  82375. NullEngine.prototype.createIndexBuffer = function (indices) {
  82376. return {
  82377. capacity: 0,
  82378. references: 1,
  82379. is32Bits: false
  82380. };
  82381. };
  82382. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  82383. if (stencil === void 0) { stencil = false; }
  82384. };
  82385. NullEngine.prototype.getRenderWidth = function (useScreen) {
  82386. if (useScreen === void 0) { useScreen = false; }
  82387. if (!useScreen && this._currentRenderTarget) {
  82388. return this._currentRenderTarget.width;
  82389. }
  82390. return this._options.renderWidth;
  82391. };
  82392. NullEngine.prototype.getRenderHeight = function (useScreen) {
  82393. if (useScreen === void 0) { useScreen = false; }
  82394. if (!useScreen && this._currentRenderTarget) {
  82395. return this._currentRenderTarget.height;
  82396. }
  82397. return this._options.renderHeight;
  82398. };
  82399. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  82400. this._cachedViewport = viewport;
  82401. };
  82402. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  82403. return {
  82404. transformFeedback: null,
  82405. __SPECTOR_rebuildProgram: null
  82406. };
  82407. };
  82408. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  82409. return [];
  82410. };
  82411. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  82412. return [];
  82413. };
  82414. NullEngine.prototype.bindSamplers = function (effect) {
  82415. this._currentEffect = null;
  82416. };
  82417. NullEngine.prototype.enableEffect = function (effect) {
  82418. this._currentEffect = effect;
  82419. if (effect.onBind) {
  82420. effect.onBind(effect);
  82421. }
  82422. effect.onBindObservable.notifyObservers(effect);
  82423. };
  82424. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  82425. if (zOffset === void 0) { zOffset = 0; }
  82426. if (reverseSide === void 0) { reverseSide = false; }
  82427. };
  82428. NullEngine.prototype.setIntArray = function (uniform, array) {
  82429. };
  82430. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  82431. };
  82432. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  82433. };
  82434. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  82435. };
  82436. NullEngine.prototype.setFloatArray = function (uniform, array) {
  82437. };
  82438. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  82439. };
  82440. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  82441. };
  82442. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  82443. };
  82444. NullEngine.prototype.setArray = function (uniform, array) {
  82445. };
  82446. NullEngine.prototype.setArray2 = function (uniform, array) {
  82447. };
  82448. NullEngine.prototype.setArray3 = function (uniform, array) {
  82449. };
  82450. NullEngine.prototype.setArray4 = function (uniform, array) {
  82451. };
  82452. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  82453. };
  82454. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  82455. };
  82456. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  82457. };
  82458. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  82459. };
  82460. NullEngine.prototype.setFloat = function (uniform, value) {
  82461. };
  82462. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  82463. };
  82464. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  82465. };
  82466. NullEngine.prototype.setBool = function (uniform, bool) {
  82467. };
  82468. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  82469. };
  82470. NullEngine.prototype.setColor3 = function (uniform, color3) {
  82471. };
  82472. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  82473. };
  82474. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  82475. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  82476. if (this._alphaMode === mode) {
  82477. return;
  82478. }
  82479. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  82480. if (!noDepthWriteChange) {
  82481. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  82482. }
  82483. this._alphaMode = mode;
  82484. };
  82485. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  82486. };
  82487. NullEngine.prototype.wipeCaches = function (bruteForce) {
  82488. if (this.preventCacheWipeBetweenFrames) {
  82489. return;
  82490. }
  82491. this.resetTextureCache();
  82492. this._currentEffect = null;
  82493. if (bruteForce) {
  82494. this._currentProgram = null;
  82495. this._stencilState.reset();
  82496. this._depthCullingState.reset();
  82497. this.setDepthFunctionToLessOrEqual();
  82498. this._alphaState.reset();
  82499. }
  82500. this._cachedVertexBuffers = null;
  82501. this._cachedIndexBuffer = null;
  82502. this._cachedEffectForVertexBuffers = null;
  82503. };
  82504. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  82505. };
  82506. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  82507. };
  82508. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  82509. };
  82510. NullEngine.prototype._createTexture = function () {
  82511. return {};
  82512. };
  82513. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  82514. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  82515. if (onLoad === void 0) { onLoad = null; }
  82516. if (onError === void 0) { onError = null; }
  82517. if (buffer === void 0) { buffer = null; }
  82518. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  82519. var url = String(urlArg);
  82520. texture.url = url;
  82521. texture.generateMipMaps = !noMipmap;
  82522. texture.samplingMode = samplingMode;
  82523. texture.invertY = invertY;
  82524. texture.baseWidth = this._options.textureSize;
  82525. texture.baseHeight = this._options.textureSize;
  82526. texture.width = this._options.textureSize;
  82527. texture.height = this._options.textureSize;
  82528. if (format) {
  82529. texture.format = format;
  82530. }
  82531. texture.isReady = true;
  82532. if (onLoad) {
  82533. onLoad();
  82534. }
  82535. return texture;
  82536. };
  82537. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  82538. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  82539. if (options !== undefined && typeof options === "object") {
  82540. fullOptions.generateMipMaps = options.generateMipMaps;
  82541. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  82542. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  82543. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  82544. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  82545. }
  82546. else {
  82547. fullOptions.generateMipMaps = options;
  82548. fullOptions.generateDepthBuffer = true;
  82549. fullOptions.generateStencilBuffer = false;
  82550. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82551. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82552. }
  82553. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  82554. var width = size.width || size;
  82555. var height = size.height || size;
  82556. texture._depthStencilBuffer = {};
  82557. texture._framebuffer = {};
  82558. texture.baseWidth = width;
  82559. texture.baseHeight = height;
  82560. texture.width = width;
  82561. texture.height = height;
  82562. texture.isReady = true;
  82563. texture.samples = 1;
  82564. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  82565. texture.samplingMode = fullOptions.samplingMode;
  82566. texture.type = fullOptions.type;
  82567. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  82568. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  82569. return texture;
  82570. };
  82571. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  82572. texture.samplingMode = samplingMode;
  82573. };
  82574. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  82575. if (this._currentRenderTarget) {
  82576. this.unBindFramebuffer(this._currentRenderTarget);
  82577. }
  82578. this._currentRenderTarget = texture;
  82579. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  82580. if (this._cachedViewport && !forceFullscreenViewport) {
  82581. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  82582. }
  82583. };
  82584. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  82585. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  82586. this._currentRenderTarget = null;
  82587. if (onBeforeUnbind) {
  82588. if (texture._MSAAFramebuffer) {
  82589. this._currentFramebuffer = texture._framebuffer;
  82590. }
  82591. onBeforeUnbind();
  82592. }
  82593. this._currentFramebuffer = null;
  82594. };
  82595. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  82596. var vbo = {
  82597. capacity: 1,
  82598. references: 1,
  82599. is32Bits: false
  82600. };
  82601. return vbo;
  82602. };
  82603. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  82604. if (offset === void 0) { offset = 0; }
  82605. };
  82606. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  82607. };
  82608. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  82609. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  82610. this._boundTexturesCache[this._activeChannel] = texture;
  82611. }
  82612. };
  82613. NullEngine.prototype._bindTexture = function (channel, texture) {
  82614. if (channel < 0) {
  82615. return;
  82616. }
  82617. this._bindTextureDirectly(0, texture);
  82618. };
  82619. NullEngine.prototype._releaseBuffer = function (buffer) {
  82620. buffer.references--;
  82621. if (buffer.references === 0) {
  82622. return true;
  82623. }
  82624. return false;
  82625. };
  82626. return NullEngine;
  82627. }(BABYLON.Engine));
  82628. BABYLON.NullEngine = NullEngine;
  82629. })(BABYLON || (BABYLON = {}));
  82630. //# sourceMappingURL=babylon.nullEngine.js.map
  82631. var BABYLON;
  82632. (function (BABYLON) {
  82633. /**
  82634. * This class can be used to get instrumentation data from a Babylon engine
  82635. */
  82636. var EngineInstrumentation = /** @class */ (function () {
  82637. function EngineInstrumentation(engine) {
  82638. this.engine = engine;
  82639. this._captureGPUFrameTime = false;
  82640. this._gpuFrameTime = new BABYLON.PerfCounter();
  82641. this._captureShaderCompilationTime = false;
  82642. this._shaderCompilationTime = new BABYLON.PerfCounter();
  82643. // Observers
  82644. this._onBeginFrameObserver = null;
  82645. this._onEndFrameObserver = null;
  82646. this._onBeforeShaderCompilationObserver = null;
  82647. this._onAfterShaderCompilationObserver = null;
  82648. }
  82649. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  82650. // Properties
  82651. /**
  82652. * Gets the perf counter used for GPU frame time
  82653. */
  82654. get: function () {
  82655. return this._gpuFrameTime;
  82656. },
  82657. enumerable: true,
  82658. configurable: true
  82659. });
  82660. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  82661. /**
  82662. * Gets the GPU frame time capture status
  82663. */
  82664. get: function () {
  82665. return this._captureGPUFrameTime;
  82666. },
  82667. /**
  82668. * Enable or disable the GPU frame time capture
  82669. */
  82670. set: function (value) {
  82671. var _this = this;
  82672. if (value === this._captureGPUFrameTime) {
  82673. return;
  82674. }
  82675. this._captureGPUFrameTime = value;
  82676. if (value) {
  82677. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  82678. if (!_this._gpuFrameTimeToken) {
  82679. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  82680. }
  82681. });
  82682. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  82683. if (!_this._gpuFrameTimeToken) {
  82684. return;
  82685. }
  82686. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  82687. if (time > -1) {
  82688. _this._gpuFrameTimeToken = null;
  82689. _this._gpuFrameTime.fetchNewFrame();
  82690. _this._gpuFrameTime.addCount(time, true);
  82691. }
  82692. });
  82693. }
  82694. else {
  82695. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  82696. this._onBeginFrameObserver = null;
  82697. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  82698. this._onEndFrameObserver = null;
  82699. }
  82700. },
  82701. enumerable: true,
  82702. configurable: true
  82703. });
  82704. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  82705. /**
  82706. * Gets the perf counter used for shader compilation time
  82707. */
  82708. get: function () {
  82709. return this._shaderCompilationTime;
  82710. },
  82711. enumerable: true,
  82712. configurable: true
  82713. });
  82714. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  82715. /**
  82716. * Gets the shader compilation time capture status
  82717. */
  82718. get: function () {
  82719. return this._captureShaderCompilationTime;
  82720. },
  82721. /**
  82722. * Enable or disable the shader compilation time capture
  82723. */
  82724. set: function (value) {
  82725. var _this = this;
  82726. if (value === this._captureShaderCompilationTime) {
  82727. return;
  82728. }
  82729. this._captureShaderCompilationTime = value;
  82730. if (value) {
  82731. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  82732. _this._shaderCompilationTime.fetchNewFrame();
  82733. _this._shaderCompilationTime.beginMonitoring();
  82734. });
  82735. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  82736. _this._shaderCompilationTime.endMonitoring();
  82737. });
  82738. }
  82739. else {
  82740. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  82741. this._onBeforeShaderCompilationObserver = null;
  82742. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  82743. this._onAfterShaderCompilationObserver = null;
  82744. }
  82745. },
  82746. enumerable: true,
  82747. configurable: true
  82748. });
  82749. EngineInstrumentation.prototype.dispose = function () {
  82750. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  82751. this._onBeginFrameObserver = null;
  82752. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  82753. this._onEndFrameObserver = null;
  82754. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  82755. this._onBeforeShaderCompilationObserver = null;
  82756. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  82757. this._onAfterShaderCompilationObserver = null;
  82758. this.engine = null;
  82759. };
  82760. return EngineInstrumentation;
  82761. }());
  82762. BABYLON.EngineInstrumentation = EngineInstrumentation;
  82763. })(BABYLON || (BABYLON = {}));
  82764. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  82765. var BABYLON;
  82766. (function (BABYLON) {
  82767. /**
  82768. * This class can be used to get instrumentation data from a Babylon engine
  82769. */
  82770. var SceneInstrumentation = /** @class */ (function () {
  82771. function SceneInstrumentation(scene) {
  82772. var _this = this;
  82773. this.scene = scene;
  82774. this._captureActiveMeshesEvaluationTime = false;
  82775. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  82776. this._captureRenderTargetsRenderTime = false;
  82777. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  82778. this._captureFrameTime = false;
  82779. this._frameTime = new BABYLON.PerfCounter();
  82780. this._captureRenderTime = false;
  82781. this._renderTime = new BABYLON.PerfCounter();
  82782. this._captureInterFrameTime = false;
  82783. this._interFrameTime = new BABYLON.PerfCounter();
  82784. this._captureParticlesRenderTime = false;
  82785. this._particlesRenderTime = new BABYLON.PerfCounter();
  82786. this._captureSpritesRenderTime = false;
  82787. this._spritesRenderTime = new BABYLON.PerfCounter();
  82788. this._capturePhysicsTime = false;
  82789. this._physicsTime = new BABYLON.PerfCounter();
  82790. this._captureAnimationsTime = false;
  82791. this._animationsTime = new BABYLON.PerfCounter();
  82792. // Observers
  82793. this._onBeforeActiveMeshesEvaluationObserver = null;
  82794. this._onAfterActiveMeshesEvaluationObserver = null;
  82795. this._onBeforeRenderTargetsRenderObserver = null;
  82796. this._onAfterRenderTargetsRenderObserver = null;
  82797. this._onAfterRenderObserver = null;
  82798. this._onBeforeDrawPhaseObserver = null;
  82799. this._onAfterDrawPhaseObserver = null;
  82800. this._onBeforeAnimationsObserver = null;
  82801. this._onBeforeParticlesRenderingObserver = null;
  82802. this._onAfterParticlesRenderingObserver = null;
  82803. this._onBeforeSpritesRenderingObserver = null;
  82804. this._onAfterSpritesRenderingObserver = null;
  82805. this._onBeforePhysicsObserver = null;
  82806. this._onAfterPhysicsObserver = null;
  82807. this._onAfterAnimationsObserver = null;
  82808. // Before render
  82809. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  82810. if (_this._captureActiveMeshesEvaluationTime) {
  82811. _this._activeMeshesEvaluationTime.fetchNewFrame();
  82812. }
  82813. if (_this._captureRenderTargetsRenderTime) {
  82814. _this._renderTargetsRenderTime.fetchNewFrame();
  82815. }
  82816. if (_this._captureFrameTime) {
  82817. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  82818. _this._frameTime.beginMonitoring();
  82819. }
  82820. if (_this._captureInterFrameTime) {
  82821. _this._interFrameTime.endMonitoring();
  82822. }
  82823. if (_this._captureParticlesRenderTime) {
  82824. _this._particlesRenderTime.fetchNewFrame();
  82825. }
  82826. if (_this._captureSpritesRenderTime) {
  82827. _this._spritesRenderTime.fetchNewFrame();
  82828. }
  82829. if (_this._captureAnimationsTime) {
  82830. _this._animationsTime.beginMonitoring();
  82831. }
  82832. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  82833. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  82834. });
  82835. // After render
  82836. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  82837. if (_this._captureFrameTime) {
  82838. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  82839. _this._frameTime.endMonitoring();
  82840. }
  82841. if (_this._captureRenderTime) {
  82842. _this._renderTime.endMonitoring(false);
  82843. }
  82844. if (_this._captureInterFrameTime) {
  82845. _this._interFrameTime.beginMonitoring();
  82846. }
  82847. });
  82848. }
  82849. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  82850. // Properties
  82851. /**
  82852. * Gets the perf counter used for active meshes evaluation time
  82853. */
  82854. get: function () {
  82855. return this._activeMeshesEvaluationTime;
  82856. },
  82857. enumerable: true,
  82858. configurable: true
  82859. });
  82860. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  82861. /**
  82862. * Gets the active meshes evaluation time capture status
  82863. */
  82864. get: function () {
  82865. return this._captureActiveMeshesEvaluationTime;
  82866. },
  82867. /**
  82868. * Enable or disable the active meshes evaluation time capture
  82869. */
  82870. set: function (value) {
  82871. var _this = this;
  82872. if (value === this._captureActiveMeshesEvaluationTime) {
  82873. return;
  82874. }
  82875. this._captureActiveMeshesEvaluationTime = value;
  82876. if (value) {
  82877. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  82878. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  82879. _this._activeMeshesEvaluationTime.beginMonitoring();
  82880. });
  82881. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  82882. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  82883. _this._activeMeshesEvaluationTime.endMonitoring();
  82884. });
  82885. }
  82886. else {
  82887. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  82888. this._onBeforeActiveMeshesEvaluationObserver = null;
  82889. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  82890. this._onAfterActiveMeshesEvaluationObserver = null;
  82891. }
  82892. },
  82893. enumerable: true,
  82894. configurable: true
  82895. });
  82896. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  82897. /**
  82898. * Gets the perf counter used for render targets render time
  82899. */
  82900. get: function () {
  82901. return this._renderTargetsRenderTime;
  82902. },
  82903. enumerable: true,
  82904. configurable: true
  82905. });
  82906. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  82907. /**
  82908. * Gets the render targets render time capture status
  82909. */
  82910. get: function () {
  82911. return this._captureRenderTargetsRenderTime;
  82912. },
  82913. /**
  82914. * Enable or disable the render targets render time capture
  82915. */
  82916. set: function (value) {
  82917. var _this = this;
  82918. if (value === this._captureRenderTargetsRenderTime) {
  82919. return;
  82920. }
  82921. this._captureRenderTargetsRenderTime = value;
  82922. if (value) {
  82923. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  82924. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  82925. _this._renderTargetsRenderTime.beginMonitoring();
  82926. });
  82927. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  82928. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  82929. _this._renderTargetsRenderTime.endMonitoring(false);
  82930. });
  82931. }
  82932. else {
  82933. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  82934. this._onBeforeRenderTargetsRenderObserver = null;
  82935. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  82936. this._onAfterRenderTargetsRenderObserver = null;
  82937. }
  82938. },
  82939. enumerable: true,
  82940. configurable: true
  82941. });
  82942. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  82943. /**
  82944. * Gets the perf counter used for particles render time
  82945. */
  82946. get: function () {
  82947. return this._particlesRenderTime;
  82948. },
  82949. enumerable: true,
  82950. configurable: true
  82951. });
  82952. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  82953. /**
  82954. * Gets the particles render time capture status
  82955. */
  82956. get: function () {
  82957. return this._captureParticlesRenderTime;
  82958. },
  82959. /**
  82960. * Enable or disable the particles render time capture
  82961. */
  82962. set: function (value) {
  82963. var _this = this;
  82964. if (value === this._captureParticlesRenderTime) {
  82965. return;
  82966. }
  82967. this._captureParticlesRenderTime = value;
  82968. if (value) {
  82969. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  82970. BABYLON.Tools.StartPerformanceCounter("Particles");
  82971. _this._particlesRenderTime.beginMonitoring();
  82972. });
  82973. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  82974. BABYLON.Tools.EndPerformanceCounter("Particles");
  82975. _this._particlesRenderTime.endMonitoring(false);
  82976. });
  82977. }
  82978. else {
  82979. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  82980. this._onBeforeParticlesRenderingObserver = null;
  82981. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  82982. this._onAfterParticlesRenderingObserver = null;
  82983. }
  82984. },
  82985. enumerable: true,
  82986. configurable: true
  82987. });
  82988. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  82989. /**
  82990. * Gets the perf counter used for sprites render time
  82991. */
  82992. get: function () {
  82993. return this._spritesRenderTime;
  82994. },
  82995. enumerable: true,
  82996. configurable: true
  82997. });
  82998. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  82999. /**
  83000. * Gets the sprites render time capture status
  83001. */
  83002. get: function () {
  83003. return this._captureSpritesRenderTime;
  83004. },
  83005. /**
  83006. * Enable or disable the sprites render time capture
  83007. */
  83008. set: function (value) {
  83009. var _this = this;
  83010. if (value === this._captureSpritesRenderTime) {
  83011. return;
  83012. }
  83013. this._captureSpritesRenderTime = value;
  83014. if (value) {
  83015. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  83016. BABYLON.Tools.StartPerformanceCounter("Sprites");
  83017. _this._spritesRenderTime.beginMonitoring();
  83018. });
  83019. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  83020. BABYLON.Tools.EndPerformanceCounter("Sprites");
  83021. _this._spritesRenderTime.endMonitoring(false);
  83022. });
  83023. }
  83024. else {
  83025. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  83026. this._onBeforeSpritesRenderingObserver = null;
  83027. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  83028. this._onAfterSpritesRenderingObserver = null;
  83029. }
  83030. },
  83031. enumerable: true,
  83032. configurable: true
  83033. });
  83034. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  83035. /**
  83036. * Gets the perf counter used for physics time
  83037. */
  83038. get: function () {
  83039. return this._physicsTime;
  83040. },
  83041. enumerable: true,
  83042. configurable: true
  83043. });
  83044. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  83045. /**
  83046. * Gets the physics time capture status
  83047. */
  83048. get: function () {
  83049. return this._capturePhysicsTime;
  83050. },
  83051. /**
  83052. * Enable or disable the physics time capture
  83053. */
  83054. set: function (value) {
  83055. var _this = this;
  83056. if (value === this._capturePhysicsTime) {
  83057. return;
  83058. }
  83059. this._capturePhysicsTime = value;
  83060. if (value) {
  83061. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  83062. BABYLON.Tools.StartPerformanceCounter("Physics");
  83063. _this._physicsTime.beginMonitoring();
  83064. });
  83065. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  83066. BABYLON.Tools.EndPerformanceCounter("Physics");
  83067. _this._physicsTime.endMonitoring();
  83068. });
  83069. }
  83070. else {
  83071. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  83072. this._onBeforePhysicsObserver = null;
  83073. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  83074. this._onAfterPhysicsObserver = null;
  83075. }
  83076. },
  83077. enumerable: true,
  83078. configurable: true
  83079. });
  83080. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  83081. /**
  83082. * Gets the perf counter used for animations time
  83083. */
  83084. get: function () {
  83085. return this._animationsTime;
  83086. },
  83087. enumerable: true,
  83088. configurable: true
  83089. });
  83090. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  83091. /**
  83092. * Gets the animations time capture status
  83093. */
  83094. get: function () {
  83095. return this._captureAnimationsTime;
  83096. },
  83097. /**
  83098. * Enable or disable the animations time capture
  83099. */
  83100. set: function (value) {
  83101. var _this = this;
  83102. if (value === this._captureAnimationsTime) {
  83103. return;
  83104. }
  83105. this._captureAnimationsTime = value;
  83106. if (value) {
  83107. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  83108. _this._animationsTime.endMonitoring();
  83109. });
  83110. }
  83111. else {
  83112. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  83113. this._onAfterAnimationsObserver = null;
  83114. }
  83115. },
  83116. enumerable: true,
  83117. configurable: true
  83118. });
  83119. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  83120. /**
  83121. * Gets the perf counter used for frame time capture
  83122. */
  83123. get: function () {
  83124. return this._frameTime;
  83125. },
  83126. enumerable: true,
  83127. configurable: true
  83128. });
  83129. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  83130. /**
  83131. * Gets the frame time capture status
  83132. */
  83133. get: function () {
  83134. return this._captureFrameTime;
  83135. },
  83136. /**
  83137. * Enable or disable the frame time capture
  83138. */
  83139. set: function (value) {
  83140. this._captureFrameTime = value;
  83141. },
  83142. enumerable: true,
  83143. configurable: true
  83144. });
  83145. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  83146. /**
  83147. * Gets the perf counter used for inter-frames time capture
  83148. */
  83149. get: function () {
  83150. return this._interFrameTime;
  83151. },
  83152. enumerable: true,
  83153. configurable: true
  83154. });
  83155. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  83156. /**
  83157. * Gets the inter-frames time capture status
  83158. */
  83159. get: function () {
  83160. return this._captureInterFrameTime;
  83161. },
  83162. /**
  83163. * Enable or disable the inter-frames time capture
  83164. */
  83165. set: function (value) {
  83166. this._captureInterFrameTime = value;
  83167. },
  83168. enumerable: true,
  83169. configurable: true
  83170. });
  83171. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  83172. /**
  83173. * Gets the perf counter used for render time capture
  83174. */
  83175. get: function () {
  83176. return this._renderTime;
  83177. },
  83178. enumerable: true,
  83179. configurable: true
  83180. });
  83181. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  83182. /**
  83183. * Gets the render time capture status
  83184. */
  83185. get: function () {
  83186. return this._captureRenderTime;
  83187. },
  83188. /**
  83189. * Enable or disable the render time capture
  83190. */
  83191. set: function (value) {
  83192. var _this = this;
  83193. if (value === this._captureRenderTime) {
  83194. return;
  83195. }
  83196. this._captureRenderTime = value;
  83197. if (value) {
  83198. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  83199. _this._renderTime.beginMonitoring();
  83200. BABYLON.Tools.StartPerformanceCounter("Main render");
  83201. });
  83202. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  83203. _this._renderTime.endMonitoring(false);
  83204. BABYLON.Tools.EndPerformanceCounter("Main render");
  83205. });
  83206. }
  83207. else {
  83208. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  83209. this._onBeforeDrawPhaseObserver = null;
  83210. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  83211. this._onAfterDrawPhaseObserver = null;
  83212. }
  83213. },
  83214. enumerable: true,
  83215. configurable: true
  83216. });
  83217. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  83218. /**
  83219. * Gets the perf counter used for draw calls
  83220. */
  83221. get: function () {
  83222. return this.scene.getEngine()._drawCalls;
  83223. },
  83224. enumerable: true,
  83225. configurable: true
  83226. });
  83227. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  83228. /**
  83229. * Gets the perf counter used for texture collisions
  83230. */
  83231. get: function () {
  83232. return this.scene.getEngine()._textureCollisions;
  83233. },
  83234. enumerable: true,
  83235. configurable: true
  83236. });
  83237. SceneInstrumentation.prototype.dispose = function () {
  83238. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  83239. this._onAfterRenderObserver = null;
  83240. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  83241. this._onBeforeActiveMeshesEvaluationObserver = null;
  83242. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  83243. this._onAfterActiveMeshesEvaluationObserver = null;
  83244. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  83245. this._onBeforeRenderTargetsRenderObserver = null;
  83246. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  83247. this._onAfterRenderTargetsRenderObserver = null;
  83248. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  83249. this._onBeforeAnimationsObserver = null;
  83250. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  83251. this._onBeforeParticlesRenderingObserver = null;
  83252. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  83253. this._onAfterParticlesRenderingObserver = null;
  83254. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  83255. this._onBeforeSpritesRenderingObserver = null;
  83256. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  83257. this._onAfterSpritesRenderingObserver = null;
  83258. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  83259. this._onBeforeDrawPhaseObserver = null;
  83260. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  83261. this._onAfterDrawPhaseObserver = null;
  83262. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  83263. this._onBeforePhysicsObserver = null;
  83264. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  83265. this._onAfterPhysicsObserver = null;
  83266. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  83267. this._onAfterAnimationsObserver = null;
  83268. this.scene = null;
  83269. };
  83270. return SceneInstrumentation;
  83271. }());
  83272. BABYLON.SceneInstrumentation = SceneInstrumentation;
  83273. })(BABYLON || (BABYLON = {}));
  83274. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  83275. var BABYLON;
  83276. (function (BABYLON) {
  83277. var _TimeToken = /** @class */ (function () {
  83278. function _TimeToken() {
  83279. this._timeElapsedQueryEnded = false;
  83280. }
  83281. return _TimeToken;
  83282. }());
  83283. BABYLON._TimeToken = _TimeToken;
  83284. })(BABYLON || (BABYLON = {}));
  83285. //# sourceMappingURL=babylon.timeToken.js.map
  83286. var BABYLON;
  83287. (function (BABYLON) {
  83288. /**
  83289. * Background material defines definition.
  83290. */
  83291. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  83292. __extends(BackgroundMaterialDefines, _super);
  83293. /**
  83294. * Constructor of the defines.
  83295. */
  83296. function BackgroundMaterialDefines() {
  83297. var _this = _super.call(this) || this;
  83298. /**
  83299. * True if the diffuse texture is in use.
  83300. */
  83301. _this.DIFFUSE = false;
  83302. /**
  83303. * The direct UV channel to use.
  83304. */
  83305. _this.DIFFUSEDIRECTUV = 0;
  83306. /**
  83307. * True if the diffuse texture is in gamma space.
  83308. */
  83309. _this.GAMMADIFFUSE = false;
  83310. /**
  83311. * True if the diffuse texture has opacity in the alpha channel.
  83312. */
  83313. _this.DIFFUSEHASALPHA = false;
  83314. /**
  83315. * True if you want the material to fade to transparent at grazing angle.
  83316. */
  83317. _this.OPACITYFRESNEL = false;
  83318. /**
  83319. * True if an extra blur needs to be added in the reflection.
  83320. */
  83321. _this.REFLECTIONBLUR = false;
  83322. /**
  83323. * True if you want the material to fade to reflection at grazing angle.
  83324. */
  83325. _this.REFLECTIONFRESNEL = false;
  83326. /**
  83327. * True if you want the material to falloff as far as you move away from the scene center.
  83328. */
  83329. _this.REFLECTIONFALLOFF = false;
  83330. /**
  83331. * False if the current Webgl implementation does not support the texture lod extension.
  83332. */
  83333. _this.TEXTURELODSUPPORT = false;
  83334. /**
  83335. * True to ensure the data are premultiplied.
  83336. */
  83337. _this.PREMULTIPLYALPHA = false;
  83338. /**
  83339. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  83340. */
  83341. _this.USERGBCOLOR = false;
  83342. /**
  83343. * True to add noise in order to reduce the banding effect.
  83344. */
  83345. _this.NOISE = false;
  83346. // Image Processing Configuration.
  83347. _this.IMAGEPROCESSING = false;
  83348. _this.VIGNETTE = false;
  83349. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  83350. _this.VIGNETTEBLENDMODEOPAQUE = false;
  83351. _this.TONEMAPPING = false;
  83352. _this.CONTRAST = false;
  83353. _this.COLORCURVES = false;
  83354. _this.COLORGRADING = false;
  83355. _this.COLORGRADING3D = false;
  83356. _this.SAMPLER3DGREENDEPTH = false;
  83357. _this.SAMPLER3DBGRMAP = false;
  83358. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  83359. _this.EXPOSURE = false;
  83360. // Reflection.
  83361. _this.REFLECTION = false;
  83362. _this.REFLECTIONMAP_3D = false;
  83363. _this.REFLECTIONMAP_SPHERICAL = false;
  83364. _this.REFLECTIONMAP_PLANAR = false;
  83365. _this.REFLECTIONMAP_CUBIC = false;
  83366. _this.REFLECTIONMAP_PROJECTION = false;
  83367. _this.REFLECTIONMAP_SKYBOX = false;
  83368. _this.REFLECTIONMAP_EXPLICIT = false;
  83369. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  83370. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  83371. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  83372. _this.INVERTCUBICMAP = false;
  83373. _this.REFLECTIONMAP_OPPOSITEZ = false;
  83374. _this.LODINREFLECTIONALPHA = false;
  83375. _this.GAMMAREFLECTION = false;
  83376. // Default BJS.
  83377. _this.MAINUV1 = false;
  83378. _this.MAINUV2 = false;
  83379. _this.UV1 = false;
  83380. _this.UV2 = false;
  83381. _this.CLIPPLANE = false;
  83382. _this.POINTSIZE = false;
  83383. _this.FOG = false;
  83384. _this.NORMAL = false;
  83385. _this.NUM_BONE_INFLUENCERS = 0;
  83386. _this.BonesPerMesh = 0;
  83387. _this.INSTANCES = false;
  83388. _this.SHADOWFLOAT = false;
  83389. _this.rebuild();
  83390. return _this;
  83391. }
  83392. return BackgroundMaterialDefines;
  83393. }(BABYLON.MaterialDefines));
  83394. /**
  83395. * Background material used to create an efficient environement around your scene.
  83396. */
  83397. var BackgroundMaterial = /** @class */ (function (_super) {
  83398. __extends(BackgroundMaterial, _super);
  83399. /**
  83400. * constructor
  83401. * @param name The name of the material
  83402. * @param scene The scene to add the material to
  83403. */
  83404. function BackgroundMaterial(name, scene) {
  83405. var _this = _super.call(this, name, scene) || this;
  83406. _this.primaryColor = BABYLON.Color3.White();
  83407. _this.primaryLevel = 1;
  83408. _this.secondaryColor = BABYLON.Color3.Gray();
  83409. _this.secondaryLevel = 1;
  83410. _this.tertiaryColor = BABYLON.Color3.Black();
  83411. _this.tertiaryLevel = 1;
  83412. _this.reflectionTexture = null;
  83413. _this.reflectionBlur = 0;
  83414. _this.diffuseTexture = null;
  83415. /**
  83416. * Specify the list of lights casting shadow on the material.
  83417. * All scene shadow lights will be included if null.
  83418. */
  83419. _this._shadowLights = null;
  83420. _this.shadowLights = null;
  83421. _this.shadowBlurScale = 1;
  83422. _this.shadowLevel = 0;
  83423. _this.sceneCenter = BABYLON.Vector3.Zero();
  83424. _this.opacityFresnel = true;
  83425. _this.reflectionFresnel = false;
  83426. _this.reflectionFalloffDistance = 0.0;
  83427. _this.reflectionAmount = 1.0;
  83428. _this.reflectionReflectance0 = 0.05;
  83429. _this.reflectionReflectance90 = 0.5;
  83430. _this.useRGBColor = true;
  83431. _this.enableNoise = false;
  83432. /**
  83433. * Number of Simultaneous lights allowed on the material.
  83434. */
  83435. _this._maxSimultaneousLights = 4;
  83436. _this.maxSimultaneousLights = 4;
  83437. /**
  83438. * Keep track of the image processing observer to allow dispose and replace.
  83439. */
  83440. _this._imageProcessingObserver = null;
  83441. // Temp values kept as cache in the material.
  83442. _this._renderTargets = new BABYLON.SmartArray(16);
  83443. _this._reflectionControls = BABYLON.Vector4.Zero();
  83444. // Setup the default processing configuration to the scene.
  83445. _this._attachImageProcessingConfiguration(null);
  83446. _this.getRenderTargetTextures = function () {
  83447. _this._renderTargets.reset();
  83448. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  83449. _this._renderTargets.push(_this._diffuseTexture);
  83450. }
  83451. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  83452. _this._renderTargets.push(_this._reflectionTexture);
  83453. }
  83454. return _this._renderTargets;
  83455. };
  83456. return _this;
  83457. }
  83458. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  83459. /**
  83460. * Sets the reflection reflectance fresnel values according to the default standard
  83461. * empirically know to work well :-)
  83462. */
  83463. set: function (value) {
  83464. var reflectionWeight = value;
  83465. if (reflectionWeight < 0.5) {
  83466. reflectionWeight = reflectionWeight * 2.0;
  83467. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  83468. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  83469. }
  83470. else {
  83471. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  83472. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  83473. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  83474. }
  83475. },
  83476. enumerable: true,
  83477. configurable: true
  83478. });
  83479. /**
  83480. * Attaches a new image processing configuration to the PBR Material.
  83481. * @param configuration (if null the scene configuration will be use)
  83482. */
  83483. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  83484. var _this = this;
  83485. if (configuration === this._imageProcessingConfiguration) {
  83486. return;
  83487. }
  83488. // Detaches observer.
  83489. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83490. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83491. }
  83492. // Pick the scene configuration if needed.
  83493. if (!configuration) {
  83494. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  83495. }
  83496. else {
  83497. this._imageProcessingConfiguration = configuration;
  83498. }
  83499. // Attaches observer.
  83500. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  83501. _this._markAllSubMeshesAsImageProcessingDirty();
  83502. });
  83503. };
  83504. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  83505. /**
  83506. * Gets the image processing configuration used either in this material.
  83507. */
  83508. get: function () {
  83509. return this._imageProcessingConfiguration;
  83510. },
  83511. /**
  83512. * Sets the Default image processing configuration used either in the this material.
  83513. *
  83514. * If sets to null, the scene one is in use.
  83515. */
  83516. set: function (value) {
  83517. this._attachImageProcessingConfiguration(value);
  83518. // Ensure the effect will be rebuilt.
  83519. this._markAllSubMeshesAsTexturesDirty();
  83520. },
  83521. enumerable: true,
  83522. configurable: true
  83523. });
  83524. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  83525. /**
  83526. * Gets wether the color curves effect is enabled.
  83527. */
  83528. get: function () {
  83529. return this.imageProcessingConfiguration.colorCurvesEnabled;
  83530. },
  83531. /**
  83532. * Sets wether the color curves effect is enabled.
  83533. */
  83534. set: function (value) {
  83535. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  83536. },
  83537. enumerable: true,
  83538. configurable: true
  83539. });
  83540. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  83541. /**
  83542. * Gets wether the color grading effect is enabled.
  83543. */
  83544. get: function () {
  83545. return this.imageProcessingConfiguration.colorGradingEnabled;
  83546. },
  83547. /**
  83548. * Gets wether the color grading effect is enabled.
  83549. */
  83550. set: function (value) {
  83551. this.imageProcessingConfiguration.colorGradingEnabled = value;
  83552. },
  83553. enumerable: true,
  83554. configurable: true
  83555. });
  83556. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  83557. /**
  83558. * Gets wether tonemapping is enabled or not.
  83559. */
  83560. get: function () {
  83561. return this._imageProcessingConfiguration.toneMappingEnabled;
  83562. },
  83563. /**
  83564. * Sets wether tonemapping is enabled or not
  83565. */
  83566. set: function (value) {
  83567. this._imageProcessingConfiguration.toneMappingEnabled = value;
  83568. },
  83569. enumerable: true,
  83570. configurable: true
  83571. });
  83572. ;
  83573. ;
  83574. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  83575. /**
  83576. * The camera exposure used on this material.
  83577. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  83578. * This corresponds to a photographic exposure.
  83579. */
  83580. get: function () {
  83581. return this._imageProcessingConfiguration.exposure;
  83582. },
  83583. /**
  83584. * The camera exposure used on this material.
  83585. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  83586. * This corresponds to a photographic exposure.
  83587. */
  83588. set: function (value) {
  83589. this._imageProcessingConfiguration.exposure = value;
  83590. },
  83591. enumerable: true,
  83592. configurable: true
  83593. });
  83594. ;
  83595. ;
  83596. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  83597. /**
  83598. * Gets The camera contrast used on this material.
  83599. */
  83600. get: function () {
  83601. return this._imageProcessingConfiguration.contrast;
  83602. },
  83603. /**
  83604. * Sets The camera contrast used on this material.
  83605. */
  83606. set: function (value) {
  83607. this._imageProcessingConfiguration.contrast = value;
  83608. },
  83609. enumerable: true,
  83610. configurable: true
  83611. });
  83612. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  83613. /**
  83614. * Gets the Color Grading 2D Lookup Texture.
  83615. */
  83616. get: function () {
  83617. return this._imageProcessingConfiguration.colorGradingTexture;
  83618. },
  83619. /**
  83620. * Sets the Color Grading 2D Lookup Texture.
  83621. */
  83622. set: function (value) {
  83623. this.imageProcessingConfiguration.colorGradingTexture = value;
  83624. },
  83625. enumerable: true,
  83626. configurable: true
  83627. });
  83628. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  83629. /**
  83630. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83631. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83632. * 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;
  83633. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83634. */
  83635. get: function () {
  83636. return this.imageProcessingConfiguration.colorCurves;
  83637. },
  83638. /**
  83639. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83640. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83641. * 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;
  83642. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83643. */
  83644. set: function (value) {
  83645. this.imageProcessingConfiguration.colorCurves = value;
  83646. },
  83647. enumerable: true,
  83648. configurable: true
  83649. });
  83650. /**
  83651. * The entire material has been created in order to prevent overdraw.
  83652. * @returns false
  83653. */
  83654. BackgroundMaterial.prototype.needAlphaTesting = function () {
  83655. return true;
  83656. };
  83657. /**
  83658. * The entire material has been created in order to prevent overdraw.
  83659. * @returns true if blending is enable
  83660. */
  83661. BackgroundMaterial.prototype.needAlphaBlending = function () {
  83662. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  83663. };
  83664. /**
  83665. * Checks wether the material is ready to be rendered for a given mesh.
  83666. * @param mesh The mesh to render
  83667. * @param subMesh The submesh to check against
  83668. * @param useInstances Specify wether or not the material is used with instances
  83669. */
  83670. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  83671. var _this = this;
  83672. if (useInstances === void 0) { useInstances = false; }
  83673. if (subMesh.effect && this.isFrozen) {
  83674. if (this._wasPreviouslyReady) {
  83675. return true;
  83676. }
  83677. }
  83678. if (!subMesh._materialDefines) {
  83679. subMesh._materialDefines = new BackgroundMaterialDefines();
  83680. }
  83681. var scene = this.getScene();
  83682. var defines = subMesh._materialDefines;
  83683. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  83684. if (defines._renderId === scene.getRenderId()) {
  83685. return true;
  83686. }
  83687. }
  83688. var engine = scene.getEngine();
  83689. // Lights
  83690. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  83691. defines._needNormals = true;
  83692. // Textures
  83693. if (defines._areTexturesDirty) {
  83694. defines._needUVs = false;
  83695. if (scene.texturesEnabled) {
  83696. if (scene.getEngine().getCaps().textureLOD) {
  83697. defines.TEXTURELODSUPPORT = true;
  83698. }
  83699. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83700. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  83701. return false;
  83702. }
  83703. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  83704. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  83705. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  83706. defines.OPACITYFRESNEL = this._opacityFresnel;
  83707. }
  83708. else {
  83709. defines.DIFFUSE = false;
  83710. defines.DIFFUSEHASALPHA = false;
  83711. defines.GAMMADIFFUSE = false;
  83712. defines.OPACITYFRESNEL = false;
  83713. }
  83714. var reflectionTexture = this._reflectionTexture;
  83715. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83716. if (!reflectionTexture.isReadyOrNotBlocking()) {
  83717. return false;
  83718. }
  83719. defines.REFLECTION = true;
  83720. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  83721. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  83722. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  83723. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  83724. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  83725. defines.INVERTCUBICMAP = true;
  83726. }
  83727. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  83728. switch (reflectionTexture.coordinatesMode) {
  83729. case BABYLON.Texture.CUBIC_MODE:
  83730. case BABYLON.Texture.INVCUBIC_MODE:
  83731. defines.REFLECTIONMAP_CUBIC = true;
  83732. break;
  83733. case BABYLON.Texture.EXPLICIT_MODE:
  83734. defines.REFLECTIONMAP_EXPLICIT = true;
  83735. break;
  83736. case BABYLON.Texture.PLANAR_MODE:
  83737. defines.REFLECTIONMAP_PLANAR = true;
  83738. break;
  83739. case BABYLON.Texture.PROJECTION_MODE:
  83740. defines.REFLECTIONMAP_PROJECTION = true;
  83741. break;
  83742. case BABYLON.Texture.SKYBOX_MODE:
  83743. defines.REFLECTIONMAP_SKYBOX = true;
  83744. break;
  83745. case BABYLON.Texture.SPHERICAL_MODE:
  83746. defines.REFLECTIONMAP_SPHERICAL = true;
  83747. break;
  83748. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  83749. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  83750. break;
  83751. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  83752. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  83753. break;
  83754. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  83755. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  83756. break;
  83757. }
  83758. if (this.reflectionFresnel) {
  83759. defines.REFLECTIONFRESNEL = true;
  83760. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  83761. this._reflectionControls.x = this.reflectionAmount;
  83762. this._reflectionControls.y = this.reflectionReflectance0;
  83763. this._reflectionControls.z = this.reflectionReflectance90;
  83764. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  83765. }
  83766. else {
  83767. defines.REFLECTIONFRESNEL = false;
  83768. defines.REFLECTIONFALLOFF = false;
  83769. }
  83770. }
  83771. else {
  83772. defines.REFLECTION = false;
  83773. defines.REFLECTIONFALLOFF = false;
  83774. defines.REFLECTIONBLUR = false;
  83775. defines.REFLECTIONMAP_3D = false;
  83776. defines.REFLECTIONMAP_SPHERICAL = false;
  83777. defines.REFLECTIONMAP_PLANAR = false;
  83778. defines.REFLECTIONMAP_CUBIC = false;
  83779. defines.REFLECTIONMAP_PROJECTION = false;
  83780. defines.REFLECTIONMAP_SKYBOX = false;
  83781. defines.REFLECTIONMAP_EXPLICIT = false;
  83782. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  83783. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  83784. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  83785. defines.INVERTCUBICMAP = false;
  83786. defines.REFLECTIONMAP_OPPOSITEZ = false;
  83787. defines.LODINREFLECTIONALPHA = false;
  83788. defines.GAMMAREFLECTION = false;
  83789. }
  83790. }
  83791. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  83792. defines.USERGBCOLOR = this._useRGBColor;
  83793. defines.NOISE = this._enableNoise;
  83794. }
  83795. if (defines._areImageProcessingDirty) {
  83796. if (!this._imageProcessingConfiguration.isReady()) {
  83797. return false;
  83798. }
  83799. this._imageProcessingConfiguration.prepareDefines(defines);
  83800. }
  83801. // Misc.
  83802. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  83803. // Values that need to be evaluated on every frame
  83804. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  83805. // Attribs
  83806. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  83807. if (mesh) {
  83808. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  83809. mesh.createNormals(true);
  83810. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  83811. }
  83812. }
  83813. }
  83814. // Get correct effect
  83815. if (defines.isDirty) {
  83816. defines.markAsProcessed();
  83817. scene.resetCachedMaterial();
  83818. // Fallbacks
  83819. var fallbacks = new BABYLON.EffectFallbacks();
  83820. if (defines.FOG) {
  83821. fallbacks.addFallback(0, "FOG");
  83822. }
  83823. if (defines.POINTSIZE) {
  83824. fallbacks.addFallback(1, "POINTSIZE");
  83825. }
  83826. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  83827. if (defines.NUM_BONE_INFLUENCERS > 0) {
  83828. fallbacks.addCPUSkinningFallback(0, mesh);
  83829. }
  83830. //Attributes
  83831. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83832. if (defines.NORMAL) {
  83833. attribs.push(BABYLON.VertexBuffer.NormalKind);
  83834. }
  83835. if (defines.UV1) {
  83836. attribs.push(BABYLON.VertexBuffer.UVKind);
  83837. }
  83838. if (defines.UV2) {
  83839. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83840. }
  83841. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  83842. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  83843. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  83844. "vFogInfos", "vFogColor", "pointSize",
  83845. "vClipPlane", "mBones",
  83846. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  83847. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  83848. "shadowLevel", "alpha",
  83849. "vBackgroundCenter", "vReflectionControl",
  83850. "vDiffuseInfos", "diffuseMatrix",
  83851. ];
  83852. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  83853. var uniformBuffers = ["Material", "Scene"];
  83854. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  83855. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  83856. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  83857. uniformsNames: uniforms,
  83858. uniformBuffersNames: uniformBuffers,
  83859. samplers: samplers,
  83860. defines: defines,
  83861. maxSimultaneousLights: this._maxSimultaneousLights
  83862. });
  83863. var onCompiled = function (effect) {
  83864. if (_this.onCompiled) {
  83865. _this.onCompiled(effect);
  83866. }
  83867. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  83868. };
  83869. var join = defines.toString();
  83870. subMesh.setEffect(scene.getEngine().createEffect("background", {
  83871. attributes: attribs,
  83872. uniformsNames: uniforms,
  83873. uniformBuffersNames: uniformBuffers,
  83874. samplers: samplers,
  83875. defines: join,
  83876. fallbacks: fallbacks,
  83877. onCompiled: onCompiled,
  83878. onError: this.onError,
  83879. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  83880. }, engine), defines);
  83881. this.buildUniformLayout();
  83882. }
  83883. if (!subMesh.effect || !subMesh.effect.isReady()) {
  83884. return false;
  83885. }
  83886. defines._renderId = scene.getRenderId();
  83887. this._wasPreviouslyReady = true;
  83888. return true;
  83889. };
  83890. /**
  83891. * Build the uniform buffer used in the material.
  83892. */
  83893. BackgroundMaterial.prototype.buildUniformLayout = function () {
  83894. // Order is important !
  83895. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  83896. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  83897. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  83898. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  83899. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  83900. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  83901. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  83902. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  83903. this._uniformBuffer.addUniform("pointSize", 1);
  83904. this._uniformBuffer.addUniform("shadowLevel", 1);
  83905. this._uniformBuffer.addUniform("alpha", 1);
  83906. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  83907. this._uniformBuffer.addUniform("vReflectionControl", 4);
  83908. this._uniformBuffer.create();
  83909. };
  83910. /**
  83911. * Unbind the material.
  83912. */
  83913. BackgroundMaterial.prototype.unbind = function () {
  83914. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  83915. this._uniformBuffer.setTexture("diffuseSampler", null);
  83916. }
  83917. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  83918. this._uniformBuffer.setTexture("reflectionSampler", null);
  83919. }
  83920. _super.prototype.unbind.call(this);
  83921. };
  83922. /**
  83923. * Bind only the world matrix to the material.
  83924. * @param world The world matrix to bind.
  83925. */
  83926. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  83927. this._activeEffect.setMatrix("world", world);
  83928. };
  83929. /**
  83930. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  83931. * @param world The world matrix to bind.
  83932. * @param subMesh The submesh to bind for.
  83933. */
  83934. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  83935. var scene = this.getScene();
  83936. var defines = subMesh._materialDefines;
  83937. if (!defines) {
  83938. return;
  83939. }
  83940. var effect = subMesh.effect;
  83941. if (!effect) {
  83942. return;
  83943. }
  83944. this._activeEffect = effect;
  83945. // Matrices
  83946. this.bindOnlyWorldMatrix(world);
  83947. // Bones
  83948. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  83949. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  83950. if (mustRebind) {
  83951. this._uniformBuffer.bindToEffect(effect, "Material");
  83952. this.bindViewProjection(effect);
  83953. var reflectionTexture = this._reflectionTexture;
  83954. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  83955. // Texture uniforms
  83956. if (scene.texturesEnabled) {
  83957. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83958. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  83959. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  83960. }
  83961. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83962. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  83963. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  83964. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  83965. }
  83966. }
  83967. if (this.shadowLevel > 0) {
  83968. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  83969. }
  83970. this._uniformBuffer.updateFloat("alpha", this.alpha);
  83971. // Point size
  83972. if (this.pointsCloud) {
  83973. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  83974. }
  83975. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  83976. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  83977. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  83978. }
  83979. // Textures
  83980. if (scene.texturesEnabled) {
  83981. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83982. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  83983. }
  83984. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83985. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  83986. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  83987. }
  83988. else if (!defines.REFLECTIONBLUR) {
  83989. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  83990. }
  83991. else {
  83992. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  83993. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  83994. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  83995. }
  83996. if (defines.REFLECTIONFRESNEL) {
  83997. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  83998. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  83999. }
  84000. }
  84001. }
  84002. // Clip plane
  84003. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  84004. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  84005. }
  84006. if (mustRebind || !this.isFrozen) {
  84007. if (scene.lightsEnabled) {
  84008. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  84009. }
  84010. // View
  84011. this.bindView(effect);
  84012. // Fog
  84013. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  84014. // image processing
  84015. this._imageProcessingConfiguration.bind(this._activeEffect);
  84016. }
  84017. this._uniformBuffer.update();
  84018. this._afterBind(mesh);
  84019. };
  84020. /**
  84021. * Dispose the material.
  84022. * @forceDisposeEffect Force disposal of the associated effect.
  84023. * @forceDisposeTextures Force disposal of the associated textures.
  84024. */
  84025. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  84026. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  84027. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  84028. if (forceDisposeTextures) {
  84029. if (this.diffuseTexture) {
  84030. this.diffuseTexture.dispose();
  84031. }
  84032. if (this.reflectionTexture) {
  84033. this.reflectionTexture.dispose();
  84034. }
  84035. }
  84036. this._renderTargets.dispose();
  84037. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84038. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84039. }
  84040. _super.prototype.dispose.call(this, forceDisposeEffect);
  84041. };
  84042. /**
  84043. * Clones the material.
  84044. * @name The cloned name.
  84045. * @returns The cloned material.
  84046. */
  84047. BackgroundMaterial.prototype.clone = function (name) {
  84048. var _this = this;
  84049. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  84050. };
  84051. /**
  84052. * Serializes the current material to its JSON representation.
  84053. * @returns The JSON representation.
  84054. */
  84055. BackgroundMaterial.prototype.serialize = function () {
  84056. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84057. serializationObject.customType = "BABYLON.BackgroundMaterial";
  84058. return serializationObject;
  84059. };
  84060. /**
  84061. * Gets the class name of the material
  84062. * @returns "BackgroundMaterial"
  84063. */
  84064. BackgroundMaterial.prototype.getClassName = function () {
  84065. return "BackgroundMaterial";
  84066. };
  84067. /**
  84068. * Parse a JSON input to create back a background material.
  84069. * @param source
  84070. * @param scene
  84071. * @param rootUrl
  84072. * @returns the instantiated BackgroundMaterial.
  84073. */
  84074. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  84075. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  84076. };
  84077. /**
  84078. * Standard reflectance value at parallel view angle.
  84079. */
  84080. BackgroundMaterial.standardReflectance0 = 0.05;
  84081. /**
  84082. * Standard reflectance value at grazing angle.
  84083. */
  84084. BackgroundMaterial.standardReflectance90 = 0.5;
  84085. __decorate([
  84086. BABYLON.serializeAsColor3()
  84087. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  84088. __decorate([
  84089. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84090. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  84091. __decorate([
  84092. BABYLON.serialize()
  84093. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  84094. __decorate([
  84095. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84096. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  84097. __decorate([
  84098. BABYLON.serializeAsColor3()
  84099. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  84100. __decorate([
  84101. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84102. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  84103. __decorate([
  84104. BABYLON.serialize()
  84105. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  84106. __decorate([
  84107. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84108. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  84109. __decorate([
  84110. BABYLON.serializeAsColor3()
  84111. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  84112. __decorate([
  84113. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84114. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  84115. __decorate([
  84116. BABYLON.serialize()
  84117. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  84118. __decorate([
  84119. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  84120. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  84121. __decorate([
  84122. BABYLON.serializeAsTexture()
  84123. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  84124. __decorate([
  84125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84126. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  84127. __decorate([
  84128. BABYLON.serialize()
  84129. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  84130. __decorate([
  84131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84132. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  84133. __decorate([
  84134. BABYLON.serializeAsTexture()
  84135. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  84136. __decorate([
  84137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84138. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  84139. __decorate([
  84140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84141. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  84142. __decorate([
  84143. BABYLON.serialize()
  84144. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  84145. __decorate([
  84146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84147. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  84148. __decorate([
  84149. BABYLON.serialize()
  84150. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  84151. __decorate([
  84152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84153. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  84154. __decorate([
  84155. BABYLON.serializeAsVector3()
  84156. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  84157. __decorate([
  84158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84159. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  84160. __decorate([
  84161. BABYLON.serialize()
  84162. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  84163. __decorate([
  84164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84165. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  84166. __decorate([
  84167. BABYLON.serialize()
  84168. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  84169. __decorate([
  84170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84171. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  84172. __decorate([
  84173. BABYLON.serialize()
  84174. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  84175. __decorate([
  84176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84177. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  84178. __decorate([
  84179. BABYLON.serialize()
  84180. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  84181. __decorate([
  84182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84183. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  84184. __decorate([
  84185. BABYLON.serialize()
  84186. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  84187. __decorate([
  84188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84189. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  84190. __decorate([
  84191. BABYLON.serialize()
  84192. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  84193. __decorate([
  84194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84195. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  84196. __decorate([
  84197. BABYLON.serialize()
  84198. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  84199. __decorate([
  84200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84201. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  84202. __decorate([
  84203. BABYLON.serialize()
  84204. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  84205. __decorate([
  84206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84207. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  84208. __decorate([
  84209. BABYLON.serialize()
  84210. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  84211. __decorate([
  84212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  84213. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  84214. __decorate([
  84215. BABYLON.serializeAsImageProcessingConfiguration()
  84216. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  84217. return BackgroundMaterial;
  84218. }(BABYLON.PushMaterial));
  84219. BABYLON.BackgroundMaterial = BackgroundMaterial;
  84220. })(BABYLON || (BABYLON = {}));
  84221. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  84222. var __assign = (this && this.__assign) || Object.assign || function(t) {
  84223. for (var s, i = 1, n = arguments.length; i < n; i++) {
  84224. s = arguments[i];
  84225. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  84226. t[p] = s[p];
  84227. }
  84228. return t;
  84229. };
  84230. var BABYLON;
  84231. (function (BABYLON) {
  84232. /**
  84233. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  84234. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  84235. * It also helps with the default setup of your imageProcessing configuration.
  84236. */
  84237. var EnvironmentHelper = /** @class */ (function () {
  84238. /**
  84239. * constructor
  84240. * @param options
  84241. * @param scene The scene to add the material to
  84242. */
  84243. function EnvironmentHelper(options, scene) {
  84244. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  84245. this._scene = scene;
  84246. this._setupBackground();
  84247. this._setupImageProcessing();
  84248. }
  84249. /**
  84250. * Creates the default options for the helper.
  84251. */
  84252. EnvironmentHelper._getDefaultOptions = function () {
  84253. return {
  84254. createGround: true,
  84255. groundSize: 15,
  84256. groundTexture: this._groundTextureCDNUrl,
  84257. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  84258. groundOpacity: 0.9,
  84259. enableGroundShadow: true,
  84260. groundShadowLevel: 0.5,
  84261. enableGroundMirror: false,
  84262. groundMirrorSizeRatio: 0.3,
  84263. groundMirrorBlurKernel: 64,
  84264. groundMirrorAmount: 1,
  84265. groundMirrorFresnelWeight: 1,
  84266. groundMirrorFallOffDistance: 0,
  84267. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  84268. groundYBias: 0.00001,
  84269. createSkybox: true,
  84270. skyboxSize: 20,
  84271. skyboxTexture: this._skyboxTextureCDNUrl,
  84272. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  84273. backgroundYRotation: 0,
  84274. sizeAuto: true,
  84275. rootPosition: BABYLON.Vector3.Zero(),
  84276. setupImageProcessing: true,
  84277. environmentTexture: this._environmentTextureCDNUrl,
  84278. cameraExposure: 0.8,
  84279. cameraContrast: 1.2,
  84280. toneMappingEnabled: true,
  84281. };
  84282. };
  84283. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  84284. /**
  84285. * Gets the root mesh created by the helper.
  84286. */
  84287. get: function () {
  84288. return this._rootMesh;
  84289. },
  84290. enumerable: true,
  84291. configurable: true
  84292. });
  84293. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  84294. /**
  84295. * Gets the skybox created by the helper.
  84296. */
  84297. get: function () {
  84298. return this._skybox;
  84299. },
  84300. enumerable: true,
  84301. configurable: true
  84302. });
  84303. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  84304. /**
  84305. * Gets the skybox texture created by the helper.
  84306. */
  84307. get: function () {
  84308. return this._skyboxTexture;
  84309. },
  84310. enumerable: true,
  84311. configurable: true
  84312. });
  84313. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  84314. /**
  84315. * Gets the skybox material created by the helper.
  84316. */
  84317. get: function () {
  84318. return this._skyboxMaterial;
  84319. },
  84320. enumerable: true,
  84321. configurable: true
  84322. });
  84323. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  84324. /**
  84325. * Gets the ground mesh created by the helper.
  84326. */
  84327. get: function () {
  84328. return this._ground;
  84329. },
  84330. enumerable: true,
  84331. configurable: true
  84332. });
  84333. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  84334. /**
  84335. * Gets the ground texture created by the helper.
  84336. */
  84337. get: function () {
  84338. return this._groundTexture;
  84339. },
  84340. enumerable: true,
  84341. configurable: true
  84342. });
  84343. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  84344. /**
  84345. * Gets the ground mirror created by the helper.
  84346. */
  84347. get: function () {
  84348. return this._groundMirror;
  84349. },
  84350. enumerable: true,
  84351. configurable: true
  84352. });
  84353. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  84354. /**
  84355. * Gets the ground mirror render list to helps pushing the meshes
  84356. * you wish in the ground reflection.
  84357. */
  84358. get: function () {
  84359. if (this._groundMirror) {
  84360. return this._groundMirror.renderList;
  84361. }
  84362. return null;
  84363. },
  84364. enumerable: true,
  84365. configurable: true
  84366. });
  84367. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  84368. /**
  84369. * Gets the ground material created by the helper.
  84370. */
  84371. get: function () {
  84372. return this._groundMaterial;
  84373. },
  84374. enumerable: true,
  84375. configurable: true
  84376. });
  84377. /**
  84378. * Updates the background according to the new options
  84379. * @param options
  84380. */
  84381. EnvironmentHelper.prototype.updateOptions = function (options) {
  84382. var newOptions = __assign({}, this._options, options);
  84383. if (this._ground && !newOptions.createGround) {
  84384. this._ground.dispose();
  84385. this._ground = null;
  84386. }
  84387. if (this._groundMaterial && !newOptions.createGround) {
  84388. this._groundMaterial.dispose();
  84389. this._groundMaterial = null;
  84390. }
  84391. if (this._groundTexture) {
  84392. if (this._options.groundTexture != newOptions.groundTexture) {
  84393. this._groundTexture.dispose();
  84394. this._groundTexture = null;
  84395. }
  84396. }
  84397. if (this._skybox && !newOptions.createSkybox) {
  84398. this._skybox.dispose();
  84399. this._skybox = null;
  84400. }
  84401. if (this._skyboxMaterial && !newOptions.createSkybox) {
  84402. this._skyboxMaterial.dispose();
  84403. this._skyboxMaterial = null;
  84404. }
  84405. if (this._skyboxTexture) {
  84406. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  84407. this._skyboxTexture.dispose();
  84408. this._skyboxTexture = null;
  84409. }
  84410. }
  84411. if (this._groundMirror && !newOptions.enableGroundMirror) {
  84412. this._groundMirror.dispose();
  84413. this._groundMirror = null;
  84414. }
  84415. if (this._scene.environmentTexture) {
  84416. if (this._options.environmentTexture != newOptions.environmentTexture) {
  84417. this._scene.environmentTexture.dispose();
  84418. }
  84419. }
  84420. this._options = newOptions;
  84421. this._setupBackground();
  84422. this._setupImageProcessing();
  84423. };
  84424. /**
  84425. * Sets the primary color of all the available elements.
  84426. * @param color
  84427. */
  84428. EnvironmentHelper.prototype.setMainColor = function (color) {
  84429. if (this.groundMaterial) {
  84430. this.groundMaterial.primaryColor = color;
  84431. }
  84432. if (this.skyboxMaterial) {
  84433. this.skyboxMaterial.primaryColor = color;
  84434. }
  84435. if (this.groundMirror) {
  84436. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  84437. }
  84438. };
  84439. /**
  84440. * Setup the image processing according to the specified options.
  84441. */
  84442. EnvironmentHelper.prototype._setupImageProcessing = function () {
  84443. if (this._options.setupImageProcessing) {
  84444. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  84445. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  84446. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  84447. this._setupEnvironmentTexture();
  84448. }
  84449. };
  84450. /**
  84451. * Setup the environment texture according to the specified options.
  84452. */
  84453. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  84454. if (this._scene.environmentTexture) {
  84455. return;
  84456. }
  84457. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  84458. this._scene.environmentTexture = this._options.environmentTexture;
  84459. return;
  84460. }
  84461. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  84462. this._scene.environmentTexture = environmentTexture;
  84463. };
  84464. /**
  84465. * Setup the background according to the specified options.
  84466. */
  84467. EnvironmentHelper.prototype._setupBackground = function () {
  84468. if (!this._rootMesh) {
  84469. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  84470. }
  84471. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  84472. var sceneSize = this._getSceneSize();
  84473. if (this._options.createGround) {
  84474. this._setupGround(sceneSize);
  84475. this._setupGroundMaterial();
  84476. this._setupGroundDiffuseTexture();
  84477. if (this._options.enableGroundMirror) {
  84478. this._setupGroundMirrorTexture(sceneSize);
  84479. }
  84480. this._setupMirrorInGroundMaterial();
  84481. }
  84482. if (this._options.createSkybox) {
  84483. this._setupSkybox(sceneSize);
  84484. this._setupSkyboxMaterial();
  84485. this._setupSkyboxReflectionTexture();
  84486. }
  84487. this._rootMesh.position.x = sceneSize.rootPosition.x;
  84488. this._rootMesh.position.z = sceneSize.rootPosition.z;
  84489. this._rootMesh.position.y = sceneSize.rootPosition.y;
  84490. };
  84491. /**
  84492. * Get the scene sizes according to the setup.
  84493. */
  84494. EnvironmentHelper.prototype._getSceneSize = function () {
  84495. var groundSize = this._options.groundSize;
  84496. var skyboxSize = this._options.skyboxSize;
  84497. var rootPosition = this._options.rootPosition;
  84498. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  84499. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  84500. }
  84501. var sceneExtends = this._scene.getWorldExtends();
  84502. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  84503. if (this._options.sizeAuto) {
  84504. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  84505. this._scene.activeCamera.upperRadiusLimit) {
  84506. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  84507. skyboxSize = groundSize;
  84508. }
  84509. var sceneDiagonalLenght = sceneDiagonal.length();
  84510. if (sceneDiagonalLenght > groundSize) {
  84511. groundSize = sceneDiagonalLenght * 2;
  84512. skyboxSize = groundSize;
  84513. }
  84514. // 10 % bigger.
  84515. groundSize *= 1.1;
  84516. skyboxSize *= 1.5;
  84517. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  84518. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  84519. }
  84520. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  84521. };
  84522. /**
  84523. * Setup the ground according to the specified options.
  84524. */
  84525. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  84526. var _this = this;
  84527. if (!this._ground) {
  84528. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  84529. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  84530. this._ground.parent = this._rootMesh;
  84531. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  84532. }
  84533. this._ground.receiveShadows = this._options.enableGroundShadow;
  84534. };
  84535. /**
  84536. * Setup the ground material according to the specified options.
  84537. */
  84538. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  84539. if (!this._groundMaterial) {
  84540. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  84541. }
  84542. this._groundMaterial.alpha = this._options.groundOpacity;
  84543. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  84544. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  84545. this._groundMaterial.primaryLevel = 1;
  84546. this._groundMaterial.primaryColor = this._options.groundColor;
  84547. this._groundMaterial.secondaryLevel = 0;
  84548. this._groundMaterial.tertiaryLevel = 0;
  84549. this._groundMaterial.useRGBColor = false;
  84550. this._groundMaterial.enableNoise = true;
  84551. if (this._ground) {
  84552. this._ground.material = this._groundMaterial;
  84553. }
  84554. };
  84555. /**
  84556. * Setup the ground diffuse texture according to the specified options.
  84557. */
  84558. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  84559. if (!this._groundMaterial) {
  84560. return;
  84561. }
  84562. if (this._groundTexture) {
  84563. return;
  84564. }
  84565. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  84566. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  84567. return;
  84568. }
  84569. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  84570. diffuseTexture.gammaSpace = false;
  84571. diffuseTexture.hasAlpha = true;
  84572. this._groundMaterial.diffuseTexture = diffuseTexture;
  84573. };
  84574. /**
  84575. * Setup the ground mirror texture according to the specified options.
  84576. */
  84577. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  84578. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84579. if (!this._groundMirror) {
  84580. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  84581. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  84582. this._groundMirror.anisotropicFilteringLevel = 1;
  84583. this._groundMirror.wrapU = wrapping;
  84584. this._groundMirror.wrapV = wrapping;
  84585. this._groundMirror.gammaSpace = false;
  84586. if (this._groundMirror.renderList) {
  84587. for (var i = 0; i < this._scene.meshes.length; i++) {
  84588. var mesh = this._scene.meshes[i];
  84589. if (mesh !== this._ground &&
  84590. mesh !== this._skybox &&
  84591. mesh !== this._rootMesh) {
  84592. this._groundMirror.renderList.push(mesh);
  84593. }
  84594. }
  84595. }
  84596. }
  84597. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  84598. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  84599. };
  84600. /**
  84601. * Setup the ground to receive the mirror texture.
  84602. */
  84603. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  84604. if (this._groundMaterial) {
  84605. this._groundMaterial.reflectionTexture = this._groundMirror;
  84606. this._groundMaterial.reflectionFresnel = true;
  84607. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  84608. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  84609. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  84610. }
  84611. };
  84612. /**
  84613. * Setup the skybox according to the specified options.
  84614. */
  84615. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  84616. var _this = this;
  84617. if (!this._skybox) {
  84618. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  84619. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  84620. }
  84621. this._skybox.parent = this._rootMesh;
  84622. };
  84623. /**
  84624. * Setup the skybox material according to the specified options.
  84625. */
  84626. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  84627. if (!this._skybox) {
  84628. return;
  84629. }
  84630. if (!this._skyboxMaterial) {
  84631. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  84632. }
  84633. this._skyboxMaterial.useRGBColor = false;
  84634. this._skyboxMaterial.primaryLevel = 1;
  84635. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  84636. this._skyboxMaterial.secondaryLevel = 0;
  84637. this._skyboxMaterial.tertiaryLevel = 0;
  84638. this._skyboxMaterial.enableNoise = true;
  84639. this._skybox.material = this._skyboxMaterial;
  84640. };
  84641. /**
  84642. * Setup the skybox reflection texture according to the specified options.
  84643. */
  84644. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  84645. if (!this._skyboxMaterial) {
  84646. return;
  84647. }
  84648. if (this._skyboxTexture) {
  84649. return;
  84650. }
  84651. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  84652. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  84653. return;
  84654. }
  84655. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  84656. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  84657. this._skyboxTexture.gammaSpace = false;
  84658. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  84659. };
  84660. /**
  84661. * Dispose all the elements created by the Helper.
  84662. */
  84663. EnvironmentHelper.prototype.dispose = function () {
  84664. if (this._groundMaterial) {
  84665. this._groundMaterial.dispose(true, true);
  84666. }
  84667. if (this._skyboxMaterial) {
  84668. this._skyboxMaterial.dispose(true, true);
  84669. }
  84670. this._rootMesh.dispose(false);
  84671. };
  84672. /**
  84673. * Default ground texture URL.
  84674. */
  84675. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  84676. /**
  84677. * Default skybox texture URL.
  84678. */
  84679. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  84680. /**
  84681. * Default environment texture URL.
  84682. */
  84683. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  84684. return EnvironmentHelper;
  84685. }());
  84686. BABYLON.EnvironmentHelper = EnvironmentHelper;
  84687. })(BABYLON || (BABYLON = {}));
  84688. //# sourceMappingURL=babylon.environmentHelper.js.map
  84689. 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}","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#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 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}","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}"};
  84690. 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#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}\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 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#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 PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\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);
  84691. globalObject["BABYLON"] = BABYLON;
  84692. 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 PostProcessRenderPass = BABYLON.PostProcessRenderPass;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 DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var HighlightLayer = BABYLON.HighlightLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var 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;
  84693. 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,PostProcessRenderPass,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,BlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,HighlightLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper };