es6.js 4.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381
  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. "use strict";
  4. var BABYLON;
  5. (function (BABYLON) {
  6. /**
  7. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  8. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  9. */
  10. var EffectFallbacks = /** @class */ (function () {
  11. function EffectFallbacks() {
  12. this._defines = {};
  13. this._currentRank = 32;
  14. this._maxRank = -1;
  15. }
  16. /**
  17. * Removes the fallback from the bound mesh.
  18. */
  19. EffectFallbacks.prototype.unBindMesh = function () {
  20. this._mesh = null;
  21. };
  22. /**
  23. * Adds a fallback on the specified property.
  24. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  25. * @param define The name of the define in the shader
  26. */
  27. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28. if (!this._defines[rank]) {
  29. if (rank < this._currentRank) {
  30. this._currentRank = rank;
  31. }
  32. if (rank > this._maxRank) {
  33. this._maxRank = rank;
  34. }
  35. this._defines[rank] = new Array();
  36. }
  37. this._defines[rank].push(define);
  38. };
  39. /**
  40. * Sets the mesh to use CPU skinning when needing to fallback.
  41. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  42. * @param mesh The mesh to use the fallbacks.
  43. */
  44. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  45. this._mesh = mesh;
  46. if (rank < this._currentRank) {
  47. this._currentRank = rank;
  48. }
  49. if (rank > this._maxRank) {
  50. this._maxRank = rank;
  51. }
  52. };
  53. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  54. /**
  55. * Checks to see if more fallbacks are still availible.
  56. */
  57. get: function () {
  58. return this._currentRank <= this._maxRank;
  59. },
  60. enumerable: true,
  61. configurable: true
  62. });
  63. /**
  64. * Removes the defines that shoould be removed when falling back.
  65. * @param currentDefines defines the current define statements for the shader.
  66. * @param effect defines the current effect we try to compile
  67. * @returns The resulting defines with defines of the current rank removed.
  68. */
  69. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  70. // First we try to switch to CPU skinning
  71. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  72. this._mesh.computeBonesUsingShaders = false;
  73. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. this._uniformBuffersNames = {};
  163. this._isReady = false;
  164. this._compilationError = "";
  165. this.name = baseName;
  166. if (attributesNamesOrOptions.attributes) {
  167. var options = attributesNamesOrOptions;
  168. this._engine = uniformsNamesOrEngine;
  169. this._attributesNames = options.attributes;
  170. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  171. this._samplers = options.samplers;
  172. this.defines = options.defines;
  173. this.onError = options.onError;
  174. this.onCompiled = options.onCompiled;
  175. this._fallbacks = options.fallbacks;
  176. this._indexParameters = options.indexParameters;
  177. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  178. if (options.uniformBuffersNames) {
  179. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  180. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  181. }
  182. }
  183. }
  184. else {
  185. this._engine = engine;
  186. this.defines = defines;
  187. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  188. this._samplers = samplers;
  189. this._attributesNames = attributesNamesOrOptions;
  190. this.onError = onError;
  191. this.onCompiled = onCompiled;
  192. this._indexParameters = indexParameters;
  193. this._fallbacks = fallbacks;
  194. }
  195. this.uniqueId = Effect._uniqueIdSeed++;
  196. var vertexSource;
  197. var fragmentSource;
  198. if (baseName.vertexElement) {
  199. vertexSource = document.getElementById(baseName.vertexElement);
  200. if (!vertexSource) {
  201. vertexSource = baseName.vertexElement;
  202. }
  203. }
  204. else {
  205. vertexSource = baseName.vertex || baseName;
  206. }
  207. if (baseName.fragmentElement) {
  208. fragmentSource = document.getElementById(baseName.fragmentElement);
  209. if (!fragmentSource) {
  210. fragmentSource = baseName.fragmentElement;
  211. }
  212. }
  213. else {
  214. fragmentSource = baseName.fragment || baseName;
  215. }
  216. this._loadVertexShader(vertexSource, function (vertexCode) {
  217. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  218. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  219. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  220. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  221. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  222. if (baseName) {
  223. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  224. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  225. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  226. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  227. }
  228. else {
  229. _this._vertexSourceCode = migratedVertexCode;
  230. _this._fragmentSourceCode = migratedFragmentCode;
  231. }
  232. _this._prepareEffect();
  233. });
  234. });
  235. });
  236. });
  237. });
  238. });
  239. }
  240. Object.defineProperty(Effect.prototype, "key", {
  241. /**
  242. * Unique key for this effect
  243. */
  244. get: function () {
  245. return this._key;
  246. },
  247. enumerable: true,
  248. configurable: true
  249. });
  250. /**
  251. * If the effect has been compiled and prepared.
  252. * @returns if the effect is compiled and prepared.
  253. */
  254. Effect.prototype.isReady = function () {
  255. return this._isReady;
  256. };
  257. /**
  258. * The engine the effect was initialized with.
  259. * @returns the engine.
  260. */
  261. Effect.prototype.getEngine = function () {
  262. return this._engine;
  263. };
  264. /**
  265. * The compiled webGL program for the effect
  266. * @returns the webGL program.
  267. */
  268. Effect.prototype.getProgram = function () {
  269. return this._program;
  270. };
  271. /**
  272. * The set of names of attribute variables for the shader.
  273. * @returns An array of attribute names.
  274. */
  275. Effect.prototype.getAttributesNames = function () {
  276. return this._attributesNames;
  277. };
  278. /**
  279. * Returns the attribute at the given index.
  280. * @param index The index of the attribute.
  281. * @returns The location of the attribute.
  282. */
  283. Effect.prototype.getAttributeLocation = function (index) {
  284. return this._attributes[index];
  285. };
  286. /**
  287. * Returns the attribute based on the name of the variable.
  288. * @param name of the attribute to look up.
  289. * @returns the attribute location.
  290. */
  291. Effect.prototype.getAttributeLocationByName = function (name) {
  292. var index = this._attributesNames.indexOf(name);
  293. return this._attributes[index];
  294. };
  295. /**
  296. * The number of attributes.
  297. * @returns the numnber of attributes.
  298. */
  299. Effect.prototype.getAttributesCount = function () {
  300. return this._attributes.length;
  301. };
  302. /**
  303. * Gets the index of a uniform variable.
  304. * @param uniformName of the uniform to look up.
  305. * @returns the index.
  306. */
  307. Effect.prototype.getUniformIndex = function (uniformName) {
  308. return this._uniformsNames.indexOf(uniformName);
  309. };
  310. /**
  311. * Returns the attribute based on the name of the variable.
  312. * @param uniformName of the uniform to look up.
  313. * @returns the location of the uniform.
  314. */
  315. Effect.prototype.getUniform = function (uniformName) {
  316. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  317. };
  318. /**
  319. * Returns an array of sampler variable names
  320. * @returns The array of sampler variable neames.
  321. */
  322. Effect.prototype.getSamplers = function () {
  323. return this._samplers;
  324. };
  325. /**
  326. * The error from the last compilation.
  327. * @returns the error string.
  328. */
  329. Effect.prototype.getCompilationError = function () {
  330. return this._compilationError;
  331. };
  332. /**
  333. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  334. * @param func The callback to be used.
  335. */
  336. Effect.prototype.executeWhenCompiled = function (func) {
  337. if (this.isReady()) {
  338. func(this);
  339. return;
  340. }
  341. this.onCompileObservable.add(function (effect) {
  342. func(effect);
  343. });
  344. };
  345. /** @ignore */
  346. Effect.prototype._loadVertexShader = function (vertex, callback) {
  347. if (BABYLON.Tools.IsWindowObjectExist()) {
  348. // DOM element ?
  349. if (vertex instanceof HTMLElement) {
  350. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  351. callback(vertexCode);
  352. return;
  353. }
  354. }
  355. // Base64 encoded ?
  356. if (vertex.substr(0, 7) === "base64:") {
  357. var vertexBinary = window.atob(vertex.substr(7));
  358. callback(vertexBinary);
  359. return;
  360. }
  361. // Is in local store ?
  362. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  363. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  364. return;
  365. }
  366. var vertexShaderUrl;
  367. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  368. vertexShaderUrl = vertex;
  369. }
  370. else {
  371. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  372. }
  373. // Vertex shader
  374. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  375. };
  376. /** @ignore */
  377. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  378. if (BABYLON.Tools.IsWindowObjectExist()) {
  379. // DOM element ?
  380. if (fragment instanceof HTMLElement) {
  381. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  382. callback(fragmentCode);
  383. return;
  384. }
  385. }
  386. // Base64 encoded ?
  387. if (fragment.substr(0, 7) === "base64:") {
  388. var fragmentBinary = window.atob(fragment.substr(7));
  389. callback(fragmentBinary);
  390. return;
  391. }
  392. // Is in local store ?
  393. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  394. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  395. return;
  396. }
  397. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  398. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  399. return;
  400. }
  401. var fragmentShaderUrl;
  402. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  403. fragmentShaderUrl = fragment;
  404. }
  405. else {
  406. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  407. }
  408. // Fragment shader
  409. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  410. };
  411. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  412. // Rebuild shaders source code
  413. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  414. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  415. vertexCode = prefix + vertexCode;
  416. fragmentCode = prefix + fragmentCode;
  417. // Number lines of shaders source code
  418. var i = 2;
  419. var regex = /\n/gm;
  420. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  421. i = 2;
  422. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. // Dump shaders name and formatted source code
  424. if (this.name.vertexElement) {
  425. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  426. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  427. }
  428. else if (this.name.vertex) {
  429. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  430. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  431. }
  432. else {
  433. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  434. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  435. }
  436. };
  437. ;
  438. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  439. var preparedSourceCode = this._processPrecision(sourceCode);
  440. if (this._engine.webGLVersion == 1) {
  441. callback(preparedSourceCode);
  442. return;
  443. }
  444. // Already converted
  445. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  446. callback(preparedSourceCode.replace("#version 300 es", ""));
  447. return;
  448. }
  449. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  450. // Remove extensions
  451. // #extension GL_OES_standard_derivatives : enable
  452. // #extension GL_EXT_shader_texture_lod : enable
  453. // #extension GL_EXT_frag_depth : enable
  454. // #extension GL_EXT_draw_buffers : require
  455. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  456. var result = preparedSourceCode.replace(regex, "");
  457. // Migrate to GLSL v300
  458. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  459. result = result.replace(/attribute[ \t]/g, "in ");
  460. result = result.replace(/[ \t]attribute/g, " in");
  461. if (isFragment) {
  462. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  463. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  464. result = result.replace(/texture2D\s*\(/g, "texture(");
  465. result = result.replace(/textureCube\s*\(/g, "texture(");
  466. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  467. result = result.replace(/gl_FragColor/g, "glFragColor");
  468. result = result.replace(/gl_FragData/g, "glFragData");
  469. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  470. }
  471. callback(result);
  472. };
  473. Effect.prototype._processIncludes = function (sourceCode, callback) {
  474. var _this = this;
  475. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  476. var match = regex.exec(sourceCode);
  477. var returnValue = new String(sourceCode);
  478. while (match != null) {
  479. var includeFile = match[1];
  480. // Uniform declaration
  481. if (includeFile.indexOf("__decl__") !== -1) {
  482. includeFile = includeFile.replace(/__decl__/, "");
  483. if (this._engine.supportsUniformBuffers) {
  484. includeFile = includeFile.replace(/Vertex/, "Ubo");
  485. includeFile = includeFile.replace(/Fragment/, "Ubo");
  486. }
  487. includeFile = includeFile + "Declaration";
  488. }
  489. if (Effect.IncludesShadersStore[includeFile]) {
  490. // Substitution
  491. var includeContent = Effect.IncludesShadersStore[includeFile];
  492. if (match[2]) {
  493. var splits = match[3].split(",");
  494. for (var index = 0; index < splits.length; index += 2) {
  495. var source = new RegExp(splits[index], "g");
  496. var dest = splits[index + 1];
  497. includeContent = includeContent.replace(source, dest);
  498. }
  499. }
  500. if (match[4]) {
  501. var indexString = match[5];
  502. if (indexString.indexOf("..") !== -1) {
  503. var indexSplits = indexString.split("..");
  504. var minIndex = parseInt(indexSplits[0]);
  505. var maxIndex = parseInt(indexSplits[1]);
  506. var sourceIncludeContent = includeContent.slice(0);
  507. includeContent = "";
  508. if (isNaN(maxIndex)) {
  509. maxIndex = this._indexParameters[indexSplits[1]];
  510. }
  511. for (var i = minIndex; i < maxIndex; i++) {
  512. if (!this._engine.supportsUniformBuffers) {
  513. // Ubo replacement
  514. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  515. return p1 + "{X}";
  516. });
  517. }
  518. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  519. }
  520. }
  521. else {
  522. if (!this._engine.supportsUniformBuffers) {
  523. // Ubo replacement
  524. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  525. return p1 + "{X}";
  526. });
  527. }
  528. includeContent = includeContent.replace(/\{X\}/g, indexString);
  529. }
  530. }
  531. // Replace
  532. returnValue = returnValue.replace(match[0], includeContent);
  533. }
  534. else {
  535. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  536. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  537. Effect.IncludesShadersStore[includeFile] = fileContent;
  538. _this._processIncludes(returnValue, callback);
  539. });
  540. return;
  541. }
  542. match = regex.exec(sourceCode);
  543. }
  544. callback(returnValue);
  545. };
  546. Effect.prototype._processPrecision = function (source) {
  547. if (source.indexOf("precision highp float") === -1) {
  548. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  549. source = "precision mediump float;\n" + source;
  550. }
  551. else {
  552. source = "precision highp float;\n" + source;
  553. }
  554. }
  555. else {
  556. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  557. source = source.replace("precision highp float", "precision mediump float");
  558. }
  559. }
  560. return source;
  561. };
  562. /**
  563. * Recompiles the webGL program
  564. * @param vertexSourceCode The source code for the vertex shader.
  565. * @param fragmentSourceCode The source code for the fragment shader.
  566. * @param onCompiled Callback called when completed.
  567. * @param onError Callback called on error.
  568. */
  569. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  570. var _this = this;
  571. this._isReady = false;
  572. this._vertexSourceCodeOverride = vertexSourceCode;
  573. this._fragmentSourceCodeOverride = fragmentSourceCode;
  574. this.onError = function (effect, error) {
  575. if (onError) {
  576. onError(error);
  577. }
  578. };
  579. this.onCompiled = function () {
  580. var scenes = _this.getEngine().scenes;
  581. for (var i = 0; i < scenes.length; i++) {
  582. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  583. }
  584. if (onCompiled) {
  585. onCompiled(_this._program);
  586. }
  587. };
  588. this._fallbacks = null;
  589. this._prepareEffect();
  590. };
  591. /**
  592. * Gets the uniform locations of the the specified variable names
  593. * @param names THe names of the variables to lookup.
  594. * @returns Array of locations in the same order as variable names.
  595. */
  596. Effect.prototype.getSpecificUniformLocations = function (names) {
  597. var engine = this._engine;
  598. return engine.getUniforms(this._program, names);
  599. };
  600. /**
  601. * Prepares the effect
  602. */
  603. Effect.prototype._prepareEffect = function () {
  604. var attributesNames = this._attributesNames;
  605. var defines = this.defines;
  606. var fallbacks = this._fallbacks;
  607. this._valueCache = {};
  608. var previousProgram = this._program;
  609. try {
  610. var engine = this._engine;
  611. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  612. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  613. }
  614. else {
  615. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  616. }
  617. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  618. if (engine.supportsUniformBuffers) {
  619. for (var name in this._uniformBuffersNames) {
  620. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  621. }
  622. }
  623. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  624. this._attributes = engine.getAttributes(this._program, attributesNames);
  625. var index;
  626. for (index = 0; index < this._samplers.length; index++) {
  627. var sampler = this.getUniform(this._samplers[index]);
  628. if (sampler == null) {
  629. this._samplers.splice(index, 1);
  630. index--;
  631. }
  632. }
  633. engine.bindSamplers(this);
  634. this._compilationError = "";
  635. this._isReady = true;
  636. if (this.onCompiled) {
  637. this.onCompiled(this);
  638. }
  639. this.onCompileObservable.notifyObservers(this);
  640. this.onCompileObservable.clear();
  641. // Unbind mesh reference in fallbacks
  642. if (this._fallbacks) {
  643. this._fallbacks.unBindMesh();
  644. }
  645. if (previousProgram) {
  646. this.getEngine()._deleteProgram(previousProgram);
  647. }
  648. }
  649. catch (e) {
  650. this._compilationError = e.message;
  651. // Let's go through fallbacks then
  652. BABYLON.Tools.Error("Unable to compile effect:");
  653. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  654. return " " + uniform;
  655. }));
  656. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  657. return " " + attribute;
  658. }));
  659. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  660. BABYLON.Tools.Error("Error: " + this._compilationError);
  661. if (previousProgram) {
  662. this._program = previousProgram;
  663. this._isReady = true;
  664. if (this.onError) {
  665. this.onError(this, this._compilationError);
  666. }
  667. this.onErrorObservable.notifyObservers(this);
  668. }
  669. if (fallbacks && fallbacks.isMoreFallbacks) {
  670. BABYLON.Tools.Error("Trying next fallback.");
  671. this.defines = fallbacks.reduce(this.defines, this);
  672. this._prepareEffect();
  673. }
  674. else {
  675. if (this.onError) {
  676. this.onError(this, this._compilationError);
  677. }
  678. this.onErrorObservable.notifyObservers(this);
  679. this.onErrorObservable.clear();
  680. // Unbind mesh reference in fallbacks
  681. if (this._fallbacks) {
  682. this._fallbacks.unBindMesh();
  683. }
  684. }
  685. }
  686. };
  687. Object.defineProperty(Effect.prototype, "isSupported", {
  688. /**
  689. * Checks if the effect is supported. (Must be called after compilation)
  690. */
  691. get: function () {
  692. return this._compilationError === "";
  693. },
  694. enumerable: true,
  695. configurable: true
  696. });
  697. /**
  698. * Binds a texture to the engine to be used as output of the shader.
  699. * @param channel Name of the output variable.
  700. * @param texture Texture to bind.
  701. */
  702. Effect.prototype._bindTexture = function (channel, texture) {
  703. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  704. };
  705. /**
  706. * Sets a texture on the engine to be used in the shader.
  707. * @param channel Name of the sampler variable.
  708. * @param texture Texture to set.
  709. */
  710. Effect.prototype.setTexture = function (channel, texture) {
  711. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  712. };
  713. /**
  714. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  715. * @param channel Name of the sampler variable.
  716. * @param texture Texture to set.
  717. */
  718. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  719. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  720. };
  721. /**
  722. * Sets an array of textures on the engine to be used in the shader.
  723. * @param channel Name of the variable.
  724. * @param textures Textures to set.
  725. */
  726. Effect.prototype.setTextureArray = function (channel, textures) {
  727. if (this._samplers.indexOf(channel + "Ex") === -1) {
  728. var initialPos = this._samplers.indexOf(channel);
  729. for (var index = 1; index < textures.length; index++) {
  730. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  731. }
  732. }
  733. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  734. };
  735. /**
  736. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  737. * @param channel Name of the sampler variable.
  738. * @param postProcess Post process to get the input texture from.
  739. */
  740. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  741. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  742. };
  743. /**
  744. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  745. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  746. * @param channel Name of the sampler variable.
  747. * @param postProcess Post process to get the output texture from.
  748. */
  749. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  750. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  751. };
  752. /** @ignore */
  753. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  754. var cache = this._valueCache[uniformName];
  755. var flag = matrix.updateFlag;
  756. if (cache !== undefined && cache === flag) {
  757. return false;
  758. }
  759. this._valueCache[uniformName] = flag;
  760. return true;
  761. };
  762. /** @ignore */
  763. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  764. var cache = this._valueCache[uniformName];
  765. if (!cache) {
  766. cache = [x, y];
  767. this._valueCache[uniformName] = cache;
  768. return true;
  769. }
  770. var changed = false;
  771. if (cache[0] !== x) {
  772. cache[0] = x;
  773. changed = true;
  774. }
  775. if (cache[1] !== y) {
  776. cache[1] = y;
  777. changed = true;
  778. }
  779. return changed;
  780. };
  781. /** @ignore */
  782. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  783. var cache = this._valueCache[uniformName];
  784. if (!cache) {
  785. cache = [x, y, z];
  786. this._valueCache[uniformName] = cache;
  787. return true;
  788. }
  789. var changed = false;
  790. if (cache[0] !== x) {
  791. cache[0] = x;
  792. changed = true;
  793. }
  794. if (cache[1] !== y) {
  795. cache[1] = y;
  796. changed = true;
  797. }
  798. if (cache[2] !== z) {
  799. cache[2] = z;
  800. changed = true;
  801. }
  802. return changed;
  803. };
  804. /** @ignore */
  805. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  806. var cache = this._valueCache[uniformName];
  807. if (!cache) {
  808. cache = [x, y, z, w];
  809. this._valueCache[uniformName] = cache;
  810. return true;
  811. }
  812. var changed = false;
  813. if (cache[0] !== x) {
  814. cache[0] = x;
  815. changed = true;
  816. }
  817. if (cache[1] !== y) {
  818. cache[1] = y;
  819. changed = true;
  820. }
  821. if (cache[2] !== z) {
  822. cache[2] = z;
  823. changed = true;
  824. }
  825. if (cache[3] !== w) {
  826. cache[3] = w;
  827. changed = true;
  828. }
  829. return changed;
  830. };
  831. /**
  832. * Binds a buffer to a uniform.
  833. * @param buffer Buffer to bind.
  834. * @param name Name of the uniform variable to bind to.
  835. */
  836. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  837. var bufferName = this._uniformBuffersNames[name];
  838. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  839. return;
  840. }
  841. Effect._baseCache[bufferName] = buffer;
  842. this._engine.bindUniformBufferBase(buffer, bufferName);
  843. };
  844. /**
  845. * Binds block to a uniform.
  846. * @param blockName Name of the block to bind.
  847. * @param index Index to bind.
  848. */
  849. Effect.prototype.bindUniformBlock = function (blockName, index) {
  850. this._engine.bindUniformBlock(this._program, blockName, index);
  851. };
  852. /**
  853. * Sets an interger value on a uniform variable.
  854. * @param uniformName Name of the variable.
  855. * @param value Value to be set.
  856. * @returns this effect.
  857. */
  858. Effect.prototype.setInt = function (uniformName, value) {
  859. var cache = this._valueCache[uniformName];
  860. if (cache !== undefined && cache === value)
  861. return this;
  862. this._valueCache[uniformName] = value;
  863. this._engine.setInt(this.getUniform(uniformName), value);
  864. return this;
  865. };
  866. /**
  867. * Sets an int array on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param array array to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setIntArray = function (uniformName, array) {
  873. this._valueCache[uniformName] = null;
  874. this._engine.setIntArray(this.getUniform(uniformName), array);
  875. return this;
  876. };
  877. /**
  878. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  879. * @param uniformName Name of the variable.
  880. * @param array array to be set.
  881. * @returns this effect.
  882. */
  883. Effect.prototype.setIntArray2 = function (uniformName, array) {
  884. this._valueCache[uniformName] = null;
  885. this._engine.setIntArray2(this.getUniform(uniformName), array);
  886. return this;
  887. };
  888. /**
  889. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  890. * @param uniformName Name of the variable.
  891. * @param array array to be set.
  892. * @returns this effect.
  893. */
  894. Effect.prototype.setIntArray3 = function (uniformName, array) {
  895. this._valueCache[uniformName] = null;
  896. this._engine.setIntArray3(this.getUniform(uniformName), array);
  897. return this;
  898. };
  899. /**
  900. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  901. * @param uniformName Name of the variable.
  902. * @param array array to be set.
  903. * @returns this effect.
  904. */
  905. Effect.prototype.setIntArray4 = function (uniformName, array) {
  906. this._valueCache[uniformName] = null;
  907. this._engine.setIntArray4(this.getUniform(uniformName), array);
  908. return this;
  909. };
  910. /**
  911. * Sets an float array on a uniform variable.
  912. * @param uniformName Name of the variable.
  913. * @param array array to be set.
  914. * @returns this effect.
  915. */
  916. Effect.prototype.setFloatArray = function (uniformName, array) {
  917. this._valueCache[uniformName] = null;
  918. this._engine.setFloatArray(this.getUniform(uniformName), array);
  919. return this;
  920. };
  921. /**
  922. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  923. * @param uniformName Name of the variable.
  924. * @param array array to be set.
  925. * @returns this effect.
  926. */
  927. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  928. this._valueCache[uniformName] = null;
  929. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  930. return this;
  931. };
  932. /**
  933. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  934. * @param uniformName Name of the variable.
  935. * @param array array to be set.
  936. * @returns this effect.
  937. */
  938. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  939. this._valueCache[uniformName] = null;
  940. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  941. return this;
  942. };
  943. /**
  944. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  945. * @param uniformName Name of the variable.
  946. * @param array array to be set.
  947. * @returns this effect.
  948. */
  949. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  950. this._valueCache[uniformName] = null;
  951. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  952. return this;
  953. };
  954. /**
  955. * Sets an array on a uniform variable.
  956. * @param uniformName Name of the variable.
  957. * @param array array to be set.
  958. * @returns this effect.
  959. */
  960. Effect.prototype.setArray = function (uniformName, array) {
  961. this._valueCache[uniformName] = null;
  962. this._engine.setArray(this.getUniform(uniformName), array);
  963. return this;
  964. };
  965. /**
  966. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  967. * @param uniformName Name of the variable.
  968. * @param array array to be set.
  969. * @returns this effect.
  970. */
  971. Effect.prototype.setArray2 = function (uniformName, array) {
  972. this._valueCache[uniformName] = null;
  973. this._engine.setArray2(this.getUniform(uniformName), array);
  974. return this;
  975. };
  976. /**
  977. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  978. * @param uniformName Name of the variable.
  979. * @param array array to be set.
  980. * @returns this effect.
  981. */
  982. Effect.prototype.setArray3 = function (uniformName, array) {
  983. this._valueCache[uniformName] = null;
  984. this._engine.setArray3(this.getUniform(uniformName), array);
  985. return this;
  986. };
  987. /**
  988. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  989. * @param uniformName Name of the variable.
  990. * @param array array to be set.
  991. * @returns this effect.
  992. */
  993. Effect.prototype.setArray4 = function (uniformName, array) {
  994. this._valueCache[uniformName] = null;
  995. this._engine.setArray4(this.getUniform(uniformName), array);
  996. return this;
  997. };
  998. /**
  999. * Sets matrices on a uniform variable.
  1000. * @param uniformName Name of the variable.
  1001. * @param matrices matrices to be set.
  1002. * @returns this effect.
  1003. */
  1004. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1005. if (!matrices) {
  1006. return this;
  1007. }
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrix on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrix matrix to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1019. if (this._cacheMatrix(uniformName, matrix)) {
  1020. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1021. }
  1022. return this;
  1023. };
  1024. /**
  1025. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1026. * @param uniformName Name of the variable.
  1027. * @param matrix matrix to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1031. this._valueCache[uniformName] = null;
  1032. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1033. return this;
  1034. };
  1035. /**
  1036. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1037. * @param uniformName Name of the variable.
  1038. * @param matrix matrix to be set.
  1039. * @returns this effect.
  1040. */
  1041. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1042. this._valueCache[uniformName] = null;
  1043. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1044. return this;
  1045. };
  1046. /**
  1047. * Sets a float on a uniform variable.
  1048. * @param uniformName Name of the variable.
  1049. * @param value value to be set.
  1050. * @returns this effect.
  1051. */
  1052. Effect.prototype.setFloat = function (uniformName, value) {
  1053. var cache = this._valueCache[uniformName];
  1054. if (cache !== undefined && cache === value)
  1055. return this;
  1056. this._valueCache[uniformName] = value;
  1057. this._engine.setFloat(this.getUniform(uniformName), value);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a boolean on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param bool value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setBool = function (uniformName, bool) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === bool)
  1069. return this;
  1070. this._valueCache[uniformName] = bool;
  1071. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a Vector2 on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param vector2 vector2 to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1081. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1082. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1083. }
  1084. return this;
  1085. };
  1086. /**
  1087. * Sets a float2 on a uniform variable.
  1088. * @param uniformName Name of the variable.
  1089. * @param x First float in float2.
  1090. * @param y Second float in float2.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1094. if (this._cacheFloat2(uniformName, x, y)) {
  1095. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1096. }
  1097. return this;
  1098. };
  1099. /**
  1100. * Sets a Vector3 on a uniform variable.
  1101. * @param uniformName Name of the variable.
  1102. * @param vector3 Value to be set.
  1103. * @returns this effect.
  1104. */
  1105. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1106. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1107. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1108. }
  1109. return this;
  1110. };
  1111. /**
  1112. * Sets a float3 on a uniform variable.
  1113. * @param uniformName Name of the variable.
  1114. * @param x First float in float3.
  1115. * @param y Second float in float3.
  1116. * @param z Third float in float3.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1120. if (this._cacheFloat3(uniformName, x, y, z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a Vector4 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param vector4 Value to be set.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1132. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1133. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1134. }
  1135. return this;
  1136. };
  1137. /**
  1138. * Sets a float4 on a uniform variable.
  1139. * @param uniformName Name of the variable.
  1140. * @param x First float in float4.
  1141. * @param y Second float in float4.
  1142. * @param z Third float in float4.
  1143. * @param w Fourth float in float4.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1147. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1148. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a Color3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param color3 Value to be set.
  1156. * @returns this effect.
  1157. */
  1158. Effect.prototype.setColor3 = function (uniformName, color3) {
  1159. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1160. this._engine.setColor3(this.getUniform(uniformName), color3);
  1161. }
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a Color4 on a uniform variable.
  1166. * @param uniformName Name of the variable.
  1167. * @param color3 Value to be set.
  1168. * @param alpha Alpha value to be set.
  1169. * @returns this effect.
  1170. */
  1171. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1172. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1173. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1174. }
  1175. return this;
  1176. };
  1177. /**
  1178. * Sets a Color4 on a uniform variable
  1179. * @param uniformName defines the name of the variable
  1180. * @param color4 defines the value to be set
  1181. * @returns this effect.
  1182. */
  1183. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1184. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1185. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1186. }
  1187. return this;
  1188. };
  1189. /**
  1190. * Resets the cache of effects.
  1191. */
  1192. Effect.ResetCache = function () {
  1193. Effect._baseCache = {};
  1194. };
  1195. Effect._uniqueIdSeed = 0;
  1196. Effect._baseCache = {};
  1197. /**
  1198. * Store of each shader (The can be looked up using effect.key)
  1199. */
  1200. Effect.ShadersStore = {};
  1201. /**
  1202. * Store of each included file for a shader (The can be looked up using effect.key)
  1203. */
  1204. Effect.IncludesShadersStore = {};
  1205. return Effect;
  1206. }());
  1207. BABYLON.Effect = Effect;
  1208. })(BABYLON || (BABYLON = {}));
  1209. //# sourceMappingURL=babylon.effect.js.map
  1210. "use strict";
  1211. //# sourceMappingURL=babylon.types.js.map
  1212. "use strict";
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. "use strict";
  1262. var BABYLON;
  1263. (function (BABYLON) {
  1264. var PointerEventTypes = /** @class */ (function () {
  1265. function PointerEventTypes() {
  1266. }
  1267. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1268. get: function () {
  1269. return PointerEventTypes._POINTERDOWN;
  1270. },
  1271. enumerable: true,
  1272. configurable: true
  1273. });
  1274. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1275. get: function () {
  1276. return PointerEventTypes._POINTERUP;
  1277. },
  1278. enumerable: true,
  1279. configurable: true
  1280. });
  1281. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1282. get: function () {
  1283. return PointerEventTypes._POINTERMOVE;
  1284. },
  1285. enumerable: true,
  1286. configurable: true
  1287. });
  1288. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1289. get: function () {
  1290. return PointerEventTypes._POINTERWHEEL;
  1291. },
  1292. enumerable: true,
  1293. configurable: true
  1294. });
  1295. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1296. get: function () {
  1297. return PointerEventTypes._POINTERPICK;
  1298. },
  1299. enumerable: true,
  1300. configurable: true
  1301. });
  1302. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1303. get: function () {
  1304. return PointerEventTypes._POINTERTAP;
  1305. },
  1306. enumerable: true,
  1307. configurable: true
  1308. });
  1309. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1310. get: function () {
  1311. return PointerEventTypes._POINTERDOUBLETAP;
  1312. },
  1313. enumerable: true,
  1314. configurable: true
  1315. });
  1316. PointerEventTypes._POINTERDOWN = 0x01;
  1317. PointerEventTypes._POINTERUP = 0x02;
  1318. PointerEventTypes._POINTERMOVE = 0x04;
  1319. PointerEventTypes._POINTERWHEEL = 0x08;
  1320. PointerEventTypes._POINTERPICK = 0x10;
  1321. PointerEventTypes._POINTERTAP = 0x20;
  1322. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1323. return PointerEventTypes;
  1324. }());
  1325. BABYLON.PointerEventTypes = PointerEventTypes;
  1326. var PointerInfoBase = /** @class */ (function () {
  1327. function PointerInfoBase(type, event) {
  1328. this.type = type;
  1329. this.event = event;
  1330. }
  1331. return PointerInfoBase;
  1332. }());
  1333. BABYLON.PointerInfoBase = PointerInfoBase;
  1334. /**
  1335. * This class is used to store pointer related info for the onPrePointerObservable event.
  1336. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1337. */
  1338. var PointerInfoPre = /** @class */ (function (_super) {
  1339. __extends(PointerInfoPre, _super);
  1340. function PointerInfoPre(type, event, localX, localY) {
  1341. var _this = _super.call(this, type, event) || this;
  1342. _this.skipOnPointerObservable = false;
  1343. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1344. return _this;
  1345. }
  1346. return PointerInfoPre;
  1347. }(PointerInfoBase));
  1348. BABYLON.PointerInfoPre = PointerInfoPre;
  1349. /**
  1350. * This type contains all the data related to a pointer event in Babylon.js.
  1351. * 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.
  1352. */
  1353. var PointerInfo = /** @class */ (function (_super) {
  1354. __extends(PointerInfo, _super);
  1355. function PointerInfo(type, event, pickInfo) {
  1356. var _this = _super.call(this, type, event) || this;
  1357. _this.pickInfo = pickInfo;
  1358. return _this;
  1359. }
  1360. return PointerInfo;
  1361. }(PointerInfoBase));
  1362. BABYLON.PointerInfo = PointerInfo;
  1363. })(BABYLON || (BABYLON = {}));
  1364. //# sourceMappingURL=babylon.pointerEvents.js.map
  1365. "use strict";
  1366. var BABYLON;
  1367. (function (BABYLON) {
  1368. BABYLON.ToGammaSpace = 1 / 2.2;
  1369. BABYLON.ToLinearSpace = 2.2;
  1370. BABYLON.Epsilon = 0.001;
  1371. /**
  1372. * Class used to hold a RBG color
  1373. */
  1374. var Color3 = /** @class */ (function () {
  1375. /**
  1376. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1377. * @param r defines the red component (between 0 and 1, default is 0)
  1378. * @param g defines the green component (between 0 and 1, default is 0)
  1379. * @param b defines the blue component (between 0 and 1, default is 0)
  1380. */
  1381. function Color3(
  1382. /**
  1383. * Defines the red component (between 0 and 1, default is 0)
  1384. */
  1385. r,
  1386. /**
  1387. * Defines the green component (between 0 and 1, default is 0)
  1388. */
  1389. g,
  1390. /**
  1391. * Defines the blue component (between 0 and 1, default is 0)
  1392. */
  1393. b) {
  1394. if (r === void 0) { r = 0; }
  1395. if (g === void 0) { g = 0; }
  1396. if (b === void 0) { b = 0; }
  1397. this.r = r;
  1398. this.g = g;
  1399. this.b = b;
  1400. }
  1401. /**
  1402. * Creates a string with the Color3 current values
  1403. * @returns the string representation of the Color3 object
  1404. */
  1405. Color3.prototype.toString = function () {
  1406. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1407. };
  1408. /**
  1409. * Returns the string "Color3"
  1410. * @returns "Color3"
  1411. */
  1412. Color3.prototype.getClassName = function () {
  1413. return "Color3";
  1414. };
  1415. /**
  1416. * Compute the Color3 hash code
  1417. * @returns an unique number that can be used to hash Color3 objects
  1418. */
  1419. Color3.prototype.getHashCode = function () {
  1420. var hash = this.r || 0;
  1421. hash = (hash * 397) ^ (this.g || 0);
  1422. hash = (hash * 397) ^ (this.b || 0);
  1423. return hash;
  1424. };
  1425. // Operators
  1426. /**
  1427. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1428. * @param array defines the array where to store the r,g,b components
  1429. * @param index defines an optional index in the target array to define where to start storing values
  1430. * @returns the current Color3 object
  1431. */
  1432. Color3.prototype.toArray = function (array, index) {
  1433. if (index === undefined) {
  1434. index = 0;
  1435. }
  1436. array[index] = this.r;
  1437. array[index + 1] = this.g;
  1438. array[index + 2] = this.b;
  1439. return this;
  1440. };
  1441. /**
  1442. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1443. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1444. * @returns a new {BABYLON.Color4} object
  1445. */
  1446. Color3.prototype.toColor4 = function (alpha) {
  1447. if (alpha === void 0) { alpha = 1; }
  1448. return new Color4(this.r, this.g, this.b, alpha);
  1449. };
  1450. /**
  1451. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1452. * @returns the new array
  1453. */
  1454. Color3.prototype.asArray = function () {
  1455. var result = new Array();
  1456. this.toArray(result, 0);
  1457. return result;
  1458. };
  1459. /**
  1460. * Returns the luminance value
  1461. * @returns a float value
  1462. */
  1463. Color3.prototype.toLuminance = function () {
  1464. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1465. };
  1466. /**
  1467. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1468. * @param otherColor defines the second operand
  1469. * @returns the new Color3 object
  1470. */
  1471. Color3.prototype.multiply = function (otherColor) {
  1472. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1473. };
  1474. /**
  1475. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1476. * @param otherColor defines the second operand
  1477. * @param result defines the Color3 object where to store the result
  1478. * @returns the current Color3
  1479. */
  1480. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1481. result.r = this.r * otherColor.r;
  1482. result.g = this.g * otherColor.g;
  1483. result.b = this.b * otherColor.b;
  1484. return this;
  1485. };
  1486. /**
  1487. * Determines equality between Color3 objects
  1488. * @param otherColor defines the second operand
  1489. * @returns true if the rgb values are equal to the passed ones
  1490. */
  1491. Color3.prototype.equals = function (otherColor) {
  1492. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1493. };
  1494. /**
  1495. * Determines equality between the current Color3 object and a set of r,b,g values
  1496. * @param r defines the red component to check
  1497. * @param g defines the green component to check
  1498. * @param b defines the blue component to check
  1499. * @returns true if the rgb values are equal to the passed ones
  1500. */
  1501. Color3.prototype.equalsFloats = function (r, g, b) {
  1502. return this.r === r && this.g === g && this.b === b;
  1503. };
  1504. /**
  1505. * Multiplies in place each rgb value by scale
  1506. * @param scale defines the scaling factor
  1507. * @returns the updated Color3
  1508. */
  1509. Color3.prototype.scale = function (scale) {
  1510. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1511. };
  1512. /**
  1513. * Multiplies the rgb values by scale and stores the result into "result"
  1514. * @param scale defines the scaling factor
  1515. * @param result defines the Color3 object where to store the result
  1516. * @returns the unmodified current Color3
  1517. */
  1518. Color3.prototype.scaleToRef = function (scale, result) {
  1519. result.r = this.r * scale;
  1520. result.g = this.g * scale;
  1521. result.b = this.b * scale;
  1522. return this;
  1523. };
  1524. /**
  1525. * Scale the current Color3 values by a factor and add the result to a given Color3
  1526. * @param scale defines the scale factor
  1527. * @param result defines color to store the result into
  1528. * @returns the unmodified current Color3
  1529. */
  1530. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1531. result.r += this.r * scale;
  1532. result.g += this.g * scale;
  1533. result.b += this.b * scale;
  1534. return this;
  1535. };
  1536. /**
  1537. * Clamps the rgb values by the min and max values and stores the result into "result"
  1538. * @param min defines minimum clamping value (default is 0)
  1539. * @param max defines maximum clamping value (default is 1)
  1540. * @param result defines color to store the result into
  1541. * @returns the original Color3
  1542. */
  1543. Color3.prototype.clampToRef = function (min, max, result) {
  1544. if (min === void 0) { min = 0; }
  1545. if (max === void 0) { max = 1; }
  1546. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1547. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1548. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1549. return this;
  1550. };
  1551. /**
  1552. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1553. * @param otherColor defines the second operand
  1554. * @returns the new Color3
  1555. */
  1556. Color3.prototype.add = function (otherColor) {
  1557. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1558. };
  1559. /**
  1560. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1561. * @param otherColor defines the second operand
  1562. * @param result defines Color3 object to store the result into
  1563. * @returns the unmodified current Color3
  1564. */
  1565. Color3.prototype.addToRef = function (otherColor, result) {
  1566. result.r = this.r + otherColor.r;
  1567. result.g = this.g + otherColor.g;
  1568. result.b = this.b + otherColor.b;
  1569. return this;
  1570. };
  1571. /**
  1572. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1573. * @param otherColor defines the second operand
  1574. * @returns the new Color3
  1575. */
  1576. Color3.prototype.subtract = function (otherColor) {
  1577. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1578. };
  1579. /**
  1580. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1581. * @param otherColor defines the second operand
  1582. * @param result defines Color3 object to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.subtractToRef = function (otherColor, result) {
  1586. result.r = this.r - otherColor.r;
  1587. result.g = this.g - otherColor.g;
  1588. result.b = this.b - otherColor.b;
  1589. return this;
  1590. };
  1591. /**
  1592. * Copy the current object
  1593. * @returns a new Color3 copied the current one
  1594. */
  1595. Color3.prototype.clone = function () {
  1596. return new Color3(this.r, this.g, this.b);
  1597. };
  1598. /**
  1599. * Copies the rgb values from the source in the current Color3
  1600. * @param source defines the source Color3 object
  1601. * @returns the updated Color3 object
  1602. */
  1603. Color3.prototype.copyFrom = function (source) {
  1604. this.r = source.r;
  1605. this.g = source.g;
  1606. this.b = source.b;
  1607. return this;
  1608. };
  1609. /**
  1610. * Updates the Color3 rgb values from the passed floats
  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. * @returns the current Color3 object
  1615. */
  1616. Color3.prototype.copyFromFloats = function (r, g, b) {
  1617. this.r = r;
  1618. this.g = g;
  1619. this.b = b;
  1620. return this;
  1621. };
  1622. /**
  1623. * Updates the Color3 rgb values from the passed floats
  1624. * @param r defines the red component to read from
  1625. * @param g defines the green component to read from
  1626. * @param b defines the blue component to read from
  1627. * @returns the current Color3 object
  1628. */
  1629. Color3.prototype.set = function (r, g, b) {
  1630. return this.copyFromFloats(r, g, b);
  1631. };
  1632. /**
  1633. * Compute the Color3 hexadecimal code as a string
  1634. * @returns a string containing the hexadecimal representation of the Color3 object
  1635. */
  1636. Color3.prototype.toHexString = function () {
  1637. var intR = (this.r * 255) | 0;
  1638. var intG = (this.g * 255) | 0;
  1639. var intB = (this.b * 255) | 0;
  1640. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1641. };
  1642. /**
  1643. * Computes a new Color3 converted from the current one to linear space
  1644. * @returns a new Color3 object
  1645. */
  1646. Color3.prototype.toLinearSpace = function () {
  1647. var convertedColor = new Color3();
  1648. this.toLinearSpaceToRef(convertedColor);
  1649. return convertedColor;
  1650. };
  1651. /**
  1652. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1653. * @param convertedColor defines the Color3 object where to store the linear space version
  1654. * @returns the unmodified Color3
  1655. */
  1656. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1657. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1658. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1659. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1660. return this;
  1661. };
  1662. /**
  1663. * Computes a new Color3 converted from the current one to gamma space
  1664. * @returns a new Color3 object
  1665. */
  1666. Color3.prototype.toGammaSpace = function () {
  1667. var convertedColor = new Color3();
  1668. this.toGammaSpaceToRef(convertedColor);
  1669. return convertedColor;
  1670. };
  1671. /**
  1672. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1673. * @param convertedColor defines the Color3 object where to store the gamma space version
  1674. * @returns the unmodified Color3
  1675. */
  1676. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1677. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1678. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1679. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1680. return this;
  1681. };
  1682. // Statics
  1683. /**
  1684. * Creates a new Color3 from the string containing valid hexadecimal values
  1685. * @param hex defines a string containing valid hexadecimal values
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.FromHexString = function (hex) {
  1689. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1690. return new Color3(0, 0, 0);
  1691. }
  1692. var r = parseInt(hex.substring(1, 3), 16);
  1693. var g = parseInt(hex.substring(3, 5), 16);
  1694. var b = parseInt(hex.substring(5, 7), 16);
  1695. return Color3.FromInts(r, g, b);
  1696. };
  1697. /**
  1698. * Creates a new Vector3 from the starting index of the passed array
  1699. * @param array defines the source array
  1700. * @param offset defines an offset in the source array
  1701. * @returns a new Color3 object
  1702. */
  1703. Color3.FromArray = function (array, offset) {
  1704. if (offset === void 0) { offset = 0; }
  1705. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1706. };
  1707. /**
  1708. * Creates a new Color3 from integer values (< 256)
  1709. * @param r defines the red component to read from (value between 0 and 255)
  1710. * @param g defines the green component to read from (value between 0 and 255)
  1711. * @param b defines the blue component to read from (value between 0 and 255)
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.FromInts = function (r, g, b) {
  1715. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1716. };
  1717. /**
  1718. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1719. * @param start defines the start Color3 value
  1720. * @param end defines the end Color3 value
  1721. * @param amount defines the gradient value between start and end
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.Lerp = function (start, end, amount) {
  1725. var r = start.r + ((end.r - start.r) * amount);
  1726. var g = start.g + ((end.g - start.g) * amount);
  1727. var b = start.b + ((end.b - start.b) * amount);
  1728. return new Color3(r, g, b);
  1729. };
  1730. /**
  1731. * Returns a Color3 value containing a red color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Red = function () { return new Color3(1, 0, 0); };
  1735. /**
  1736. * Returns a Color3 value containing a green color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Green = function () { return new Color3(0, 1, 0); };
  1740. /**
  1741. * Returns a Color3 value containing a blue color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1745. /**
  1746. * Returns a Color3 value containing a black color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Black = function () { return new Color3(0, 0, 0); };
  1750. /**
  1751. * Returns a Color3 value containing a white color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.White = function () { return new Color3(1, 1, 1); };
  1755. /**
  1756. * Returns a Color3 value containing a purple color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1760. /**
  1761. * Returns a Color3 value containing a magenta color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1765. /**
  1766. * Returns a Color3 value containing a yellow color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1770. /**
  1771. * Returns a Color3 value containing a gray color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1775. /**
  1776. * Returns a Color3 value containing a teal color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1780. /**
  1781. * Returns a Color3 value containing a random color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1785. return Color3;
  1786. }());
  1787. BABYLON.Color3 = Color3;
  1788. /**
  1789. * Class used to hold a RBGA color
  1790. */
  1791. var Color4 = /** @class */ (function () {
  1792. /**
  1793. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1794. * @param r defines the red component (between 0 and 1, default is 0)
  1795. * @param g defines the green component (between 0 and 1, default is 0)
  1796. * @param b defines the blue component (between 0 and 1, default is 0)
  1797. * @param a defines the alpha component (between 0 and 1, default is 1)
  1798. */
  1799. function Color4(
  1800. /**
  1801. * Defines the red component (between 0 and 1, default is 0)
  1802. */
  1803. r,
  1804. /**
  1805. * Defines the green component (between 0 and 1, default is 0)
  1806. */
  1807. g,
  1808. /**
  1809. * Defines the blue component (between 0 and 1, default is 0)
  1810. */
  1811. b,
  1812. /**
  1813. * Defines the alpha component (between 0 and 1, default is 1)
  1814. */
  1815. a) {
  1816. if (r === void 0) { r = 0; }
  1817. if (g === void 0) { g = 0; }
  1818. if (b === void 0) { b = 0; }
  1819. if (a === void 0) { a = 1; }
  1820. this.r = r;
  1821. this.g = g;
  1822. this.b = b;
  1823. this.a = a;
  1824. }
  1825. // Operators
  1826. /**
  1827. * Adds in place the passed Color4 values to the current Color4 object
  1828. * @param right defines the second operand
  1829. * @returns the current updated Color4 object
  1830. */
  1831. Color4.prototype.addInPlace = function (right) {
  1832. this.r += right.r;
  1833. this.g += right.g;
  1834. this.b += right.b;
  1835. this.a += right.a;
  1836. return this;
  1837. };
  1838. /**
  1839. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1840. * @returns the new array
  1841. */
  1842. Color4.prototype.asArray = function () {
  1843. var result = new Array();
  1844. this.toArray(result, 0);
  1845. return result;
  1846. };
  1847. /**
  1848. * Stores from the starting index in the passed array the Color4 successive values
  1849. * @param array defines the array where to store the r,g,b components
  1850. * @param index defines an optional index in the target array to define where to start storing values
  1851. * @returns the current Color4 object
  1852. */
  1853. Color4.prototype.toArray = function (array, index) {
  1854. if (index === undefined) {
  1855. index = 0;
  1856. }
  1857. array[index] = this.r;
  1858. array[index + 1] = this.g;
  1859. array[index + 2] = this.b;
  1860. array[index + 3] = this.a;
  1861. return this;
  1862. };
  1863. /**
  1864. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1865. * @param right defines the second operand
  1866. * @returns a new Color4 object
  1867. */
  1868. Color4.prototype.add = function (right) {
  1869. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1870. };
  1871. /**
  1872. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1873. * @param right defines the second operand
  1874. * @returns a new Color4 object
  1875. */
  1876. Color4.prototype.subtract = function (right) {
  1877. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1878. };
  1879. /**
  1880. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1881. * @param right defines the second operand
  1882. * @param result defines the Color4 object where to store the result
  1883. * @returns the current Color4 object
  1884. */
  1885. Color4.prototype.subtractToRef = function (right, result) {
  1886. result.r = this.r - right.r;
  1887. result.g = this.g - right.g;
  1888. result.b = this.b - right.b;
  1889. result.a = this.a - right.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 with the current Color4 values multiplied by scale
  1894. * @param scale defines the scaling factor to apply
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.scale = function (scale) {
  1898. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1899. };
  1900. /**
  1901. * Multiplies the current Color4 values by scale and stores the result in "result"
  1902. * @param scale defines the scaling factor to apply
  1903. * @param result defines the Color4 object where to store the result
  1904. * @returns the current unmodified Color4
  1905. */
  1906. Color4.prototype.scaleToRef = function (scale, result) {
  1907. result.r = this.r * scale;
  1908. result.g = this.g * scale;
  1909. result.b = this.b * scale;
  1910. result.a = this.a * scale;
  1911. return this;
  1912. };
  1913. /**
  1914. * Scale the current Color4 values by a factor and add the result to a given Color4
  1915. * @param scale defines the scale factor
  1916. * @param result defines the Color4 object where to store the result
  1917. * @returns the unmodified current Color4
  1918. */
  1919. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1920. result.r += this.r * scale;
  1921. result.g += this.g * scale;
  1922. result.b += this.b * scale;
  1923. result.a += this.a * scale;
  1924. return this;
  1925. };
  1926. /**
  1927. * Clamps the rgb values by the min and max values and stores the result into "result"
  1928. * @param min defines minimum clamping value (default is 0)
  1929. * @param max defines maximum clamping value (default is 1)
  1930. * @param result defines color to store the result into.
  1931. * @returns the cuurent Color4
  1932. */
  1933. Color4.prototype.clampToRef = function (min, max, result) {
  1934. if (min === void 0) { min = 0; }
  1935. if (max === void 0) { max = 1; }
  1936. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1937. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1938. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1939. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1940. return this;
  1941. };
  1942. /**
  1943. * Multipy an Color4 value by another and return a new Color4 object
  1944. * @param color defines the Color4 value to multiply by
  1945. * @returns a new Color4 object
  1946. */
  1947. Color4.prototype.multiply = function (color) {
  1948. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1949. };
  1950. /**
  1951. * Multipy a Color4 value by another and push the result in a reference value
  1952. * @param color defines the Color4 value to multiply by
  1953. * @param result defines the Color4 to fill the result in
  1954. * @returns the result Color4
  1955. */
  1956. Color4.prototype.multiplyToRef = function (color, result) {
  1957. result.r = this.r * color.r;
  1958. result.g = this.g * color.g;
  1959. result.b = this.b * color.b;
  1960. result.a = this.a * color.a;
  1961. return result;
  1962. };
  1963. /**
  1964. * Creates a string with the Color4 current values
  1965. * @returns the string representation of the Color4 object
  1966. */
  1967. Color4.prototype.toString = function () {
  1968. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1969. };
  1970. /**
  1971. * Returns the string "Color4"
  1972. * @returns "Color4"
  1973. */
  1974. Color4.prototype.getClassName = function () {
  1975. return "Color4";
  1976. };
  1977. /**
  1978. * Compute the Color4 hash code
  1979. * @returns an unique number that can be used to hash Color4 objects
  1980. */
  1981. Color4.prototype.getHashCode = function () {
  1982. var hash = this.r || 0;
  1983. hash = (hash * 397) ^ (this.g || 0);
  1984. hash = (hash * 397) ^ (this.b || 0);
  1985. hash = (hash * 397) ^ (this.a || 0);
  1986. return hash;
  1987. };
  1988. /**
  1989. * Creates a new Color4 copied from the current one
  1990. * @returns a new Color4 object
  1991. */
  1992. Color4.prototype.clone = function () {
  1993. return new Color4(this.r, this.g, this.b, this.a);
  1994. };
  1995. /**
  1996. * Copies the passed Color4 values into the current one
  1997. * @param source defines the source Color4 object
  1998. * @returns the current updated Color4 object
  1999. */
  2000. Color4.prototype.copyFrom = function (source) {
  2001. this.r = source.r;
  2002. this.g = source.g;
  2003. this.b = source.b;
  2004. this.a = source.a;
  2005. return this;
  2006. };
  2007. /**
  2008. * Copies the passed float values into the current one
  2009. * @param r defines the red component to read from
  2010. * @param g defines the green component to read from
  2011. * @param b defines the blue component to read from
  2012. * @param a defines the alpha component to read from
  2013. * @returns the current updated Color4 object
  2014. */
  2015. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2016. this.r = r;
  2017. this.g = g;
  2018. this.b = b;
  2019. this.a = a;
  2020. return this;
  2021. };
  2022. /**
  2023. * Copies the passed float values into the current one
  2024. * @param r defines the red component to read from
  2025. * @param g defines the green component to read from
  2026. * @param b defines the blue component to read from
  2027. * @param a defines the alpha component to read from
  2028. * @returns the current updated Color4 object
  2029. */
  2030. Color4.prototype.set = function (r, g, b, a) {
  2031. return this.copyFromFloats(r, g, b, a);
  2032. };
  2033. /**
  2034. * Compute the Color4 hexadecimal code as a string
  2035. * @returns a string containing the hexadecimal representation of the Color4 object
  2036. */
  2037. Color4.prototype.toHexString = function () {
  2038. var intR = (this.r * 255) | 0;
  2039. var intG = (this.g * 255) | 0;
  2040. var intB = (this.b * 255) | 0;
  2041. var intA = (this.a * 255) | 0;
  2042. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2043. };
  2044. /**
  2045. * Computes a new Color4 converted from the current one to linear space
  2046. * @returns a new Color4 object
  2047. */
  2048. Color4.prototype.toLinearSpace = function () {
  2049. var convertedColor = new Color4();
  2050. this.toLinearSpaceToRef(convertedColor);
  2051. return convertedColor;
  2052. };
  2053. /**
  2054. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2055. * @param convertedColor defines the Color4 object where to store the linear space version
  2056. * @returns the unmodified Color4
  2057. */
  2058. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2059. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2060. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2061. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2062. convertedColor.a = this.a;
  2063. return this;
  2064. };
  2065. /**
  2066. * Computes a new Color4 converted from the current one to gamma space
  2067. * @returns a new Color4 object
  2068. */
  2069. Color4.prototype.toGammaSpace = function () {
  2070. var convertedColor = new Color4();
  2071. this.toGammaSpaceToRef(convertedColor);
  2072. return convertedColor;
  2073. };
  2074. /**
  2075. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2076. * @param convertedColor defines the Color4 object where to store the gamma space version
  2077. * @returns the unmodified Color4
  2078. */
  2079. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2080. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2081. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2082. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2083. convertedColor.a = this.a;
  2084. return this;
  2085. };
  2086. // Statics
  2087. /**
  2088. * Creates a new Color4 from the string containing valid hexadecimal values
  2089. * @param hex defines a string containing valid hexadecimal values
  2090. * @returns a new Color4 object
  2091. */
  2092. Color4.FromHexString = function (hex) {
  2093. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2094. return new Color4(0.0, 0.0, 0.0, 0.0);
  2095. }
  2096. var r = parseInt(hex.substring(1, 3), 16);
  2097. var g = parseInt(hex.substring(3, 5), 16);
  2098. var b = parseInt(hex.substring(5, 7), 16);
  2099. var a = parseInt(hex.substring(7, 9), 16);
  2100. return Color4.FromInts(r, g, b, a);
  2101. };
  2102. /**
  2103. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2104. * @param left defines the start value
  2105. * @param right defines the end value
  2106. * @param amount defines the gradient factor
  2107. * @returns a new Color4 object
  2108. */
  2109. Color4.Lerp = function (left, right, amount) {
  2110. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2111. Color4.LerpToRef(left, right, amount, result);
  2112. return result;
  2113. };
  2114. /**
  2115. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2116. * @param left defines the start value
  2117. * @param right defines the end value
  2118. * @param amount defines the gradient factor
  2119. * @param result defines the Color4 object where to store data
  2120. */
  2121. Color4.LerpToRef = function (left, right, amount, result) {
  2122. result.r = left.r + (right.r - left.r) * amount;
  2123. result.g = left.g + (right.g - left.g) * amount;
  2124. result.b = left.b + (right.b - left.b) * amount;
  2125. result.a = left.a + (right.a - left.a) * amount;
  2126. };
  2127. /**
  2128. * Creates a new Color4 from the starting index element of the passed array
  2129. * @param array defines the source array to read from
  2130. * @param offset defines the offset in the source array
  2131. * @returns a new Color4 object
  2132. */
  2133. Color4.FromArray = function (array, offset) {
  2134. if (offset === void 0) { offset = 0; }
  2135. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2136. };
  2137. /**
  2138. * Creates a new Color3 from integer values (< 256)
  2139. * @param r defines the red component to read from (value between 0 and 255)
  2140. * @param g defines the green component to read from (value between 0 and 255)
  2141. * @param b defines the blue component to read from (value between 0 and 255)
  2142. * @param a defines the alpha component to read from (value between 0 and 255)
  2143. * @returns a new Color3 object
  2144. */
  2145. Color4.FromInts = function (r, g, b, a) {
  2146. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2147. };
  2148. /**
  2149. * Check the content of a given array and convert it to an array containing RGBA data
  2150. * If the original array was already containing count * 4 values then it is returned directly
  2151. * @param colors defines the array to check
  2152. * @param count defines the number of RGBA data to expect
  2153. * @returns an array containing count * 4 values (RGBA)
  2154. */
  2155. Color4.CheckColors4 = function (colors, count) {
  2156. // Check if color3 was used
  2157. if (colors.length === count * 3) {
  2158. var colors4 = [];
  2159. for (var index = 0; index < colors.length; index += 3) {
  2160. var newIndex = (index / 3) * 4;
  2161. colors4[newIndex] = colors[index];
  2162. colors4[newIndex + 1] = colors[index + 1];
  2163. colors4[newIndex + 2] = colors[index + 2];
  2164. colors4[newIndex + 3] = 1.0;
  2165. }
  2166. return colors4;
  2167. }
  2168. return colors;
  2169. };
  2170. return Color4;
  2171. }());
  2172. BABYLON.Color4 = Color4;
  2173. var Vector2 = /** @class */ (function () {
  2174. /**
  2175. * Creates a new Vector2 from the passed x and y coordinates.
  2176. */
  2177. function Vector2(x, y) {
  2178. this.x = x;
  2179. this.y = y;
  2180. }
  2181. /**
  2182. * Returns a string with the Vector2 coordinates.
  2183. */
  2184. Vector2.prototype.toString = function () {
  2185. return "{X: " + this.x + " Y:" + this.y + "}";
  2186. };
  2187. /**
  2188. * Returns the string "Vector2"
  2189. */
  2190. Vector2.prototype.getClassName = function () {
  2191. return "Vector2";
  2192. };
  2193. /**
  2194. * Returns the Vector2 hash code as a number.
  2195. */
  2196. Vector2.prototype.getHashCode = function () {
  2197. var hash = this.x || 0;
  2198. hash = (hash * 397) ^ (this.y || 0);
  2199. return hash;
  2200. };
  2201. // Operators
  2202. /**
  2203. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2204. * Returns the Vector2.
  2205. */
  2206. Vector2.prototype.toArray = function (array, index) {
  2207. if (index === void 0) { index = 0; }
  2208. array[index] = this.x;
  2209. array[index + 1] = this.y;
  2210. return this;
  2211. };
  2212. /**
  2213. * Returns a new array with 2 elements : the Vector2 coordinates.
  2214. */
  2215. Vector2.prototype.asArray = function () {
  2216. var result = new Array();
  2217. this.toArray(result, 0);
  2218. return result;
  2219. };
  2220. /**
  2221. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2222. * Returns the updated Vector2.
  2223. */
  2224. Vector2.prototype.copyFrom = function (source) {
  2225. this.x = source.x;
  2226. this.y = source.y;
  2227. return this;
  2228. };
  2229. /**
  2230. * Sets the Vector2 coordinates with the passed floats.
  2231. * Returns the updated Vector2.
  2232. */
  2233. Vector2.prototype.copyFromFloats = function (x, y) {
  2234. this.x = x;
  2235. this.y = y;
  2236. return this;
  2237. };
  2238. /**
  2239. * Sets the Vector2 coordinates with the passed floats.
  2240. * Returns the updated Vector2.
  2241. */
  2242. Vector2.prototype.set = function (x, y) {
  2243. return this.copyFromFloats(x, y);
  2244. };
  2245. /**
  2246. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2247. */
  2248. Vector2.prototype.add = function (otherVector) {
  2249. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2250. };
  2251. /**
  2252. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2253. * Returns the Vector2.
  2254. */
  2255. Vector2.prototype.addToRef = function (otherVector, result) {
  2256. result.x = this.x + otherVector.x;
  2257. result.y = this.y + otherVector.y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2262. * Returns the updated Vector2.
  2263. */
  2264. Vector2.prototype.addInPlace = function (otherVector) {
  2265. this.x += otherVector.x;
  2266. this.y += otherVector.y;
  2267. return this;
  2268. };
  2269. /**
  2270. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2271. */
  2272. Vector2.prototype.addVector3 = function (otherVector) {
  2273. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2274. };
  2275. /**
  2276. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2277. */
  2278. Vector2.prototype.subtract = function (otherVector) {
  2279. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2280. };
  2281. /**
  2282. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2283. * Returns the Vector2.
  2284. */
  2285. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2286. result.x = this.x - otherVector.x;
  2287. result.y = this.y - otherVector.y;
  2288. return this;
  2289. };
  2290. /**
  2291. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2292. * Returns the updated Vector2.
  2293. */
  2294. Vector2.prototype.subtractInPlace = function (otherVector) {
  2295. this.x -= otherVector.x;
  2296. this.y -= otherVector.y;
  2297. return this;
  2298. };
  2299. /**
  2300. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2301. * Returns the updated Vector2.
  2302. */
  2303. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2304. this.x *= otherVector.x;
  2305. this.y *= otherVector.y;
  2306. return this;
  2307. };
  2308. /**
  2309. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2310. */
  2311. Vector2.prototype.multiply = function (otherVector) {
  2312. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2313. };
  2314. /**
  2315. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2316. * Returns the Vector2.
  2317. */
  2318. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2319. result.x = this.x * otherVector.x;
  2320. result.y = this.y * otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2325. */
  2326. Vector2.prototype.multiplyByFloats = function (x, y) {
  2327. return new Vector2(this.x * x, this.y * y);
  2328. };
  2329. /**
  2330. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2331. */
  2332. Vector2.prototype.divide = function (otherVector) {
  2333. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2334. };
  2335. /**
  2336. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2337. * Returns the Vector2.
  2338. */
  2339. Vector2.prototype.divideToRef = function (otherVector, result) {
  2340. result.x = this.x / otherVector.x;
  2341. result.y = this.y / otherVector.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Divides the current Vector3 coordinates by the passed ones.
  2346. * Returns the updated Vector3.
  2347. */
  2348. Vector2.prototype.divideInPlace = function (otherVector) {
  2349. return this.divideToRef(otherVector, this);
  2350. };
  2351. /**
  2352. * Returns a new Vector2 with current Vector2 negated coordinates.
  2353. */
  2354. Vector2.prototype.negate = function () {
  2355. return new Vector2(-this.x, -this.y);
  2356. };
  2357. /**
  2358. * Multiply the Vector2 coordinates by scale.
  2359. * Returns the updated Vector2.
  2360. */
  2361. Vector2.prototype.scaleInPlace = function (scale) {
  2362. this.x *= scale;
  2363. this.y *= scale;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2368. */
  2369. Vector2.prototype.scale = function (scale) {
  2370. var result = new Vector2(0, 0);
  2371. this.scaleToRef(scale, result);
  2372. return result;
  2373. };
  2374. /**
  2375. * Scale the current Vector2 values by a factor to a given Vector2
  2376. * @param scale defines the scale factor
  2377. * @param result defines the Vector2 object where to store the result
  2378. * @returns the unmodified current Vector2
  2379. */
  2380. Vector2.prototype.scaleToRef = function (scale, result) {
  2381. result.x = this.x * scale;
  2382. result.y = this.y * scale;
  2383. return this;
  2384. };
  2385. /**
  2386. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2387. * @param scale defines the scale factor
  2388. * @param result defines the Vector2 object where to store the result
  2389. * @returns the unmodified current Vector2
  2390. */
  2391. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2392. result.x += this.x * scale;
  2393. result.y += this.y * scale;
  2394. return this;
  2395. };
  2396. /**
  2397. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2398. */
  2399. Vector2.prototype.equals = function (otherVector) {
  2400. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2401. };
  2402. /**
  2403. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2404. */
  2405. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2406. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2407. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2408. };
  2409. // Properties
  2410. /**
  2411. * Returns the vector length (float).
  2412. */
  2413. Vector2.prototype.length = function () {
  2414. return Math.sqrt(this.x * this.x + this.y * this.y);
  2415. };
  2416. /**
  2417. * Returns the vector squared length (float);
  2418. */
  2419. Vector2.prototype.lengthSquared = function () {
  2420. return (this.x * this.x + this.y * this.y);
  2421. };
  2422. // Methods
  2423. /**
  2424. * Normalize the vector.
  2425. * Returns the updated Vector2.
  2426. */
  2427. Vector2.prototype.normalize = function () {
  2428. var len = this.length();
  2429. if (len === 0)
  2430. return this;
  2431. var num = 1.0 / len;
  2432. this.x *= num;
  2433. this.y *= num;
  2434. return this;
  2435. };
  2436. /**
  2437. * Returns a new Vector2 copied from the Vector2.
  2438. */
  2439. Vector2.prototype.clone = function () {
  2440. return new Vector2(this.x, this.y);
  2441. };
  2442. // Statics
  2443. /**
  2444. * Returns a new Vector2(0, 0)
  2445. */
  2446. Vector2.Zero = function () {
  2447. return new Vector2(0, 0);
  2448. };
  2449. /**
  2450. * Returns a new Vector2(1, 1)
  2451. */
  2452. Vector2.One = function () {
  2453. return new Vector2(1, 1);
  2454. };
  2455. /**
  2456. * Returns a new Vector2 set from the passed index element of the passed array.
  2457. */
  2458. Vector2.FromArray = function (array, offset) {
  2459. if (offset === void 0) { offset = 0; }
  2460. return new Vector2(array[offset], array[offset + 1]);
  2461. };
  2462. /**
  2463. * Sets "result" from the passed index element of the passed array.
  2464. */
  2465. Vector2.FromArrayToRef = function (array, offset, result) {
  2466. result.x = array[offset];
  2467. result.y = array[offset + 1];
  2468. };
  2469. /**
  2470. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2471. */
  2472. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2473. var squared = amount * amount;
  2474. var cubed = amount * squared;
  2475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2481. return new Vector2(x, y);
  2482. };
  2483. /**
  2484. * 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".
  2485. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2486. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2487. */
  2488. Vector2.Clamp = function (value, min, max) {
  2489. var x = value.x;
  2490. x = (x > max.x) ? max.x : x;
  2491. x = (x < min.x) ? min.x : x;
  2492. var y = value.y;
  2493. y = (y > max.y) ? max.y : y;
  2494. y = (y < min.y) ? min.y : y;
  2495. return new Vector2(x, y);
  2496. };
  2497. /**
  2498. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2499. */
  2500. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2501. var squared = amount * amount;
  2502. var cubed = amount * squared;
  2503. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2504. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2505. var part3 = (cubed - (2.0 * squared)) + amount;
  2506. var part4 = cubed - squared;
  2507. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2508. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2509. return new Vector2(x, y);
  2510. };
  2511. /**
  2512. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2513. */
  2514. Vector2.Lerp = function (start, end, amount) {
  2515. var x = start.x + ((end.x - start.x) * amount);
  2516. var y = start.y + ((end.y - start.y) * amount);
  2517. return new Vector2(x, y);
  2518. };
  2519. /**
  2520. * Returns the dot product (float) of the vector "left" and the vector "right".
  2521. */
  2522. Vector2.Dot = function (left, right) {
  2523. return left.x * right.x + left.y * right.y;
  2524. };
  2525. /**
  2526. * Returns a new Vector2 equal to the normalized passed vector.
  2527. */
  2528. Vector2.Normalize = function (vector) {
  2529. var newVector = vector.clone();
  2530. newVector.normalize();
  2531. return newVector;
  2532. };
  2533. /**
  2534. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2535. */
  2536. Vector2.Minimize = function (left, right) {
  2537. var x = (left.x < right.x) ? left.x : right.x;
  2538. var y = (left.y < right.y) ? left.y : right.y;
  2539. return new Vector2(x, y);
  2540. };
  2541. /**
  2542. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2543. */
  2544. Vector2.Maximize = function (left, right) {
  2545. var x = (left.x > right.x) ? left.x : right.x;
  2546. var y = (left.y > right.y) ? left.y : right.y;
  2547. return new Vector2(x, y);
  2548. };
  2549. /**
  2550. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2551. */
  2552. Vector2.Transform = function (vector, transformation) {
  2553. var r = Vector2.Zero();
  2554. Vector2.TransformToRef(vector, transformation, r);
  2555. return r;
  2556. };
  2557. /**
  2558. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2559. */
  2560. Vector2.TransformToRef = function (vector, transformation, result) {
  2561. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2562. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2563. result.x = x;
  2564. result.y = y;
  2565. };
  2566. /**
  2567. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2568. */
  2569. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2570. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2571. var sign = a < 0 ? -1 : 1;
  2572. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2573. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2574. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2575. };
  2576. /**
  2577. * Returns the distance (float) between the vectors "value1" and "value2".
  2578. */
  2579. Vector2.Distance = function (value1, value2) {
  2580. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2581. };
  2582. /**
  2583. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2584. */
  2585. Vector2.DistanceSquared = function (value1, value2) {
  2586. var x = value1.x - value2.x;
  2587. var y = value1.y - value2.y;
  2588. return (x * x) + (y * y);
  2589. };
  2590. /**
  2591. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2592. */
  2593. Vector2.Center = function (value1, value2) {
  2594. var center = value1.add(value2);
  2595. center.scaleInPlace(0.5);
  2596. return center;
  2597. };
  2598. /**
  2599. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2600. */
  2601. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2602. var l2 = Vector2.DistanceSquared(segA, segB);
  2603. if (l2 === 0.0) {
  2604. return Vector2.Distance(p, segA);
  2605. }
  2606. var v = segB.subtract(segA);
  2607. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2608. var proj = segA.add(v.multiplyByFloats(t, t));
  2609. return Vector2.Distance(p, proj);
  2610. };
  2611. return Vector2;
  2612. }());
  2613. BABYLON.Vector2 = Vector2;
  2614. /**
  2615. * Classed used to store (x,y,z) vector representation
  2616. * A Vector3 is the main object used in 3D geometry
  2617. * It can represent etiher the coordinates of a point the space, either a direction
  2618. * Reminder: Babylon.js uses a left handed forward facing system
  2619. */
  2620. var Vector3 = /** @class */ (function () {
  2621. /**
  2622. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2623. * @param x defines the first coordinates (on X axis)
  2624. * @param y defines the second coordinates (on Y axis)
  2625. * @param z defines the third coordinates (on Z axis)
  2626. */
  2627. function Vector3(
  2628. /**
  2629. * Defines the first coordinates (on X axis)
  2630. */
  2631. x,
  2632. /**
  2633. * Defines the second coordinates (on Y axis)
  2634. */
  2635. y,
  2636. /**
  2637. * Defines the third coordinates (on Z axis)
  2638. */
  2639. z) {
  2640. this.x = x;
  2641. this.y = y;
  2642. this.z = z;
  2643. }
  2644. /**
  2645. * Creates a string representation of the Vector3
  2646. * @returns a string with the Vector3 coordinates.
  2647. */
  2648. Vector3.prototype.toString = function () {
  2649. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2650. };
  2651. /**
  2652. * Gets the class name
  2653. * @returns the string "Vector3"
  2654. */
  2655. Vector3.prototype.getClassName = function () {
  2656. return "Vector3";
  2657. };
  2658. /**
  2659. * Creates the Vector3 hash code
  2660. * @returns a number which tends to be unique between Vector3 instances
  2661. */
  2662. Vector3.prototype.getHashCode = function () {
  2663. var hash = this.x || 0;
  2664. hash = (hash * 397) ^ (this.y || 0);
  2665. hash = (hash * 397) ^ (this.z || 0);
  2666. return hash;
  2667. };
  2668. // Operators
  2669. /**
  2670. * Creates an array containing three elements : the coordinates of the Vector3
  2671. * @returns a new array of numbers
  2672. */
  2673. Vector3.prototype.asArray = function () {
  2674. var result = [];
  2675. this.toArray(result, 0);
  2676. return result;
  2677. };
  2678. /**
  2679. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2680. * @param array defines the destination array
  2681. * @param index defines the offset in the destination array
  2682. * @returns the current Vector3
  2683. */
  2684. Vector3.prototype.toArray = function (array, index) {
  2685. if (index === void 0) { index = 0; }
  2686. array[index] = this.x;
  2687. array[index + 1] = this.y;
  2688. array[index + 2] = this.z;
  2689. return this;
  2690. };
  2691. /**
  2692. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2693. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2694. */
  2695. Vector3.prototype.toQuaternion = function () {
  2696. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2697. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2698. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2699. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2700. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2701. var cosy = Math.cos(this.y * 0.5);
  2702. var siny = Math.sin(this.y * 0.5);
  2703. result.x = coszMinusx * siny;
  2704. result.y = -sinzMinusx * siny;
  2705. result.z = sinxPlusz * cosy;
  2706. result.w = cosxPlusz * cosy;
  2707. return result;
  2708. };
  2709. /**
  2710. * Adds the passed vector to the current Vector3
  2711. * @param otherVector defines the second operand
  2712. * @returns the current updated Vector3
  2713. */
  2714. Vector3.prototype.addInPlace = function (otherVector) {
  2715. this.x += otherVector.x;
  2716. this.y += otherVector.y;
  2717. this.z += otherVector.z;
  2718. return this;
  2719. };
  2720. /**
  2721. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2722. * @param otherVector defines the second operand
  2723. * @returns the resulting Vector3
  2724. */
  2725. Vector3.prototype.add = function (otherVector) {
  2726. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2727. };
  2728. /**
  2729. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2730. * @param otherVector defines the second operand
  2731. * @param result defines the Vector3 object where to store the result
  2732. * @returns the current Vector3
  2733. */
  2734. Vector3.prototype.addToRef = function (otherVector, result) {
  2735. result.x = this.x + otherVector.x;
  2736. result.y = this.y + otherVector.y;
  2737. result.z = this.z + otherVector.z;
  2738. return this;
  2739. };
  2740. /**
  2741. * Subtract the passed vector from the current Vector3
  2742. * @param otherVector defines the second operand
  2743. * @returns the current updated Vector3
  2744. */
  2745. Vector3.prototype.subtractInPlace = function (otherVector) {
  2746. this.x -= otherVector.x;
  2747. this.y -= otherVector.y;
  2748. this.z -= otherVector.z;
  2749. return this;
  2750. };
  2751. /**
  2752. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2753. * @param otherVector defines the second operand
  2754. * @returns the resulting Vector3
  2755. */
  2756. Vector3.prototype.subtract = function (otherVector) {
  2757. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2758. };
  2759. /**
  2760. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2761. * @param otherVector defines the second operand
  2762. * @param result defines the Vector3 object where to store the result
  2763. * @returns the current Vector3
  2764. */
  2765. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2766. result.x = this.x - otherVector.x;
  2767. result.y = this.y - otherVector.y;
  2768. result.z = this.z - otherVector.z;
  2769. return this;
  2770. };
  2771. /**
  2772. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2773. * @param x defines the x coordinate of the operand
  2774. * @param y defines the y coordinate of the operand
  2775. * @param z defines the z coordinate of the operand
  2776. * @returns the resulting Vector3
  2777. */
  2778. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2779. return new Vector3(this.x - x, this.y - y, this.z - z);
  2780. };
  2781. /**
  2782. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2783. * @param x defines the x coordinate of the operand
  2784. * @param y defines the y coordinate of the operand
  2785. * @param z defines the z coordinate of the operand
  2786. * @param result defines the Vector3 object where to store the result
  2787. * @returns the current Vector3
  2788. */
  2789. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2790. result.x = this.x - x;
  2791. result.y = this.y - y;
  2792. result.z = this.z - z;
  2793. return this;
  2794. };
  2795. /**
  2796. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2797. * @returns a new Vector3
  2798. */
  2799. Vector3.prototype.negate = function () {
  2800. return new Vector3(-this.x, -this.y, -this.z);
  2801. };
  2802. /**
  2803. * Multiplies the Vector3 coordinates by the float "scale"
  2804. * @param scale defines the multiplier factor
  2805. * @returns the current updated Vector3
  2806. */
  2807. Vector3.prototype.scaleInPlace = function (scale) {
  2808. this.x *= scale;
  2809. this.y *= scale;
  2810. this.z *= scale;
  2811. return this;
  2812. };
  2813. /**
  2814. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2815. * @param scale defines the multiplier factor
  2816. * @returns a new Vector3
  2817. */
  2818. Vector3.prototype.scale = function (scale) {
  2819. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2820. };
  2821. /**
  2822. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2823. * @param scale defines the multiplier factor
  2824. * @param result defines the Vector3 object where to store the result
  2825. * @returns the current Vector3
  2826. */
  2827. Vector3.prototype.scaleToRef = function (scale, result) {
  2828. result.x = this.x * scale;
  2829. result.y = this.y * scale;
  2830. result.z = this.z * scale;
  2831. return this;
  2832. };
  2833. /**
  2834. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2835. * @param scale defines the scale factor
  2836. * @param result defines the Vector3 object where to store the result
  2837. * @returns the unmodified current Vector3
  2838. */
  2839. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2840. result.x += this.x * scale;
  2841. result.y += this.y * scale;
  2842. result.z += this.z * scale;
  2843. return this;
  2844. };
  2845. /**
  2846. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2847. * @param otherVector defines the second operand
  2848. * @returns true if both vectors are equals
  2849. */
  2850. Vector3.prototype.equals = function (otherVector) {
  2851. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2852. };
  2853. /**
  2854. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2855. * @param otherVector defines the second operand
  2856. * @param epsilon defines the minimal distance to define values as equals
  2857. * @returns true if both vectors are distant less than epsilon
  2858. */
  2859. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2860. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2861. 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);
  2862. };
  2863. /**
  2864. * Returns true if the current Vector3 coordinates equals the passed floats
  2865. * @param x defines the x coordinate of the operand
  2866. * @param y defines the y coordinate of the operand
  2867. * @param z defines the z coordinate of the operand
  2868. * @returns true if both vectors are equals
  2869. */
  2870. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2871. return this.x === x && this.y === y && this.z === z;
  2872. };
  2873. /**
  2874. * Multiplies the current Vector3 coordinates by the passed ones
  2875. * @param otherVector defines the second operand
  2876. * @returns the current updated Vector3
  2877. */
  2878. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2879. this.x *= otherVector.x;
  2880. this.y *= otherVector.y;
  2881. this.z *= otherVector.z;
  2882. return this;
  2883. };
  2884. /**
  2885. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2886. * @param otherVector defines the second operand
  2887. * @returns the new Vector3
  2888. */
  2889. Vector3.prototype.multiply = function (otherVector) {
  2890. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2891. };
  2892. /**
  2893. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2894. * @param otherVector defines the second operand
  2895. * @param result defines the Vector3 object where to store the result
  2896. * @returns the current Vector3
  2897. */
  2898. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2899. result.x = this.x * otherVector.x;
  2900. result.y = this.y * otherVector.y;
  2901. result.z = this.z * otherVector.z;
  2902. return this;
  2903. };
  2904. /**
  2905. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2906. * @param x defines the x coordinate of the operand
  2907. * @param y defines the y coordinate of the operand
  2908. * @param z defines the z coordinate of the operand
  2909. * @returns the new Vector3
  2910. */
  2911. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2912. return new Vector3(this.x * x, this.y * y, this.z * z);
  2913. };
  2914. /**
  2915. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2916. * @param otherVector defines the second operand
  2917. * @returns the new Vector3
  2918. */
  2919. Vector3.prototype.divide = function (otherVector) {
  2920. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2921. };
  2922. /**
  2923. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2924. * @param otherVector defines the second operand
  2925. * @param result defines the Vector3 object where to store the result
  2926. * @returns the current Vector3
  2927. */
  2928. Vector3.prototype.divideToRef = function (otherVector, result) {
  2929. result.x = this.x / otherVector.x;
  2930. result.y = this.y / otherVector.y;
  2931. result.z = this.z / otherVector.z;
  2932. return this;
  2933. };
  2934. /**
  2935. * Divides the current Vector3 coordinates by the passed ones.
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.divideInPlace = function (otherVector) {
  2940. return this.divideToRef(otherVector, this);
  2941. };
  2942. /**
  2943. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2944. * @param other defines the second operand
  2945. * @returns the current updated Vector3
  2946. */
  2947. Vector3.prototype.minimizeInPlace = function (other) {
  2948. if (other.x < this.x)
  2949. this.x = other.x;
  2950. if (other.y < this.y)
  2951. this.y = other.y;
  2952. if (other.z < this.z)
  2953. this.z = other.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2958. * @param other defines the second operand
  2959. * @returns the current updated Vector3
  2960. */
  2961. Vector3.prototype.maximizeInPlace = function (other) {
  2962. if (other.x > this.x)
  2963. this.x = other.x;
  2964. if (other.y > this.y)
  2965. this.y = other.y;
  2966. if (other.z > this.z)
  2967. this.z = other.z;
  2968. return this;
  2969. };
  2970. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2971. /**
  2972. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2973. */
  2974. get: function () {
  2975. var absX = Math.abs(this.x);
  2976. var absY = Math.abs(this.y);
  2977. if (absX !== absY) {
  2978. return true;
  2979. }
  2980. var absZ = Math.abs(this.z);
  2981. if (absX !== absZ) {
  2982. return true;
  2983. }
  2984. if (absY !== absZ) {
  2985. return true;
  2986. }
  2987. return false;
  2988. },
  2989. enumerable: true,
  2990. configurable: true
  2991. });
  2992. // Properties
  2993. /**
  2994. * Gets the length of the Vector3
  2995. * @returns the length of the Vecto3
  2996. */
  2997. Vector3.prototype.length = function () {
  2998. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2999. };
  3000. /**
  3001. * Gets the squared length of the Vector3
  3002. * @returns squared length of the Vector3
  3003. */
  3004. Vector3.prototype.lengthSquared = function () {
  3005. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3006. };
  3007. /**
  3008. * Normalize the current Vector3.
  3009. * Please note that this is an in place operation.
  3010. * @returns the current updated Vector3
  3011. */
  3012. Vector3.prototype.normalize = function () {
  3013. var len = this.length();
  3014. if (len === 0 || len === 1.0)
  3015. return this;
  3016. var num = 1.0 / len;
  3017. this.x *= num;
  3018. this.y *= num;
  3019. this.z *= num;
  3020. return this;
  3021. };
  3022. /**
  3023. * Normalize the current Vector3 to a new vector
  3024. * @returns the new Vector3
  3025. */
  3026. Vector3.prototype.normalizeToNew = function () {
  3027. var normalized = new Vector3(0, 0, 0);
  3028. this.normalizeToRef(normalized);
  3029. return normalized;
  3030. };
  3031. /**
  3032. * Normalize the current Vector3 to the reference
  3033. * @param reference define the Vector3 to update
  3034. * @returns the updated Vector3
  3035. */
  3036. Vector3.prototype.normalizeToRef = function (reference) {
  3037. var len = this.length();
  3038. if (len === 0 || len === 1.0) {
  3039. reference.set(this.x, this.y, this.z);
  3040. return reference;
  3041. }
  3042. var scale = 1.0 / len;
  3043. this.scaleToRef(scale, reference);
  3044. return reference;
  3045. };
  3046. /**
  3047. * Creates a new Vector3 copied from the current Vector3
  3048. * @returns the new Vector3
  3049. */
  3050. Vector3.prototype.clone = function () {
  3051. return new Vector3(this.x, this.y, this.z);
  3052. };
  3053. /**
  3054. * Copies the passed vector coordinates to the current Vector3 ones
  3055. * @param source defines the source Vector3
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.copyFrom = function (source) {
  3059. this.x = source.x;
  3060. this.y = source.y;
  3061. this.z = source.z;
  3062. return this;
  3063. };
  3064. /**
  3065. * Copies the passed floats to the current Vector3 coordinates
  3066. * @param x defines the x coordinate of the operand
  3067. * @param y defines the y coordinate of the operand
  3068. * @param z defines the z coordinate of the operand
  3069. * @returns the current updated Vector3
  3070. */
  3071. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3072. this.x = x;
  3073. this.y = y;
  3074. this.z = z;
  3075. return this;
  3076. };
  3077. /**
  3078. * Copies the passed floats to the current Vector3 coordinates
  3079. * @param x defines the x coordinate of the operand
  3080. * @param y defines the y coordinate of the operand
  3081. * @param z defines the z coordinate of the operand
  3082. * @returns the current updated Vector3
  3083. */
  3084. Vector3.prototype.set = function (x, y, z) {
  3085. return this.copyFromFloats(x, y, z);
  3086. };
  3087. // Statics
  3088. /**
  3089. * Get the clip factor between two vectors
  3090. * @param vector0 defines the first operand
  3091. * @param vector1 defines the second operand
  3092. * @param axis defines the axis to use
  3093. * @param size defines the size along the axis
  3094. * @returns the clip factor
  3095. */
  3096. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3097. var d0 = Vector3.Dot(vector0, axis) - size;
  3098. var d1 = Vector3.Dot(vector1, axis) - size;
  3099. var s = d0 / (d0 - d1);
  3100. return s;
  3101. };
  3102. /**
  3103. * Get angle between two vectors
  3104. * @param vector0 angle between vector0 and vector1
  3105. * @param vector1 angle between vector0 and vector1
  3106. * @param normal direction of the normal
  3107. * @return the angle between vector0 and vector1
  3108. */
  3109. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3110. var v0 = vector0.clone().normalize();
  3111. var v1 = vector1.clone().normalize();
  3112. var dot = Vector3.Dot(v0, v1);
  3113. var n = Vector3.Cross(v0, v1);
  3114. if (Vector3.Dot(n, normal) > 0) {
  3115. return Math.acos(dot);
  3116. }
  3117. return -Math.acos(dot);
  3118. };
  3119. /**
  3120. * Returns a new Vector3 set from the index "offset" of the passed array
  3121. * @param array defines the source array
  3122. * @param offset defines the offset in the source array
  3123. * @returns the new Vector3
  3124. */
  3125. Vector3.FromArray = function (array, offset) {
  3126. if (!offset) {
  3127. offset = 0;
  3128. }
  3129. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3130. };
  3131. /**
  3132. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3133. * This function is deprecated. Use FromArray instead
  3134. * @param array defines the source array
  3135. * @param offset defines the offset in the source array
  3136. * @returns the new Vector3
  3137. */
  3138. Vector3.FromFloatArray = function (array, offset) {
  3139. return Vector3.FromArray(array, offset);
  3140. };
  3141. /**
  3142. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3143. * @param array defines the source array
  3144. * @param offset defines the offset in the source array
  3145. * @param result defines the Vector3 where to store the result
  3146. */
  3147. Vector3.FromArrayToRef = function (array, offset, result) {
  3148. result.x = array[offset];
  3149. result.y = array[offset + 1];
  3150. result.z = array[offset + 2];
  3151. };
  3152. /**
  3153. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3154. * This function is deprecated. Use FromArrayToRef instead.
  3155. * @param array defines the source array
  3156. * @param offset defines the offset in the source array
  3157. * @param result defines the Vector3 where to store the result
  3158. */
  3159. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3160. return Vector3.FromArrayToRef(array, offset, result);
  3161. };
  3162. /**
  3163. * Sets the passed vector "result" with the passed floats.
  3164. * @param x defines the x coordinate of the source
  3165. * @param y defines the y coordinate of the source
  3166. * @param z defines the z coordinate of the source
  3167. * @param result defines the Vector3 where to store the result
  3168. */
  3169. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3170. result.x = x;
  3171. result.y = y;
  3172. result.z = z;
  3173. };
  3174. /**
  3175. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3176. * @returns a new empty Vector3
  3177. */
  3178. Vector3.Zero = function () {
  3179. return new Vector3(0.0, 0.0, 0.0);
  3180. };
  3181. /**
  3182. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3183. * @returns a new unit Vector3
  3184. */
  3185. Vector3.One = function () {
  3186. return new Vector3(1.0, 1.0, 1.0);
  3187. };
  3188. /**
  3189. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3190. * @returns a new up Vector3
  3191. */
  3192. Vector3.Up = function () {
  3193. return new Vector3(0.0, 1.0, 0.0);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3197. * @returns a new forward Vector3
  3198. */
  3199. Vector3.Forward = function () {
  3200. return new Vector3(0.0, 0.0, 1.0);
  3201. };
  3202. /**
  3203. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3204. * @returns a new right Vector3
  3205. */
  3206. Vector3.Right = function () {
  3207. return new Vector3(1.0, 0.0, 0.0);
  3208. };
  3209. /**
  3210. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3211. * @returns a new left Vector3
  3212. */
  3213. Vector3.Left = function () {
  3214. return new Vector3(-1.0, 0.0, 0.0);
  3215. };
  3216. /**
  3217. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3218. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3219. * @param vector defines the Vector3 to transform
  3220. * @param transformation defines the transformation matrix
  3221. * @returns the transformed Vector3
  3222. */
  3223. Vector3.TransformCoordinates = function (vector, transformation) {
  3224. var result = Vector3.Zero();
  3225. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3226. return result;
  3227. };
  3228. /**
  3229. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3230. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3231. * @param vector defines the Vector3 to transform
  3232. * @param transformation defines the transformation matrix
  3233. * @param result defines the Vector3 where to store the result
  3234. */
  3235. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3236. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3237. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3238. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3239. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3240. result.x = x / w;
  3241. result.y = y / w;
  3242. result.z = z / w;
  3243. };
  3244. /**
  3245. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3246. * This method computes tranformed coordinates only, not transformed direction vectors
  3247. * @param x define the x coordinate of the source vector
  3248. * @param y define the y coordinate of the source vector
  3249. * @param z define the z coordinate of the source vector
  3250. * @param transformation defines the transformation matrix
  3251. * @param result defines the Vector3 where to store the result
  3252. */
  3253. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3254. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3255. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3256. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3257. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3258. result.x = rx / rw;
  3259. result.y = ry / rw;
  3260. result.z = rz / rw;
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3264. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3265. * @param vector defines the Vector3 to transform
  3266. * @param transformation defines the transformation matrix
  3267. * @returns the new Vector3
  3268. */
  3269. Vector3.TransformNormal = function (vector, transformation) {
  3270. var result = Vector3.Zero();
  3271. Vector3.TransformNormalToRef(vector, transformation, result);
  3272. return result;
  3273. };
  3274. /**
  3275. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3276. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3277. * @param vector defines the Vector3 to transform
  3278. * @param transformation defines the transformation matrix
  3279. * @param result defines the Vector3 where to store the result
  3280. */
  3281. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3282. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3283. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3284. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3285. result.x = x;
  3286. result.y = y;
  3287. result.z = z;
  3288. };
  3289. /**
  3290. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3291. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3292. * @param x define the x coordinate of the source vector
  3293. * @param y define the y coordinate of the source vector
  3294. * @param z define the z coordinate of the source vector
  3295. * @param transformation defines the transformation matrix
  3296. * @param result defines the Vector3 where to store the result
  3297. */
  3298. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3299. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3300. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3301. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3302. };
  3303. /**
  3304. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3305. * @param value1 defines the first control point
  3306. * @param value2 defines the second control point
  3307. * @param value3 defines the third control point
  3308. * @param value4 defines the fourth control point
  3309. * @param amount defines the amount on the spline to use
  3310. * @returns the new Vector3
  3311. */
  3312. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3313. var squared = amount * amount;
  3314. var cubed = amount * squared;
  3315. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3316. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3317. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3318. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3319. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3320. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3321. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3322. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3323. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3324. return new Vector3(x, y, z);
  3325. };
  3326. /**
  3327. * 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"
  3328. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3329. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3330. * @param value defines the current value
  3331. * @param min defines the lower range value
  3332. * @param max defines the upper range value
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.Clamp = function (value, min, max) {
  3336. var x = value.x;
  3337. x = (x > max.x) ? max.x : x;
  3338. x = (x < min.x) ? min.x : x;
  3339. var y = value.y;
  3340. y = (y > max.y) ? max.y : y;
  3341. y = (y < min.y) ? min.y : y;
  3342. var z = value.z;
  3343. z = (z > max.z) ? max.z : z;
  3344. z = (z < min.z) ? min.z : z;
  3345. return new Vector3(x, y, z);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3349. * @param value1 defines the first control point
  3350. * @param tangent1 defines the first tangent vector
  3351. * @param value2 defines the second control point
  3352. * @param tangent2 defines the second tangent vector
  3353. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3354. * @returns the new Vector3
  3355. */
  3356. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3357. var squared = amount * amount;
  3358. var cubed = amount * squared;
  3359. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3360. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3361. var part3 = (cubed - (2.0 * squared)) + amount;
  3362. var part4 = cubed - squared;
  3363. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3364. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3365. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3366. return new Vector3(x, y, z);
  3367. };
  3368. /**
  3369. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3370. * @param start defines the start value
  3371. * @param end defines the end value
  3372. * @param amount max defines amount between both (between 0 and 1)
  3373. * @returns the new Vector3
  3374. */
  3375. Vector3.Lerp = function (start, end, amount) {
  3376. var result = new Vector3(0, 0, 0);
  3377. Vector3.LerpToRef(start, end, amount, result);
  3378. return result;
  3379. };
  3380. /**
  3381. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3382. * @param start defines the start value
  3383. * @param end defines the end value
  3384. * @param amount max defines amount between both (between 0 and 1)
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.LerpToRef = function (start, end, amount, result) {
  3388. result.x = start.x + ((end.x - start.x) * amount);
  3389. result.y = start.y + ((end.y - start.y) * amount);
  3390. result.z = start.z + ((end.z - start.z) * amount);
  3391. };
  3392. /**
  3393. * Returns the dot product (float) between the vectors "left" and "right"
  3394. * @param left defines the left operand
  3395. * @param right defines the right operand
  3396. * @returns the dot product
  3397. */
  3398. Vector3.Dot = function (left, right) {
  3399. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3403. * The cross product is then orthogonal to both "left" and "right"
  3404. * @param left defines the left operand
  3405. * @param right defines the right operand
  3406. * @returns the cross product
  3407. */
  3408. Vector3.Cross = function (left, right) {
  3409. var result = Vector3.Zero();
  3410. Vector3.CrossToRef(left, right, result);
  3411. return result;
  3412. };
  3413. /**
  3414. * Sets the passed vector "result" with the cross product of "left" and "right"
  3415. * The cross product is then orthogonal to both "left" and "right"
  3416. * @param left defines the left operand
  3417. * @param right defines the right operand
  3418. * @param result defines the Vector3 where to store the result
  3419. */
  3420. Vector3.CrossToRef = function (left, right, result) {
  3421. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3422. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3423. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3424. result.copyFrom(MathTmp.Vector3[0]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 as the normalization of the passed vector
  3428. * @param vector defines the Vector3 to normalize
  3429. * @returns the new Vector3
  3430. */
  3431. Vector3.Normalize = function (vector) {
  3432. var result = Vector3.Zero();
  3433. Vector3.NormalizeToRef(vector, result);
  3434. return result;
  3435. };
  3436. /**
  3437. * Sets the passed vector "result" with the normalization of the passed first vector
  3438. * @param vector defines the Vector3 to normalize
  3439. * @param result defines the Vector3 where to store the result
  3440. */
  3441. Vector3.NormalizeToRef = function (vector, result) {
  3442. result.copyFrom(vector);
  3443. result.normalize();
  3444. };
  3445. /**
  3446. * Project a Vector3 onto screen space
  3447. * @param vector defines the Vector3 to project
  3448. * @param world defines the world matrix to use
  3449. * @param transform defines the transform (view x projection) matrix to use
  3450. * @param viewport defines the screen viewport to use
  3451. * @returns the new Vector3
  3452. */
  3453. Vector3.Project = function (vector, world, transform, viewport) {
  3454. var cw = viewport.width;
  3455. var ch = viewport.height;
  3456. var cx = viewport.x;
  3457. var cy = viewport.y;
  3458. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3459. 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);
  3460. var matrix = MathTmp.Matrix[0];
  3461. world.multiplyToRef(transform, matrix);
  3462. matrix.multiplyToRef(viewportMatrix, matrix);
  3463. return Vector3.TransformCoordinates(vector, matrix);
  3464. };
  3465. /**
  3466. * Unproject from screen space to object space
  3467. * @param source defines the screen space Vector3 to use
  3468. * @param viewportWidth defines the current width of the viewport
  3469. * @param viewportHeight defines the current height of the viewport
  3470. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3471. * @param transform defines the transform (view x projection) matrix to use
  3472. * @returns the new Vector3
  3473. */
  3474. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3475. var matrix = MathTmp.Matrix[0];
  3476. world.multiplyToRef(transform, matrix);
  3477. matrix.invert();
  3478. source.x = source.x / viewportWidth * 2 - 1;
  3479. source.y = -(source.y / viewportHeight * 2 - 1);
  3480. var vector = Vector3.TransformCoordinates(source, matrix);
  3481. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3482. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3483. vector = vector.scale(1.0 / num);
  3484. }
  3485. return vector;
  3486. };
  3487. /**
  3488. * Unproject from screen space to object space
  3489. * @param source defines the screen space Vector3 to use
  3490. * @param viewportWidth defines the current width of the viewport
  3491. * @param viewportHeight defines the current height of the viewport
  3492. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3493. * @param view defines the view matrix to use
  3494. * @param projection defines the projection matrix to use
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3498. var result = Vector3.Zero();
  3499. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3500. return result;
  3501. };
  3502. /**
  3503. * Unproject from screen space to object space
  3504. * @param source defines the screen space Vector3 to use
  3505. * @param viewportWidth defines the current width of the viewport
  3506. * @param viewportHeight defines the current height of the viewport
  3507. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3508. * @param view defines the view matrix to use
  3509. * @param projection defines the projection matrix to use
  3510. * @param result defines the Vector3 where to store the result
  3511. */
  3512. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3513. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3514. };
  3515. /**
  3516. * Unproject from screen space to object space
  3517. * @param sourceX defines the screen space x coordinate to use
  3518. * @param sourceY defines the screen space y coordinate to use
  3519. * @param sourceZ defines the screen space z coordinate to use
  3520. * @param viewportWidth defines the current width of the viewport
  3521. * @param viewportHeight defines the current height of the viewport
  3522. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3523. * @param view defines the view matrix to use
  3524. * @param projection defines the projection matrix to use
  3525. * @param result defines the Vector3 where to store the result
  3526. */
  3527. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3528. var matrix = MathTmp.Matrix[0];
  3529. world.multiplyToRef(view, matrix);
  3530. matrix.multiplyToRef(projection, matrix);
  3531. matrix.invert();
  3532. var screenSource = MathTmp.Vector3[0];
  3533. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3534. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3535. screenSource.z = 2 * sourceZ - 1.0;
  3536. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3537. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3538. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3539. result.scaleInPlace(1.0 / num);
  3540. }
  3541. };
  3542. /**
  3543. * Gets the minimal coordinate values between two Vector3
  3544. * @param left defines the first operand
  3545. * @param right defines the second operand
  3546. * @returns the new Vector3
  3547. */
  3548. Vector3.Minimize = function (left, right) {
  3549. var min = left.clone();
  3550. min.minimizeInPlace(right);
  3551. return min;
  3552. };
  3553. /**
  3554. * Gets the maximal coordinate values between two Vector3
  3555. * @param left defines the first operand
  3556. * @param right defines the second operand
  3557. * @returns the new Vector3
  3558. */
  3559. Vector3.Maximize = function (left, right) {
  3560. var max = left.clone();
  3561. max.maximizeInPlace(right);
  3562. return max;
  3563. };
  3564. /**
  3565. * Returns the distance between the vectors "value1" and "value2"
  3566. * @param value1 defines the first operand
  3567. * @param value2 defines the second operand
  3568. * @returns the distance
  3569. */
  3570. Vector3.Distance = function (value1, value2) {
  3571. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3572. };
  3573. /**
  3574. * Returns the squared distance between the vectors "value1" and "value2"
  3575. * @param value1 defines the first operand
  3576. * @param value2 defines the second operand
  3577. * @returns the squared distance
  3578. */
  3579. Vector3.DistanceSquared = function (value1, value2) {
  3580. var x = value1.x - value2.x;
  3581. var y = value1.y - value2.y;
  3582. var z = value1.z - value2.z;
  3583. return (x * x) + (y * y) + (z * z);
  3584. };
  3585. /**
  3586. * Returns a new Vector3 located at the center between "value1" and "value2"
  3587. * @param value1 defines the first operand
  3588. * @param value2 defines the second operand
  3589. * @returns the new Vector3
  3590. */
  3591. Vector3.Center = function (value1, value2) {
  3592. var center = value1.add(value2);
  3593. center.scaleInPlace(0.5);
  3594. return center;
  3595. };
  3596. /**
  3597. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3598. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3599. * to something in order to rotate it from its local system to the given target system
  3600. * Note: axis1, axis2 and axis3 are normalized during this operation
  3601. * @param axis1 defines the first axis
  3602. * @param axis2 defines the second axis
  3603. * @param axis3 defines the third axis
  3604. * @returns a new Vector3
  3605. */
  3606. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3607. var rotation = Vector3.Zero();
  3608. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3609. return rotation;
  3610. };
  3611. /**
  3612. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3613. * @param axis1 defines the first axis
  3614. * @param axis2 defines the second axis
  3615. * @param axis3 defines the third axis
  3616. * @param ref defines the Vector3 where to store the result
  3617. */
  3618. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3619. var quat = MathTmp.Quaternion[0];
  3620. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3621. quat.toEulerAnglesToRef(ref);
  3622. };
  3623. return Vector3;
  3624. }());
  3625. BABYLON.Vector3 = Vector3;
  3626. //Vector4 class created for EulerAngle class conversion to Quaternion
  3627. var Vector4 = /** @class */ (function () {
  3628. /**
  3629. * Creates a Vector4 object from the passed floats.
  3630. */
  3631. function Vector4(x, y, z, w) {
  3632. this.x = x;
  3633. this.y = y;
  3634. this.z = z;
  3635. this.w = w;
  3636. }
  3637. /**
  3638. * Returns the string with the Vector4 coordinates.
  3639. */
  3640. Vector4.prototype.toString = function () {
  3641. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3642. };
  3643. /**
  3644. * Returns the string "Vector4".
  3645. */
  3646. Vector4.prototype.getClassName = function () {
  3647. return "Vector4";
  3648. };
  3649. /**
  3650. * Returns the Vector4 hash code.
  3651. */
  3652. Vector4.prototype.getHashCode = function () {
  3653. var hash = this.x || 0;
  3654. hash = (hash * 397) ^ (this.y || 0);
  3655. hash = (hash * 397) ^ (this.z || 0);
  3656. hash = (hash * 397) ^ (this.w || 0);
  3657. return hash;
  3658. };
  3659. // Operators
  3660. /**
  3661. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3662. */
  3663. Vector4.prototype.asArray = function () {
  3664. var result = new Array();
  3665. this.toArray(result, 0);
  3666. return result;
  3667. };
  3668. /**
  3669. * Populates the passed array from the passed index with the Vector4 coordinates.
  3670. * Returns the Vector4.
  3671. */
  3672. Vector4.prototype.toArray = function (array, index) {
  3673. if (index === undefined) {
  3674. index = 0;
  3675. }
  3676. array[index] = this.x;
  3677. array[index + 1] = this.y;
  3678. array[index + 2] = this.z;
  3679. array[index + 3] = this.w;
  3680. return this;
  3681. };
  3682. /**
  3683. * Adds the passed vector to the current Vector4.
  3684. * Returns the updated Vector4.
  3685. */
  3686. Vector4.prototype.addInPlace = function (otherVector) {
  3687. this.x += otherVector.x;
  3688. this.y += otherVector.y;
  3689. this.z += otherVector.z;
  3690. this.w += otherVector.w;
  3691. return this;
  3692. };
  3693. /**
  3694. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3695. */
  3696. Vector4.prototype.add = function (otherVector) {
  3697. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3698. };
  3699. /**
  3700. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3701. * Returns the current Vector4.
  3702. */
  3703. Vector4.prototype.addToRef = function (otherVector, result) {
  3704. result.x = this.x + otherVector.x;
  3705. result.y = this.y + otherVector.y;
  3706. result.z = this.z + otherVector.z;
  3707. result.w = this.w + otherVector.w;
  3708. return this;
  3709. };
  3710. /**
  3711. * Subtract in place the passed vector from the current Vector4.
  3712. * Returns the updated Vector4.
  3713. */
  3714. Vector4.prototype.subtractInPlace = function (otherVector) {
  3715. this.x -= otherVector.x;
  3716. this.y -= otherVector.y;
  3717. this.z -= otherVector.z;
  3718. this.w -= otherVector.w;
  3719. return this;
  3720. };
  3721. /**
  3722. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3723. */
  3724. Vector4.prototype.subtract = function (otherVector) {
  3725. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3726. };
  3727. /**
  3728. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3729. * Returns the current Vector4.
  3730. */
  3731. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3732. result.x = this.x - otherVector.x;
  3733. result.y = this.y - otherVector.y;
  3734. result.z = this.z - otherVector.z;
  3735. result.w = this.w - otherVector.w;
  3736. return this;
  3737. };
  3738. /**
  3739. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3740. */
  3741. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3742. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3743. };
  3744. /**
  3745. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3746. * Returns the current Vector4.
  3747. */
  3748. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3749. result.x = this.x - x;
  3750. result.y = this.y - y;
  3751. result.z = this.z - z;
  3752. result.w = this.w - w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3757. */
  3758. Vector4.prototype.negate = function () {
  3759. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3760. };
  3761. /**
  3762. * Multiplies the current Vector4 coordinates by scale (float).
  3763. * Returns the updated Vector4.
  3764. */
  3765. Vector4.prototype.scaleInPlace = function (scale) {
  3766. this.x *= scale;
  3767. this.y *= scale;
  3768. this.z *= scale;
  3769. this.w *= scale;
  3770. return this;
  3771. };
  3772. /**
  3773. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3774. */
  3775. Vector4.prototype.scale = function (scale) {
  3776. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3777. };
  3778. /**
  3779. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3780. * Returns the current Vector4.
  3781. */
  3782. Vector4.prototype.scaleToRef = function (scale, result) {
  3783. result.x = this.x * scale;
  3784. result.y = this.y * scale;
  3785. result.z = this.z * scale;
  3786. result.w = this.w * scale;
  3787. return this;
  3788. };
  3789. /**
  3790. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3791. * @param scale defines the scale factor
  3792. * @param result defines the Vector4 object where to store the result
  3793. * @returns the unmodified current Vector4
  3794. */
  3795. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3796. result.x += this.x * scale;
  3797. result.y += this.y * scale;
  3798. result.z += this.z * scale;
  3799. result.w += this.w * scale;
  3800. return this;
  3801. };
  3802. /**
  3803. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3804. */
  3805. Vector4.prototype.equals = function (otherVector) {
  3806. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3807. };
  3808. /**
  3809. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3810. */
  3811. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3812. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3813. return otherVector
  3814. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3815. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3816. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3817. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3818. };
  3819. /**
  3820. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3821. */
  3822. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3823. return this.x === x && this.y === y && this.z === z && this.w === w;
  3824. };
  3825. /**
  3826. * Multiplies in place the current Vector4 by the passed one.
  3827. * Returns the updated Vector4.
  3828. */
  3829. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3830. this.x *= otherVector.x;
  3831. this.y *= otherVector.y;
  3832. this.z *= otherVector.z;
  3833. this.w *= otherVector.w;
  3834. return this;
  3835. };
  3836. /**
  3837. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3838. */
  3839. Vector4.prototype.multiply = function (otherVector) {
  3840. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3841. };
  3842. /**
  3843. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3844. * Returns the current Vector4.
  3845. */
  3846. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3847. result.x = this.x * otherVector.x;
  3848. result.y = this.y * otherVector.y;
  3849. result.z = this.z * otherVector.z;
  3850. result.w = this.w * otherVector.w;
  3851. return this;
  3852. };
  3853. /**
  3854. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3855. */
  3856. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3857. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3858. };
  3859. /**
  3860. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3861. */
  3862. Vector4.prototype.divide = function (otherVector) {
  3863. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3864. };
  3865. /**
  3866. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3867. * Returns the current Vector4.
  3868. */
  3869. Vector4.prototype.divideToRef = function (otherVector, result) {
  3870. result.x = this.x / otherVector.x;
  3871. result.y = this.y / otherVector.y;
  3872. result.z = this.z / otherVector.z;
  3873. result.w = this.w / otherVector.w;
  3874. return this;
  3875. };
  3876. /**
  3877. * Divides the current Vector3 coordinates by the passed ones.
  3878. * @returns the updated Vector3.
  3879. */
  3880. Vector4.prototype.divideInPlace = function (otherVector) {
  3881. return this.divideToRef(otherVector, this);
  3882. };
  3883. /**
  3884. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3885. * @param other defines the second operand
  3886. * @returns the current updated Vector4
  3887. */
  3888. Vector4.prototype.minimizeInPlace = function (other) {
  3889. if (other.x < this.x)
  3890. this.x = other.x;
  3891. if (other.y < this.y)
  3892. this.y = other.y;
  3893. if (other.z < this.z)
  3894. this.z = other.z;
  3895. if (other.w < this.w)
  3896. this.w = other.w;
  3897. return this;
  3898. };
  3899. /**
  3900. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3901. * @param other defines the second operand
  3902. * @returns the current updated Vector4
  3903. */
  3904. Vector4.prototype.maximizeInPlace = function (other) {
  3905. if (other.x > this.x)
  3906. this.x = other.x;
  3907. if (other.y > this.y)
  3908. this.y = other.y;
  3909. if (other.z > this.z)
  3910. this.z = other.z;
  3911. if (other.w > this.w)
  3912. this.w = other.w;
  3913. return this;
  3914. };
  3915. // Properties
  3916. /**
  3917. * Returns the Vector4 length (float).
  3918. */
  3919. Vector4.prototype.length = function () {
  3920. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3921. };
  3922. /**
  3923. * Returns the Vector4 squared length (float).
  3924. */
  3925. Vector4.prototype.lengthSquared = function () {
  3926. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3927. };
  3928. // Methods
  3929. /**
  3930. * Normalizes in place the Vector4.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.normalize = function () {
  3934. var len = this.length();
  3935. if (len === 0)
  3936. return this;
  3937. var num = 1.0 / len;
  3938. this.x *= num;
  3939. this.y *= num;
  3940. this.z *= num;
  3941. this.w *= num;
  3942. return this;
  3943. };
  3944. /**
  3945. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3946. */
  3947. Vector4.prototype.toVector3 = function () {
  3948. return new Vector3(this.x, this.y, this.z);
  3949. };
  3950. /**
  3951. * Returns a new Vector4 copied from the current one.
  3952. */
  3953. Vector4.prototype.clone = function () {
  3954. return new Vector4(this.x, this.y, this.z, this.w);
  3955. };
  3956. /**
  3957. * Updates the current Vector4 with the passed one coordinates.
  3958. * Returns the updated Vector4.
  3959. */
  3960. Vector4.prototype.copyFrom = function (source) {
  3961. this.x = source.x;
  3962. this.y = source.y;
  3963. this.z = source.z;
  3964. this.w = source.w;
  3965. return this;
  3966. };
  3967. /**
  3968. * Updates the current Vector4 coordinates with the passed floats.
  3969. * Returns the updated Vector4.
  3970. */
  3971. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3972. this.x = x;
  3973. this.y = y;
  3974. this.z = z;
  3975. this.w = w;
  3976. return this;
  3977. };
  3978. /**
  3979. * Updates the current Vector4 coordinates with the passed floats.
  3980. * Returns the updated Vector4.
  3981. */
  3982. Vector4.prototype.set = function (x, y, z, w) {
  3983. return this.copyFromFloats(x, y, z, w);
  3984. };
  3985. // Statics
  3986. /**
  3987. * Returns a new Vector4 set from the starting index of the passed array.
  3988. */
  3989. Vector4.FromArray = function (array, offset) {
  3990. if (!offset) {
  3991. offset = 0;
  3992. }
  3993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3994. };
  3995. /**
  3996. * Updates the passed vector "result" from the starting index of the passed array.
  3997. */
  3998. Vector4.FromArrayToRef = function (array, offset, result) {
  3999. result.x = array[offset];
  4000. result.y = array[offset + 1];
  4001. result.z = array[offset + 2];
  4002. result.w = array[offset + 3];
  4003. };
  4004. /**
  4005. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4006. */
  4007. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4008. Vector4.FromArrayToRef(array, offset, result);
  4009. };
  4010. /**
  4011. * Updates the passed vector "result" coordinates from the passed floats.
  4012. */
  4013. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4014. result.x = x;
  4015. result.y = y;
  4016. result.z = z;
  4017. result.w = w;
  4018. };
  4019. /**
  4020. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4021. */
  4022. Vector4.Zero = function () {
  4023. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4024. };
  4025. /**
  4026. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4027. */
  4028. Vector4.One = function () {
  4029. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4030. };
  4031. /**
  4032. * Returns a new normalized Vector4 from the passed one.
  4033. */
  4034. Vector4.Normalize = function (vector) {
  4035. var result = Vector4.Zero();
  4036. Vector4.NormalizeToRef(vector, result);
  4037. return result;
  4038. };
  4039. /**
  4040. * Updates the passed vector "result" from the normalization of the passed one.
  4041. */
  4042. Vector4.NormalizeToRef = function (vector, result) {
  4043. result.copyFrom(vector);
  4044. result.normalize();
  4045. };
  4046. Vector4.Minimize = function (left, right) {
  4047. var min = left.clone();
  4048. min.minimizeInPlace(right);
  4049. return min;
  4050. };
  4051. Vector4.Maximize = function (left, right) {
  4052. var max = left.clone();
  4053. max.maximizeInPlace(right);
  4054. return max;
  4055. };
  4056. /**
  4057. * Returns the distance (float) between the vectors "value1" and "value2".
  4058. */
  4059. Vector4.Distance = function (value1, value2) {
  4060. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4061. };
  4062. /**
  4063. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4064. */
  4065. Vector4.DistanceSquared = function (value1, value2) {
  4066. var x = value1.x - value2.x;
  4067. var y = value1.y - value2.y;
  4068. var z = value1.z - value2.z;
  4069. var w = value1.w - value2.w;
  4070. return (x * x) + (y * y) + (z * z) + (w * w);
  4071. };
  4072. /**
  4073. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4074. */
  4075. Vector4.Center = function (value1, value2) {
  4076. var center = value1.add(value2);
  4077. center.scaleInPlace(0.5);
  4078. return center;
  4079. };
  4080. /**
  4081. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4082. * This methods computes transformed normalized direction vectors only.
  4083. */
  4084. Vector4.TransformNormal = function (vector, transformation) {
  4085. var result = Vector4.Zero();
  4086. Vector4.TransformNormalToRef(vector, transformation, result);
  4087. return result;
  4088. };
  4089. /**
  4090. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4091. * This methods computes transformed normalized direction vectors only.
  4092. */
  4093. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4094. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4095. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4096. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4097. result.x = x;
  4098. result.y = y;
  4099. result.z = z;
  4100. result.w = vector.w;
  4101. };
  4102. /**
  4103. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4104. * This methods computes transformed normalized direction vectors only.
  4105. */
  4106. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4107. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4108. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4109. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4110. result.w = w;
  4111. };
  4112. return Vector4;
  4113. }());
  4114. BABYLON.Vector4 = Vector4;
  4115. var Size = /** @class */ (function () {
  4116. /**
  4117. * Creates a Size object from the passed width and height (floats).
  4118. */
  4119. function Size(width, height) {
  4120. this.width = width;
  4121. this.height = height;
  4122. }
  4123. // Returns a string with the Size width and height.
  4124. Size.prototype.toString = function () {
  4125. return "{W: " + this.width + ", H: " + this.height + "}";
  4126. };
  4127. /**
  4128. * Returns the string "Size"
  4129. */
  4130. Size.prototype.getClassName = function () {
  4131. return "Size";
  4132. };
  4133. /**
  4134. * Returns the Size hash code.
  4135. */
  4136. Size.prototype.getHashCode = function () {
  4137. var hash = this.width || 0;
  4138. hash = (hash * 397) ^ (this.height || 0);
  4139. return hash;
  4140. };
  4141. /**
  4142. * Updates the current size from the passed one.
  4143. * Returns the updated Size.
  4144. */
  4145. Size.prototype.copyFrom = function (src) {
  4146. this.width = src.width;
  4147. this.height = src.height;
  4148. };
  4149. /**
  4150. * Updates in place the current Size from the passed floats.
  4151. * Returns the updated Size.
  4152. */
  4153. Size.prototype.copyFromFloats = function (width, height) {
  4154. this.width = width;
  4155. this.height = height;
  4156. return this;
  4157. };
  4158. /**
  4159. * Updates in place the current Size from the passed floats.
  4160. * Returns the updated Size.
  4161. */
  4162. Size.prototype.set = function (width, height) {
  4163. return this.copyFromFloats(width, height);
  4164. };
  4165. /**
  4166. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4167. */
  4168. Size.prototype.multiplyByFloats = function (w, h) {
  4169. return new Size(this.width * w, this.height * h);
  4170. };
  4171. /**
  4172. * Returns a new Size copied from the passed one.
  4173. */
  4174. Size.prototype.clone = function () {
  4175. return new Size(this.width, this.height);
  4176. };
  4177. /**
  4178. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4179. */
  4180. Size.prototype.equals = function (other) {
  4181. if (!other) {
  4182. return false;
  4183. }
  4184. return (this.width === other.width) && (this.height === other.height);
  4185. };
  4186. Object.defineProperty(Size.prototype, "surface", {
  4187. /**
  4188. * Returns the surface of the Size : width * height (float).
  4189. */
  4190. get: function () {
  4191. return this.width * this.height;
  4192. },
  4193. enumerable: true,
  4194. configurable: true
  4195. });
  4196. /**
  4197. * Returns a new Size set to (0.0, 0.0)
  4198. */
  4199. Size.Zero = function () {
  4200. return new Size(0.0, 0.0);
  4201. };
  4202. /**
  4203. * Returns a new Size set as the addition result of the current Size and the passed one.
  4204. */
  4205. Size.prototype.add = function (otherSize) {
  4206. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4207. return r;
  4208. };
  4209. /**
  4210. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4211. */
  4212. Size.prototype.subtract = function (otherSize) {
  4213. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4214. return r;
  4215. };
  4216. /**
  4217. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4218. */
  4219. Size.Lerp = function (start, end, amount) {
  4220. var w = start.width + ((end.width - start.width) * amount);
  4221. var h = start.height + ((end.height - start.height) * amount);
  4222. return new Size(w, h);
  4223. };
  4224. return Size;
  4225. }());
  4226. BABYLON.Size = Size;
  4227. var Quaternion = /** @class */ (function () {
  4228. /**
  4229. * Creates a new Quaternion from the passed floats.
  4230. */
  4231. function Quaternion(x, y, z, w) {
  4232. if (x === void 0) { x = 0.0; }
  4233. if (y === void 0) { y = 0.0; }
  4234. if (z === void 0) { z = 0.0; }
  4235. if (w === void 0) { w = 1.0; }
  4236. this.x = x;
  4237. this.y = y;
  4238. this.z = z;
  4239. this.w = w;
  4240. }
  4241. /**
  4242. * Returns a string with the Quaternion coordinates.
  4243. */
  4244. Quaternion.prototype.toString = function () {
  4245. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4246. };
  4247. /**
  4248. * Returns the string "Quaternion".
  4249. */
  4250. Quaternion.prototype.getClassName = function () {
  4251. return "Quaternion";
  4252. };
  4253. /**
  4254. * Returns the Quaternion hash code.
  4255. */
  4256. Quaternion.prototype.getHashCode = function () {
  4257. var hash = this.x || 0;
  4258. hash = (hash * 397) ^ (this.y || 0);
  4259. hash = (hash * 397) ^ (this.z || 0);
  4260. hash = (hash * 397) ^ (this.w || 0);
  4261. return hash;
  4262. };
  4263. /**
  4264. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4265. */
  4266. Quaternion.prototype.asArray = function () {
  4267. return [this.x, this.y, this.z, this.w];
  4268. };
  4269. /**
  4270. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4271. */
  4272. Quaternion.prototype.equals = function (otherQuaternion) {
  4273. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4274. };
  4275. /**
  4276. * Returns a new Quaternion copied from the current one.
  4277. */
  4278. Quaternion.prototype.clone = function () {
  4279. return new Quaternion(this.x, this.y, this.z, this.w);
  4280. };
  4281. /**
  4282. * Updates the current Quaternion from the passed one coordinates.
  4283. * Returns the updated Quaterion.
  4284. */
  4285. Quaternion.prototype.copyFrom = function (other) {
  4286. this.x = other.x;
  4287. this.y = other.y;
  4288. this.z = other.z;
  4289. this.w = other.w;
  4290. return this;
  4291. };
  4292. /**
  4293. * Updates the current Quaternion from the passed float coordinates.
  4294. * Returns the updated Quaterion.
  4295. */
  4296. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4297. this.x = x;
  4298. this.y = y;
  4299. this.z = z;
  4300. this.w = w;
  4301. return this;
  4302. };
  4303. /**
  4304. * Updates the current Quaternion from the passed float coordinates.
  4305. * Returns the updated Quaterion.
  4306. */
  4307. Quaternion.prototype.set = function (x, y, z, w) {
  4308. return this.copyFromFloats(x, y, z, w);
  4309. };
  4310. /**
  4311. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4312. */
  4313. Quaternion.prototype.add = function (other) {
  4314. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4315. };
  4316. /**
  4317. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4318. */
  4319. Quaternion.prototype.subtract = function (other) {
  4320. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4321. };
  4322. /**
  4323. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4324. */
  4325. Quaternion.prototype.scale = function (value) {
  4326. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4327. };
  4328. /**
  4329. * Scale the current Quaternion values by a factor to a given Quaternion
  4330. * @param scale defines the scale factor
  4331. * @param result defines the Quaternion object where to store the result
  4332. * @returns the unmodified current Quaternion
  4333. */
  4334. Quaternion.prototype.scaleToRef = function (scale, result) {
  4335. result.x = this.x * scale;
  4336. result.y = this.y * scale;
  4337. result.z = this.z * scale;
  4338. result.w = this.w * scale;
  4339. return this;
  4340. };
  4341. /**
  4342. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4343. * @param scale defines the scale factor
  4344. * @param result defines the Quaternion object where to store the result
  4345. * @returns the unmodified current Quaternion
  4346. */
  4347. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4348. result.x += this.x * scale;
  4349. result.y += this.y * scale;
  4350. result.z += this.z * scale;
  4351. result.w += this.w * scale;
  4352. return this;
  4353. };
  4354. /**
  4355. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4356. */
  4357. Quaternion.prototype.multiply = function (q1) {
  4358. var result = new Quaternion(0, 0, 0, 1.0);
  4359. this.multiplyToRef(q1, result);
  4360. return result;
  4361. };
  4362. /**
  4363. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4364. * Returns the current Quaternion.
  4365. */
  4366. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4367. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4368. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4369. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4370. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4371. result.copyFromFloats(x, y, z, w);
  4372. return this;
  4373. };
  4374. /**
  4375. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4376. * Returns the updated Quaternion.
  4377. */
  4378. Quaternion.prototype.multiplyInPlace = function (q1) {
  4379. this.multiplyToRef(q1, this);
  4380. return this;
  4381. };
  4382. /**
  4383. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4384. * Returns the current Quaternion.
  4385. */
  4386. Quaternion.prototype.conjugateToRef = function (ref) {
  4387. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4388. return this;
  4389. };
  4390. /**
  4391. * Conjugates in place the current Quaternion.
  4392. * Returns the updated Quaternion.
  4393. */
  4394. Quaternion.prototype.conjugateInPlace = function () {
  4395. this.x *= -1;
  4396. this.y *= -1;
  4397. this.z *= -1;
  4398. return this;
  4399. };
  4400. /**
  4401. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4402. */
  4403. Quaternion.prototype.conjugate = function () {
  4404. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4405. return result;
  4406. };
  4407. /**
  4408. * Returns the Quaternion length (float).
  4409. */
  4410. Quaternion.prototype.length = function () {
  4411. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4412. };
  4413. /**
  4414. * Normalize in place the current Quaternion.
  4415. * Returns the updated Quaternion.
  4416. */
  4417. Quaternion.prototype.normalize = function () {
  4418. var length = 1.0 / this.length();
  4419. this.x *= length;
  4420. this.y *= length;
  4421. this.z *= length;
  4422. this.w *= length;
  4423. return this;
  4424. };
  4425. /**
  4426. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4427. * @param order is a reserved parameter and is ignore for now
  4428. * @returns the new Vector3
  4429. */
  4430. Quaternion.prototype.toEulerAngles = function (order) {
  4431. if (order === void 0) { order = "YZX"; }
  4432. var result = Vector3.Zero();
  4433. this.toEulerAnglesToRef(result, order);
  4434. return result;
  4435. };
  4436. /**
  4437. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4438. * @param result defines the vector which will be filled with the Euler angles
  4439. * @param order is a reserved parameter and is ignore for now
  4440. * @returns the current Quaternion
  4441. */
  4442. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4443. if (order === void 0) { order = "YZX"; }
  4444. var qz = this.z;
  4445. var qx = this.x;
  4446. var qy = this.y;
  4447. var qw = this.w;
  4448. var sqw = qw * qw;
  4449. var sqz = qz * qz;
  4450. var sqx = qx * qx;
  4451. var sqy = qy * qy;
  4452. var zAxisY = qy * qz - qx * qw;
  4453. var limit = .4999999;
  4454. if (zAxisY < -limit) {
  4455. result.y = 2 * Math.atan2(qy, qw);
  4456. result.x = Math.PI / 2;
  4457. result.z = 0;
  4458. }
  4459. else if (zAxisY > limit) {
  4460. result.y = 2 * Math.atan2(qy, qw);
  4461. result.x = -Math.PI / 2;
  4462. result.z = 0;
  4463. }
  4464. else {
  4465. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4466. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4467. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4468. }
  4469. return this;
  4470. };
  4471. /**
  4472. * Updates the passed rotation matrix with the current Quaternion values.
  4473. * Returns the current Quaternion.
  4474. */
  4475. Quaternion.prototype.toRotationMatrix = function (result) {
  4476. var xx = this.x * this.x;
  4477. var yy = this.y * this.y;
  4478. var zz = this.z * this.z;
  4479. var xy = this.x * this.y;
  4480. var zw = this.z * this.w;
  4481. var zx = this.z * this.x;
  4482. var yw = this.y * this.w;
  4483. var yz = this.y * this.z;
  4484. var xw = this.x * this.w;
  4485. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4486. result.m[1] = 2.0 * (xy + zw);
  4487. result.m[2] = 2.0 * (zx - yw);
  4488. result.m[3] = 0;
  4489. result.m[4] = 2.0 * (xy - zw);
  4490. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4491. result.m[6] = 2.0 * (yz + xw);
  4492. result.m[7] = 0;
  4493. result.m[8] = 2.0 * (zx + yw);
  4494. result.m[9] = 2.0 * (yz - xw);
  4495. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4496. result.m[11] = 0;
  4497. result.m[12] = 0;
  4498. result.m[13] = 0;
  4499. result.m[14] = 0;
  4500. result.m[15] = 1.0;
  4501. result._markAsUpdated();
  4502. return this;
  4503. };
  4504. /**
  4505. * Updates the current Quaternion from the passed rotation matrix values.
  4506. * Returns the updated Quaternion.
  4507. */
  4508. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4509. Quaternion.FromRotationMatrixToRef(matrix, this);
  4510. return this;
  4511. };
  4512. // Statics
  4513. /**
  4514. * Returns a new Quaternion set from the passed rotation matrix values.
  4515. */
  4516. Quaternion.FromRotationMatrix = function (matrix) {
  4517. var result = new Quaternion();
  4518. Quaternion.FromRotationMatrixToRef(matrix, result);
  4519. return result;
  4520. };
  4521. /**
  4522. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4523. */
  4524. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4525. var data = matrix.m;
  4526. var m11 = data[0], m12 = data[4], m13 = data[8];
  4527. var m21 = data[1], m22 = data[5], m23 = data[9];
  4528. var m31 = data[2], m32 = data[6], m33 = data[10];
  4529. var trace = m11 + m22 + m33;
  4530. var s;
  4531. if (trace > 0) {
  4532. s = 0.5 / Math.sqrt(trace + 1.0);
  4533. result.w = 0.25 / s;
  4534. result.x = (m32 - m23) * s;
  4535. result.y = (m13 - m31) * s;
  4536. result.z = (m21 - m12) * s;
  4537. }
  4538. else if (m11 > m22 && m11 > m33) {
  4539. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4540. result.w = (m32 - m23) / s;
  4541. result.x = 0.25 * s;
  4542. result.y = (m12 + m21) / s;
  4543. result.z = (m13 + m31) / s;
  4544. }
  4545. else if (m22 > m33) {
  4546. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4547. result.w = (m13 - m31) / s;
  4548. result.x = (m12 + m21) / s;
  4549. result.y = 0.25 * s;
  4550. result.z = (m23 + m32) / s;
  4551. }
  4552. else {
  4553. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4554. result.w = (m21 - m12) / s;
  4555. result.x = (m13 + m31) / s;
  4556. result.y = (m23 + m32) / s;
  4557. result.z = 0.25 * s;
  4558. }
  4559. };
  4560. /**
  4561. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4562. */
  4563. Quaternion.Zero = function () {
  4564. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4565. };
  4566. /**
  4567. * Returns a new Quaternion as the inverted current Quaternion.
  4568. */
  4569. Quaternion.Inverse = function (q) {
  4570. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4571. };
  4572. /**
  4573. * Returns the identity Quaternion.
  4574. */
  4575. Quaternion.Identity = function () {
  4576. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4577. };
  4578. Quaternion.IsIdentity = function (quaternion) {
  4579. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4580. };
  4581. /**
  4582. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4583. */
  4584. Quaternion.RotationAxis = function (axis, angle) {
  4585. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4586. };
  4587. /**
  4588. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4589. */
  4590. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4591. var sin = Math.sin(angle / 2);
  4592. axis.normalize();
  4593. result.w = Math.cos(angle / 2);
  4594. result.x = axis.x * sin;
  4595. result.y = axis.y * sin;
  4596. result.z = axis.z * sin;
  4597. return result;
  4598. };
  4599. /**
  4600. * Retuns a new Quaternion set from the starting index of the passed array.
  4601. */
  4602. Quaternion.FromArray = function (array, offset) {
  4603. if (!offset) {
  4604. offset = 0;
  4605. }
  4606. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4607. };
  4608. /**
  4609. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4610. */
  4611. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4612. var q = new Quaternion();
  4613. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4614. return q;
  4615. };
  4616. /**
  4617. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4618. */
  4619. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4620. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4621. var halfRoll = roll * 0.5;
  4622. var halfPitch = pitch * 0.5;
  4623. var halfYaw = yaw * 0.5;
  4624. var sinRoll = Math.sin(halfRoll);
  4625. var cosRoll = Math.cos(halfRoll);
  4626. var sinPitch = Math.sin(halfPitch);
  4627. var cosPitch = Math.cos(halfPitch);
  4628. var sinYaw = Math.sin(halfYaw);
  4629. var cosYaw = Math.cos(halfYaw);
  4630. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4631. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4632. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4633. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4634. };
  4635. /**
  4636. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4637. */
  4638. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4639. var result = new Quaternion();
  4640. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4641. return result;
  4642. };
  4643. /**
  4644. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4645. */
  4646. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4647. // Produces a quaternion from Euler angles in the z-x-z orientation
  4648. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4649. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4650. var halfBeta = beta * 0.5;
  4651. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4652. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4653. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4654. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4655. };
  4656. /**
  4657. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4658. * cf to Vector3.RotationFromAxis() documentation.
  4659. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4660. */
  4661. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4662. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4663. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4664. return quat;
  4665. };
  4666. /**
  4667. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4668. * cf to Vector3.RotationFromAxis() documentation.
  4669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4670. */
  4671. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4672. var rotMat = MathTmp.Matrix[0];
  4673. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4674. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4675. };
  4676. Quaternion.Slerp = function (left, right, amount) {
  4677. var result = Quaternion.Identity();
  4678. Quaternion.SlerpToRef(left, right, amount, result);
  4679. return result;
  4680. };
  4681. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4682. var num2;
  4683. var num3;
  4684. var num = amount;
  4685. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4686. var flag = false;
  4687. if (num4 < 0) {
  4688. flag = true;
  4689. num4 = -num4;
  4690. }
  4691. if (num4 > 0.999999) {
  4692. num3 = 1 - num;
  4693. num2 = flag ? -num : num;
  4694. }
  4695. else {
  4696. var num5 = Math.acos(num4);
  4697. var num6 = (1.0 / Math.sin(num5));
  4698. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4699. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4700. }
  4701. result.x = (num3 * left.x) + (num2 * right.x);
  4702. result.y = (num3 * left.y) + (num2 * right.y);
  4703. result.z = (num3 * left.z) + (num2 * right.z);
  4704. result.w = (num3 * left.w) + (num2 * right.w);
  4705. };
  4706. /**
  4707. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4708. */
  4709. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4710. var squared = amount * amount;
  4711. var cubed = amount * squared;
  4712. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4713. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4714. var part3 = (cubed - (2.0 * squared)) + amount;
  4715. var part4 = cubed - squared;
  4716. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4717. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4718. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4719. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4720. return new Quaternion(x, y, z, w);
  4721. };
  4722. return Quaternion;
  4723. }());
  4724. BABYLON.Quaternion = Quaternion;
  4725. var Matrix = /** @class */ (function () {
  4726. function Matrix() {
  4727. this._isIdentity = false;
  4728. this._isIdentityDirty = true;
  4729. this.m = new Float32Array(16);
  4730. this._markAsUpdated();
  4731. }
  4732. Matrix.prototype._markAsUpdated = function () {
  4733. this.updateFlag = Matrix._updateFlagSeed++;
  4734. this._isIdentityDirty = true;
  4735. };
  4736. // Properties
  4737. /**
  4738. * Boolean : True is the matrix is the identity matrix
  4739. */
  4740. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4741. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4742. if (this._isIdentityDirty) {
  4743. this._isIdentityDirty = false;
  4744. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4745. this._isIdentity = false;
  4746. }
  4747. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4748. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4749. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4750. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4751. this._isIdentity = false;
  4752. }
  4753. else {
  4754. this._isIdentity = true;
  4755. }
  4756. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4757. this._isIdentity = false;
  4758. }
  4759. }
  4760. return this._isIdentity;
  4761. };
  4762. /**
  4763. * Returns the matrix determinant (float).
  4764. */
  4765. Matrix.prototype.determinant = function () {
  4766. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4767. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4768. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4769. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4770. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4771. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4772. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4773. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4774. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4775. };
  4776. // Methods
  4777. /**
  4778. * Returns the matrix underlying array.
  4779. */
  4780. Matrix.prototype.toArray = function () {
  4781. return this.m;
  4782. };
  4783. /**
  4784. * Returns the matrix underlying array.
  4785. */
  4786. Matrix.prototype.asArray = function () {
  4787. return this.toArray();
  4788. };
  4789. /**
  4790. * Inverts in place the Matrix.
  4791. * Returns the Matrix inverted.
  4792. */
  4793. Matrix.prototype.invert = function () {
  4794. this.invertToRef(this);
  4795. return this;
  4796. };
  4797. /**
  4798. * Sets all the matrix elements to zero.
  4799. * Returns the Matrix.
  4800. */
  4801. Matrix.prototype.reset = function () {
  4802. for (var index = 0; index < 16; index++) {
  4803. this.m[index] = 0.0;
  4804. }
  4805. this._markAsUpdated();
  4806. return this;
  4807. };
  4808. /**
  4809. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4810. */
  4811. Matrix.prototype.add = function (other) {
  4812. var result = new Matrix();
  4813. this.addToRef(other, result);
  4814. return result;
  4815. };
  4816. /**
  4817. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4818. * Returns the Matrix.
  4819. */
  4820. Matrix.prototype.addToRef = function (other, result) {
  4821. for (var index = 0; index < 16; index++) {
  4822. result.m[index] = this.m[index] + other.m[index];
  4823. }
  4824. result._markAsUpdated();
  4825. return this;
  4826. };
  4827. /**
  4828. * Adds in place the passed matrix to the current Matrix.
  4829. * Returns the updated Matrix.
  4830. */
  4831. Matrix.prototype.addToSelf = function (other) {
  4832. for (var index = 0; index < 16; index++) {
  4833. this.m[index] += other.m[index];
  4834. }
  4835. this._markAsUpdated();
  4836. return this;
  4837. };
  4838. /**
  4839. * Sets the passed matrix with the current inverted Matrix.
  4840. * Returns the unmodified current Matrix.
  4841. */
  4842. Matrix.prototype.invertToRef = function (other) {
  4843. var l1 = this.m[0];
  4844. var l2 = this.m[1];
  4845. var l3 = this.m[2];
  4846. var l4 = this.m[3];
  4847. var l5 = this.m[4];
  4848. var l6 = this.m[5];
  4849. var l7 = this.m[6];
  4850. var l8 = this.m[7];
  4851. var l9 = this.m[8];
  4852. var l10 = this.m[9];
  4853. var l11 = this.m[10];
  4854. var l12 = this.m[11];
  4855. var l13 = this.m[12];
  4856. var l14 = this.m[13];
  4857. var l15 = this.m[14];
  4858. var l16 = this.m[15];
  4859. var l17 = (l11 * l16) - (l12 * l15);
  4860. var l18 = (l10 * l16) - (l12 * l14);
  4861. var l19 = (l10 * l15) - (l11 * l14);
  4862. var l20 = (l9 * l16) - (l12 * l13);
  4863. var l21 = (l9 * l15) - (l11 * l13);
  4864. var l22 = (l9 * l14) - (l10 * l13);
  4865. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4866. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4867. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4868. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4869. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4870. var l28 = (l7 * l16) - (l8 * l15);
  4871. var l29 = (l6 * l16) - (l8 * l14);
  4872. var l30 = (l6 * l15) - (l7 * l14);
  4873. var l31 = (l5 * l16) - (l8 * l13);
  4874. var l32 = (l5 * l15) - (l7 * l13);
  4875. var l33 = (l5 * l14) - (l6 * l13);
  4876. var l34 = (l7 * l12) - (l8 * l11);
  4877. var l35 = (l6 * l12) - (l8 * l10);
  4878. var l36 = (l6 * l11) - (l7 * l10);
  4879. var l37 = (l5 * l12) - (l8 * l9);
  4880. var l38 = (l5 * l11) - (l7 * l9);
  4881. var l39 = (l5 * l10) - (l6 * l9);
  4882. other.m[0] = l23 * l27;
  4883. other.m[4] = l24 * l27;
  4884. other.m[8] = l25 * l27;
  4885. other.m[12] = l26 * l27;
  4886. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4887. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4888. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4889. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4890. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4891. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4892. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4893. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4894. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4895. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4896. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4897. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4898. other._markAsUpdated();
  4899. return this;
  4900. };
  4901. /**
  4902. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4903. * Returns the updated Matrix.
  4904. */
  4905. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4906. this.m[12] = x;
  4907. this.m[13] = y;
  4908. this.m[14] = z;
  4909. this._markAsUpdated();
  4910. return this;
  4911. };
  4912. /**
  4913. * Inserts the translation vector in the current Matrix.
  4914. * Returns the updated Matrix.
  4915. */
  4916. Matrix.prototype.setTranslation = function (vector3) {
  4917. this.m[12] = vector3.x;
  4918. this.m[13] = vector3.y;
  4919. this.m[14] = vector3.z;
  4920. this._markAsUpdated();
  4921. return this;
  4922. };
  4923. /**
  4924. * Returns a new Vector3 as the extracted translation from the Matrix.
  4925. */
  4926. Matrix.prototype.getTranslation = function () {
  4927. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4928. };
  4929. /**
  4930. * Fill a Vector3 with the extracted translation from the Matrix.
  4931. */
  4932. Matrix.prototype.getTranslationToRef = function (result) {
  4933. result.x = this.m[12];
  4934. result.y = this.m[13];
  4935. result.z = this.m[14];
  4936. return this;
  4937. };
  4938. /**
  4939. * Remove rotation and scaling part from the Matrix.
  4940. * Returns the updated Matrix.
  4941. */
  4942. Matrix.prototype.removeRotationAndScaling = function () {
  4943. this.setRowFromFloats(0, 1, 0, 0, 0);
  4944. this.setRowFromFloats(1, 0, 1, 0, 0);
  4945. this.setRowFromFloats(2, 0, 0, 1, 0);
  4946. return this;
  4947. };
  4948. /**
  4949. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4950. */
  4951. Matrix.prototype.multiply = function (other) {
  4952. var result = new Matrix();
  4953. this.multiplyToRef(other, result);
  4954. return result;
  4955. };
  4956. /**
  4957. * Updates the current Matrix from the passed one values.
  4958. * Returns the updated Matrix.
  4959. */
  4960. Matrix.prototype.copyFrom = function (other) {
  4961. for (var index = 0; index < 16; index++) {
  4962. this.m[index] = other.m[index];
  4963. }
  4964. this._markAsUpdated();
  4965. return this;
  4966. };
  4967. /**
  4968. * Populates the passed array from the starting index with the Matrix values.
  4969. * Returns the Matrix.
  4970. */
  4971. Matrix.prototype.copyToArray = function (array, offset) {
  4972. if (offset === void 0) { offset = 0; }
  4973. for (var index = 0; index < 16; index++) {
  4974. array[offset + index] = this.m[index];
  4975. }
  4976. return this;
  4977. };
  4978. /**
  4979. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4980. */
  4981. Matrix.prototype.multiplyToRef = function (other, result) {
  4982. this.multiplyToArray(other, result.m, 0);
  4983. result._markAsUpdated();
  4984. return this;
  4985. };
  4986. /**
  4987. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4988. */
  4989. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4990. var tm0 = this.m[0];
  4991. var tm1 = this.m[1];
  4992. var tm2 = this.m[2];
  4993. var tm3 = this.m[3];
  4994. var tm4 = this.m[4];
  4995. var tm5 = this.m[5];
  4996. var tm6 = this.m[6];
  4997. var tm7 = this.m[7];
  4998. var tm8 = this.m[8];
  4999. var tm9 = this.m[9];
  5000. var tm10 = this.m[10];
  5001. var tm11 = this.m[11];
  5002. var tm12 = this.m[12];
  5003. var tm13 = this.m[13];
  5004. var tm14 = this.m[14];
  5005. var tm15 = this.m[15];
  5006. var om0 = other.m[0];
  5007. var om1 = other.m[1];
  5008. var om2 = other.m[2];
  5009. var om3 = other.m[3];
  5010. var om4 = other.m[4];
  5011. var om5 = other.m[5];
  5012. var om6 = other.m[6];
  5013. var om7 = other.m[7];
  5014. var om8 = other.m[8];
  5015. var om9 = other.m[9];
  5016. var om10 = other.m[10];
  5017. var om11 = other.m[11];
  5018. var om12 = other.m[12];
  5019. var om13 = other.m[13];
  5020. var om14 = other.m[14];
  5021. var om15 = other.m[15];
  5022. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5023. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5024. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5025. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5026. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5027. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5028. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5029. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5030. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5031. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5032. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5033. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5034. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5035. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5036. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5037. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5038. return this;
  5039. };
  5040. /**
  5041. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5042. */
  5043. Matrix.prototype.equals = function (value) {
  5044. return value &&
  5045. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5046. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5047. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5048. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5049. };
  5050. /**
  5051. * Returns a new Matrix from the current Matrix.
  5052. */
  5053. Matrix.prototype.clone = function () {
  5054. 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]);
  5055. };
  5056. /**
  5057. * Returns the string "Matrix"
  5058. */
  5059. Matrix.prototype.getClassName = function () {
  5060. return "Matrix";
  5061. };
  5062. /**
  5063. * Returns the Matrix hash code.
  5064. */
  5065. Matrix.prototype.getHashCode = function () {
  5066. var hash = this.m[0] || 0;
  5067. for (var i = 1; i < 16; i++) {
  5068. hash = (hash * 397) ^ (this.m[i] || 0);
  5069. }
  5070. return hash;
  5071. };
  5072. /**
  5073. * Decomposes the current Matrix into :
  5074. * - a scale vector3 passed as a reference to update,
  5075. * - a rotation quaternion passed as a reference to update,
  5076. * - a translation vector3 passed as a reference to update.
  5077. * Returns the true if operation was successful.
  5078. */
  5079. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5080. translation.x = this.m[12];
  5081. translation.y = this.m[13];
  5082. translation.z = this.m[14];
  5083. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5084. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5085. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5086. if (this.determinant() <= 0) {
  5087. scale.y *= -1;
  5088. }
  5089. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5090. rotation.x = 0;
  5091. rotation.y = 0;
  5092. rotation.z = 0;
  5093. rotation.w = 1;
  5094. return false;
  5095. }
  5096. 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]);
  5097. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5098. return true;
  5099. };
  5100. /**
  5101. * Returns the index-th row of the current matrix as a new Vector4.
  5102. */
  5103. Matrix.prototype.getRow = function (index) {
  5104. if (index < 0 || index > 3) {
  5105. return null;
  5106. }
  5107. var i = index * 4;
  5108. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5109. };
  5110. /**
  5111. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5112. * Returns the updated Matrix.
  5113. */
  5114. Matrix.prototype.setRow = function (index, row) {
  5115. if (index < 0 || index > 3) {
  5116. return this;
  5117. }
  5118. var i = index * 4;
  5119. this.m[i + 0] = row.x;
  5120. this.m[i + 1] = row.y;
  5121. this.m[i + 2] = row.z;
  5122. this.m[i + 3] = row.w;
  5123. this._markAsUpdated();
  5124. return this;
  5125. };
  5126. /**
  5127. * Compute the transpose of the matrix.
  5128. * Returns a new Matrix.
  5129. */
  5130. Matrix.prototype.transpose = function () {
  5131. return Matrix.Transpose(this);
  5132. };
  5133. /**
  5134. * Compute the transpose of the matrix.
  5135. * Returns the current matrix.
  5136. */
  5137. Matrix.prototype.transposeToRef = function (result) {
  5138. Matrix.TransposeToRef(this, result);
  5139. return this;
  5140. };
  5141. /**
  5142. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5143. * Returns the updated Matrix.
  5144. */
  5145. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5146. if (index < 0 || index > 3) {
  5147. return this;
  5148. }
  5149. var i = index * 4;
  5150. this.m[i + 0] = x;
  5151. this.m[i + 1] = y;
  5152. this.m[i + 2] = z;
  5153. this.m[i + 3] = w;
  5154. this._markAsUpdated();
  5155. return this;
  5156. };
  5157. /**
  5158. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5159. * @param scale defines the scale factor
  5160. * @returns a new Matrix
  5161. */
  5162. Matrix.prototype.scale = function (scale) {
  5163. var result = new Matrix();
  5164. this.scaleToRef(scale, result);
  5165. return result;
  5166. };
  5167. /**
  5168. * Scale the current Matrix values by a factor to a given result Matrix
  5169. * @param scale defines the scale factor
  5170. * @param result defines the Matrix to store the result
  5171. * @returns the current Matrix
  5172. */
  5173. Matrix.prototype.scaleToRef = function (scale, result) {
  5174. for (var index = 0; index < 16; index++) {
  5175. result.m[index] = this.m[index] * scale;
  5176. }
  5177. result._markAsUpdated();
  5178. return this;
  5179. };
  5180. /**
  5181. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5182. * @param scale defines the scale factor
  5183. * @param result defines the Matrix to store the result
  5184. * @returns the current Matrix
  5185. */
  5186. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5187. for (var index = 0; index < 16; index++) {
  5188. result.m[index] += this.m[index] * scale;
  5189. }
  5190. result._markAsUpdated();
  5191. return this;
  5192. };
  5193. /**
  5194. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5195. * @param ref matrix to store the result
  5196. */
  5197. Matrix.prototype.toNormalMatrix = function (ref) {
  5198. this.invertToRef(ref);
  5199. ref.transpose();
  5200. var m = ref.m;
  5201. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5202. };
  5203. /**
  5204. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5205. */
  5206. Matrix.prototype.getRotationMatrix = function () {
  5207. var result = Matrix.Identity();
  5208. this.getRotationMatrixToRef(result);
  5209. return result;
  5210. };
  5211. /**
  5212. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5213. * Returns the current Matrix.
  5214. */
  5215. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5216. var m = this.m;
  5217. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5218. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5219. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5220. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5221. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5222. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5223. 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);
  5224. return this;
  5225. };
  5226. // Statics
  5227. /**
  5228. * Returns a new Matrix set from the starting index of the passed array.
  5229. */
  5230. Matrix.FromArray = function (array, offset) {
  5231. var result = new Matrix();
  5232. if (!offset) {
  5233. offset = 0;
  5234. }
  5235. Matrix.FromArrayToRef(array, offset, result);
  5236. return result;
  5237. };
  5238. /**
  5239. * Sets the passed "result" matrix from the starting index of the passed array.
  5240. */
  5241. Matrix.FromArrayToRef = function (array, offset, result) {
  5242. for (var index = 0; index < 16; index++) {
  5243. result.m[index] = array[index + offset];
  5244. }
  5245. result._markAsUpdated();
  5246. };
  5247. /**
  5248. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5249. */
  5250. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5251. for (var index = 0; index < 16; index++) {
  5252. result.m[index] = array[index + offset] * scale;
  5253. }
  5254. result._markAsUpdated();
  5255. };
  5256. /**
  5257. * Sets the passed matrix "result" with the 16 passed floats.
  5258. */
  5259. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5260. result.m[0] = initialM11;
  5261. result.m[1] = initialM12;
  5262. result.m[2] = initialM13;
  5263. result.m[3] = initialM14;
  5264. result.m[4] = initialM21;
  5265. result.m[5] = initialM22;
  5266. result.m[6] = initialM23;
  5267. result.m[7] = initialM24;
  5268. result.m[8] = initialM31;
  5269. result.m[9] = initialM32;
  5270. result.m[10] = initialM33;
  5271. result.m[11] = initialM34;
  5272. result.m[12] = initialM41;
  5273. result.m[13] = initialM42;
  5274. result.m[14] = initialM43;
  5275. result.m[15] = initialM44;
  5276. result._markAsUpdated();
  5277. };
  5278. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5279. /**
  5280. * Static identity matrix to be used as readonly matrix
  5281. * Must not be updated.
  5282. */
  5283. get: function () {
  5284. return Matrix._identityReadOnly;
  5285. },
  5286. enumerable: true,
  5287. configurable: true
  5288. });
  5289. /**
  5290. * Returns a new Matrix set from the 16 passed floats.
  5291. */
  5292. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5293. var result = new Matrix();
  5294. result.m[0] = initialM11;
  5295. result.m[1] = initialM12;
  5296. result.m[2] = initialM13;
  5297. result.m[3] = initialM14;
  5298. result.m[4] = initialM21;
  5299. result.m[5] = initialM22;
  5300. result.m[6] = initialM23;
  5301. result.m[7] = initialM24;
  5302. result.m[8] = initialM31;
  5303. result.m[9] = initialM32;
  5304. result.m[10] = initialM33;
  5305. result.m[11] = initialM34;
  5306. result.m[12] = initialM41;
  5307. result.m[13] = initialM42;
  5308. result.m[14] = initialM43;
  5309. result.m[15] = initialM44;
  5310. return result;
  5311. };
  5312. /**
  5313. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5314. */
  5315. Matrix.Compose = function (scale, rotation, translation) {
  5316. var result = Matrix.Identity();
  5317. Matrix.ComposeToRef(scale, rotation, translation, result);
  5318. return result;
  5319. };
  5320. /**
  5321. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5322. */
  5323. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5324. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5325. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5326. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5327. result.setTranslation(translation);
  5328. };
  5329. /**
  5330. * Returns a new indentity Matrix.
  5331. */
  5332. Matrix.Identity = function () {
  5333. 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);
  5334. };
  5335. /**
  5336. * Sets the passed "result" as an identity matrix.
  5337. */
  5338. Matrix.IdentityToRef = function (result) {
  5339. 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);
  5340. };
  5341. /**
  5342. * Returns a new zero Matrix.
  5343. */
  5344. Matrix.Zero = function () {
  5345. 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);
  5346. };
  5347. /**
  5348. * Returns a new rotation matrix for "angle" radians around the X axis.
  5349. */
  5350. Matrix.RotationX = function (angle) {
  5351. var result = new Matrix();
  5352. Matrix.RotationXToRef(angle, result);
  5353. return result;
  5354. };
  5355. /**
  5356. * Returns a new Matrix as the passed inverted one.
  5357. */
  5358. Matrix.Invert = function (source) {
  5359. var result = new Matrix();
  5360. source.invertToRef(result);
  5361. return result;
  5362. };
  5363. /**
  5364. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5365. */
  5366. Matrix.RotationXToRef = function (angle, result) {
  5367. var s = Math.sin(angle);
  5368. var c = Math.cos(angle);
  5369. result.m[0] = 1.0;
  5370. result.m[15] = 1.0;
  5371. result.m[5] = c;
  5372. result.m[10] = c;
  5373. result.m[9] = -s;
  5374. result.m[6] = s;
  5375. result.m[1] = 0.0;
  5376. result.m[2] = 0.0;
  5377. result.m[3] = 0.0;
  5378. result.m[4] = 0.0;
  5379. result.m[7] = 0.0;
  5380. result.m[8] = 0.0;
  5381. result.m[11] = 0.0;
  5382. result.m[12] = 0.0;
  5383. result.m[13] = 0.0;
  5384. result.m[14] = 0.0;
  5385. result._markAsUpdated();
  5386. };
  5387. /**
  5388. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5389. */
  5390. Matrix.RotationY = function (angle) {
  5391. var result = new Matrix();
  5392. Matrix.RotationYToRef(angle, result);
  5393. return result;
  5394. };
  5395. /**
  5396. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5397. */
  5398. Matrix.RotationYToRef = function (angle, result) {
  5399. var s = Math.sin(angle);
  5400. var c = Math.cos(angle);
  5401. result.m[5] = 1.0;
  5402. result.m[15] = 1.0;
  5403. result.m[0] = c;
  5404. result.m[2] = -s;
  5405. result.m[8] = s;
  5406. result.m[10] = c;
  5407. result.m[1] = 0.0;
  5408. result.m[3] = 0.0;
  5409. result.m[4] = 0.0;
  5410. result.m[6] = 0.0;
  5411. result.m[7] = 0.0;
  5412. result.m[9] = 0.0;
  5413. result.m[11] = 0.0;
  5414. result.m[12] = 0.0;
  5415. result.m[13] = 0.0;
  5416. result.m[14] = 0.0;
  5417. result._markAsUpdated();
  5418. };
  5419. /**
  5420. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5421. */
  5422. Matrix.RotationZ = function (angle) {
  5423. var result = new Matrix();
  5424. Matrix.RotationZToRef(angle, result);
  5425. return result;
  5426. };
  5427. /**
  5428. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5429. */
  5430. Matrix.RotationZToRef = function (angle, result) {
  5431. var s = Math.sin(angle);
  5432. var c = Math.cos(angle);
  5433. result.m[10] = 1.0;
  5434. result.m[15] = 1.0;
  5435. result.m[0] = c;
  5436. result.m[1] = s;
  5437. result.m[4] = -s;
  5438. result.m[5] = c;
  5439. result.m[2] = 0.0;
  5440. result.m[3] = 0.0;
  5441. result.m[6] = 0.0;
  5442. result.m[7] = 0.0;
  5443. result.m[8] = 0.0;
  5444. result.m[9] = 0.0;
  5445. result.m[11] = 0.0;
  5446. result.m[12] = 0.0;
  5447. result.m[13] = 0.0;
  5448. result.m[14] = 0.0;
  5449. result._markAsUpdated();
  5450. };
  5451. /**
  5452. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5453. */
  5454. Matrix.RotationAxis = function (axis, angle) {
  5455. var result = Matrix.Zero();
  5456. Matrix.RotationAxisToRef(axis, angle, result);
  5457. return result;
  5458. };
  5459. /**
  5460. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5461. */
  5462. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5463. var s = Math.sin(-angle);
  5464. var c = Math.cos(-angle);
  5465. var c1 = 1 - c;
  5466. axis.normalize();
  5467. result.m[0] = (axis.x * axis.x) * c1 + c;
  5468. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5469. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5470. result.m[3] = 0.0;
  5471. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5472. result.m[5] = (axis.y * axis.y) * c1 + c;
  5473. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5474. result.m[7] = 0.0;
  5475. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5476. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5477. result.m[10] = (axis.z * axis.z) * c1 + c;
  5478. result.m[11] = 0.0;
  5479. result.m[15] = 1.0;
  5480. result._markAsUpdated();
  5481. };
  5482. /**
  5483. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5484. */
  5485. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5486. var result = new Matrix();
  5487. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5488. return result;
  5489. };
  5490. /**
  5491. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5492. */
  5493. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5494. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5495. this._tempQuaternion.toRotationMatrix(result);
  5496. };
  5497. /**
  5498. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5499. */
  5500. Matrix.Scaling = function (x, y, z) {
  5501. var result = Matrix.Zero();
  5502. Matrix.ScalingToRef(x, y, z, result);
  5503. return result;
  5504. };
  5505. /**
  5506. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5507. */
  5508. Matrix.ScalingToRef = function (x, y, z, result) {
  5509. result.m[0] = x;
  5510. result.m[1] = 0.0;
  5511. result.m[2] = 0.0;
  5512. result.m[3] = 0.0;
  5513. result.m[4] = 0.0;
  5514. result.m[5] = y;
  5515. result.m[6] = 0.0;
  5516. result.m[7] = 0.0;
  5517. result.m[8] = 0.0;
  5518. result.m[9] = 0.0;
  5519. result.m[10] = z;
  5520. result.m[11] = 0.0;
  5521. result.m[12] = 0.0;
  5522. result.m[13] = 0.0;
  5523. result.m[14] = 0.0;
  5524. result.m[15] = 1.0;
  5525. result._markAsUpdated();
  5526. };
  5527. /**
  5528. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5529. */
  5530. Matrix.Translation = function (x, y, z) {
  5531. var result = Matrix.Identity();
  5532. Matrix.TranslationToRef(x, y, z, result);
  5533. return result;
  5534. };
  5535. /**
  5536. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5537. */
  5538. Matrix.TranslationToRef = function (x, y, z, result) {
  5539. 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);
  5540. };
  5541. /**
  5542. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5543. * @param startValue defines the start value
  5544. * @param endValue defines the end value
  5545. * @param gradient defines the gradient factor
  5546. * @returns the new matrix
  5547. */
  5548. Matrix.Lerp = function (startValue, endValue, gradient) {
  5549. var result = Matrix.Zero();
  5550. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5551. return result;
  5552. };
  5553. /**
  5554. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5555. * @param startValue defines the start value
  5556. * @param endValue defines the end value
  5557. * @param gradient defines the gradient factor
  5558. * @param result defines the Matrix object where to store data
  5559. */
  5560. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5561. for (var index = 0; index < 16; index++) {
  5562. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5563. }
  5564. result._markAsUpdated();
  5565. };
  5566. /**
  5567. * Returns a new Matrix whose values are computed by :
  5568. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5569. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5570. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5571. */
  5572. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5573. var startScale = new Vector3(0, 0, 0);
  5574. var startRotation = new Quaternion();
  5575. var startTranslation = new Vector3(0, 0, 0);
  5576. startValue.decompose(startScale, startRotation, startTranslation);
  5577. var endScale = new Vector3(0, 0, 0);
  5578. var endRotation = new Quaternion();
  5579. var endTranslation = new Vector3(0, 0, 0);
  5580. endValue.decompose(endScale, endRotation, endTranslation);
  5581. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5582. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5583. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5584. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5585. };
  5586. /**
  5587. * 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".
  5588. * This methods works for a Left-Handed system.
  5589. */
  5590. Matrix.LookAtLH = function (eye, target, up) {
  5591. var result = Matrix.Zero();
  5592. Matrix.LookAtLHToRef(eye, target, up, result);
  5593. return result;
  5594. };
  5595. /**
  5596. * 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".
  5597. * This methods works for a Left-Handed system.
  5598. */
  5599. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5600. // Z axis
  5601. target.subtractToRef(eye, this._zAxis);
  5602. this._zAxis.normalize();
  5603. // X axis
  5604. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5605. if (this._xAxis.lengthSquared() === 0) {
  5606. this._xAxis.x = 1.0;
  5607. }
  5608. else {
  5609. this._xAxis.normalize();
  5610. }
  5611. // Y axis
  5612. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5613. this._yAxis.normalize();
  5614. // Eye angles
  5615. var ex = -Vector3.Dot(this._xAxis, eye);
  5616. var ey = -Vector3.Dot(this._yAxis, eye);
  5617. var ez = -Vector3.Dot(this._zAxis, eye);
  5618. 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);
  5619. };
  5620. /**
  5621. * 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".
  5622. * This methods works for a Right-Handed system.
  5623. */
  5624. Matrix.LookAtRH = function (eye, target, up) {
  5625. var result = Matrix.Zero();
  5626. Matrix.LookAtRHToRef(eye, target, up, result);
  5627. return result;
  5628. };
  5629. /**
  5630. * 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".
  5631. * This methods works for a Left-Handed system.
  5632. */
  5633. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5634. // Z axis
  5635. eye.subtractToRef(target, this._zAxis);
  5636. this._zAxis.normalize();
  5637. // X axis
  5638. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5639. if (this._xAxis.lengthSquared() === 0) {
  5640. this._xAxis.x = 1.0;
  5641. }
  5642. else {
  5643. this._xAxis.normalize();
  5644. }
  5645. // Y axis
  5646. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5647. this._yAxis.normalize();
  5648. // Eye angles
  5649. var ex = -Vector3.Dot(this._xAxis, eye);
  5650. var ey = -Vector3.Dot(this._yAxis, eye);
  5651. var ez = -Vector3.Dot(this._zAxis, eye);
  5652. 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);
  5653. };
  5654. /**
  5655. * 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.
  5656. */
  5657. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5658. var matrix = Matrix.Zero();
  5659. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5660. return matrix;
  5661. };
  5662. /**
  5663. * 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.
  5664. */
  5665. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5666. var n = znear;
  5667. var f = zfar;
  5668. var a = 2.0 / width;
  5669. var b = 2.0 / height;
  5670. var c = 2.0 / (f - n);
  5671. var d = -(f + n) / (f - n);
  5672. 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);
  5673. };
  5674. /**
  5675. * 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.
  5676. */
  5677. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5678. var matrix = Matrix.Zero();
  5679. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5680. return matrix;
  5681. };
  5682. /**
  5683. * 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.
  5684. */
  5685. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5686. var n = znear;
  5687. var f = zfar;
  5688. var a = 2.0 / (right - left);
  5689. var b = 2.0 / (top - bottom);
  5690. var c = 2.0 / (f - n);
  5691. var d = -(f + n) / (f - n);
  5692. var i0 = (left + right) / (left - right);
  5693. var i1 = (top + bottom) / (bottom - top);
  5694. 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);
  5695. };
  5696. /**
  5697. * 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.
  5698. */
  5699. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5700. var matrix = Matrix.Zero();
  5701. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5702. return matrix;
  5703. };
  5704. /**
  5705. * 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.
  5706. */
  5707. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5708. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5709. result.m[10] *= -1.0;
  5710. };
  5711. /**
  5712. * 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.
  5713. */
  5714. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5715. var matrix = Matrix.Zero();
  5716. var n = znear;
  5717. var f = zfar;
  5718. var a = 2.0 * n / width;
  5719. var b = 2.0 * n / height;
  5720. var c = (f + n) / (f - n);
  5721. var d = -2.0 * f * n / (f - n);
  5722. 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);
  5723. return matrix;
  5724. };
  5725. /**
  5726. * 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.
  5727. */
  5728. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5729. var matrix = Matrix.Zero();
  5730. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5731. return matrix;
  5732. };
  5733. /**
  5734. * 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.
  5735. */
  5736. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5737. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5738. var n = znear;
  5739. var f = zfar;
  5740. var t = 1.0 / (Math.tan(fov * 0.5));
  5741. var a = isVerticalFovFixed ? (t / aspect) : t;
  5742. var b = isVerticalFovFixed ? t : (t * aspect);
  5743. var c = (f + n) / (f - n);
  5744. var d = -2.0 * f * n / (f - n);
  5745. 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);
  5746. };
  5747. /**
  5748. * 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.
  5749. */
  5750. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5751. var matrix = Matrix.Zero();
  5752. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5753. return matrix;
  5754. };
  5755. /**
  5756. * 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.
  5757. */
  5758. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5759. //alternatively this could be expressed as:
  5760. // m = PerspectiveFovLHToRef
  5761. // m[10] *= -1.0;
  5762. // m[11] *= -1.0;
  5763. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5764. var n = znear;
  5765. var f = zfar;
  5766. var t = 1.0 / (Math.tan(fov * 0.5));
  5767. var a = isVerticalFovFixed ? (t / aspect) : t;
  5768. var b = isVerticalFovFixed ? t : (t * aspect);
  5769. var c = -(f + n) / (f - n);
  5770. var d = -2 * f * n / (f - n);
  5771. 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);
  5772. };
  5773. /**
  5774. * 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.
  5775. */
  5776. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5777. if (rightHanded === void 0) { rightHanded = false; }
  5778. var rightHandedFactor = rightHanded ? -1 : 1;
  5779. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5780. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5781. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5782. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5783. var xScale = 2.0 / (leftTan + rightTan);
  5784. var yScale = 2.0 / (upTan + downTan);
  5785. result.m[0] = xScale;
  5786. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5787. result.m[5] = yScale;
  5788. result.m[6] = result.m[7] = 0.0;
  5789. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5790. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5791. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5792. result.m[10] = -zfar / (znear - zfar);
  5793. result.m[11] = 1.0 * rightHandedFactor;
  5794. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5795. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5796. // result.m[14] = (znear * zfar) / (znear - zfar);
  5797. result._markAsUpdated();
  5798. };
  5799. /**
  5800. * Returns the final transformation matrix : world * view * projection * viewport
  5801. */
  5802. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5803. var cw = viewport.width;
  5804. var ch = viewport.height;
  5805. var cx = viewport.x;
  5806. var cy = viewport.y;
  5807. 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);
  5808. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5809. };
  5810. /**
  5811. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5812. */
  5813. Matrix.GetAsMatrix2x2 = function (matrix) {
  5814. return new Float32Array([
  5815. matrix.m[0], matrix.m[1],
  5816. matrix.m[4], matrix.m[5]
  5817. ]);
  5818. };
  5819. /**
  5820. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5821. */
  5822. Matrix.GetAsMatrix3x3 = function (matrix) {
  5823. return new Float32Array([
  5824. matrix.m[0], matrix.m[1], matrix.m[2],
  5825. matrix.m[4], matrix.m[5], matrix.m[6],
  5826. matrix.m[8], matrix.m[9], matrix.m[10]
  5827. ]);
  5828. };
  5829. /**
  5830. * Compute the transpose of the passed Matrix.
  5831. * Returns a new Matrix.
  5832. */
  5833. Matrix.Transpose = function (matrix) {
  5834. var result = new Matrix();
  5835. Matrix.TransposeToRef(matrix, result);
  5836. return result;
  5837. };
  5838. /**
  5839. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5840. */
  5841. Matrix.TransposeToRef = function (matrix, result) {
  5842. result.m[0] = matrix.m[0];
  5843. result.m[1] = matrix.m[4];
  5844. result.m[2] = matrix.m[8];
  5845. result.m[3] = matrix.m[12];
  5846. result.m[4] = matrix.m[1];
  5847. result.m[5] = matrix.m[5];
  5848. result.m[6] = matrix.m[9];
  5849. result.m[7] = matrix.m[13];
  5850. result.m[8] = matrix.m[2];
  5851. result.m[9] = matrix.m[6];
  5852. result.m[10] = matrix.m[10];
  5853. result.m[11] = matrix.m[14];
  5854. result.m[12] = matrix.m[3];
  5855. result.m[13] = matrix.m[7];
  5856. result.m[14] = matrix.m[11];
  5857. result.m[15] = matrix.m[15];
  5858. };
  5859. /**
  5860. * Returns a new Matrix as the reflection matrix across the passed plane.
  5861. */
  5862. Matrix.Reflection = function (plane) {
  5863. var matrix = new Matrix();
  5864. Matrix.ReflectionToRef(plane, matrix);
  5865. return matrix;
  5866. };
  5867. /**
  5868. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5869. */
  5870. Matrix.ReflectionToRef = function (plane, result) {
  5871. plane.normalize();
  5872. var x = plane.normal.x;
  5873. var y = plane.normal.y;
  5874. var z = plane.normal.z;
  5875. var temp = -2 * x;
  5876. var temp2 = -2 * y;
  5877. var temp3 = -2 * z;
  5878. result.m[0] = (temp * x) + 1;
  5879. result.m[1] = temp2 * x;
  5880. result.m[2] = temp3 * x;
  5881. result.m[3] = 0.0;
  5882. result.m[4] = temp * y;
  5883. result.m[5] = (temp2 * y) + 1;
  5884. result.m[6] = temp3 * y;
  5885. result.m[7] = 0.0;
  5886. result.m[8] = temp * z;
  5887. result.m[9] = temp2 * z;
  5888. result.m[10] = (temp3 * z) + 1;
  5889. result.m[11] = 0.0;
  5890. result.m[12] = temp * plane.d;
  5891. result.m[13] = temp2 * plane.d;
  5892. result.m[14] = temp3 * plane.d;
  5893. result.m[15] = 1.0;
  5894. result._markAsUpdated();
  5895. };
  5896. /**
  5897. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5898. */
  5899. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5900. result.m[0] = xaxis.x;
  5901. result.m[1] = xaxis.y;
  5902. result.m[2] = xaxis.z;
  5903. result.m[3] = 0.0;
  5904. result.m[4] = yaxis.x;
  5905. result.m[5] = yaxis.y;
  5906. result.m[6] = yaxis.z;
  5907. result.m[7] = 0.0;
  5908. result.m[8] = zaxis.x;
  5909. result.m[9] = zaxis.y;
  5910. result.m[10] = zaxis.z;
  5911. result.m[11] = 0.0;
  5912. result.m[12] = 0.0;
  5913. result.m[13] = 0.0;
  5914. result.m[14] = 0.0;
  5915. result.m[15] = 1.0;
  5916. result._markAsUpdated();
  5917. };
  5918. /**
  5919. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5920. */
  5921. Matrix.FromQuaternionToRef = function (quat, result) {
  5922. var xx = quat.x * quat.x;
  5923. var yy = quat.y * quat.y;
  5924. var zz = quat.z * quat.z;
  5925. var xy = quat.x * quat.y;
  5926. var zw = quat.z * quat.w;
  5927. var zx = quat.z * quat.x;
  5928. var yw = quat.y * quat.w;
  5929. var yz = quat.y * quat.z;
  5930. var xw = quat.x * quat.w;
  5931. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5932. result.m[1] = 2.0 * (xy + zw);
  5933. result.m[2] = 2.0 * (zx - yw);
  5934. result.m[3] = 0.0;
  5935. result.m[4] = 2.0 * (xy - zw);
  5936. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5937. result.m[6] = 2.0 * (yz + xw);
  5938. result.m[7] = 0.0;
  5939. result.m[8] = 2.0 * (zx + yw);
  5940. result.m[9] = 2.0 * (yz - xw);
  5941. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5942. result.m[11] = 0.0;
  5943. result.m[12] = 0.0;
  5944. result.m[13] = 0.0;
  5945. result.m[14] = 0.0;
  5946. result.m[15] = 1.0;
  5947. result._markAsUpdated();
  5948. };
  5949. Matrix._tempQuaternion = new Quaternion();
  5950. Matrix._xAxis = Vector3.Zero();
  5951. Matrix._yAxis = Vector3.Zero();
  5952. Matrix._zAxis = Vector3.Zero();
  5953. Matrix._updateFlagSeed = 0;
  5954. Matrix._identityReadOnly = Matrix.Identity();
  5955. return Matrix;
  5956. }());
  5957. BABYLON.Matrix = Matrix;
  5958. var Plane = /** @class */ (function () {
  5959. /**
  5960. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5961. */
  5962. function Plane(a, b, c, d) {
  5963. this.normal = new Vector3(a, b, c);
  5964. this.d = d;
  5965. }
  5966. /**
  5967. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5968. */
  5969. Plane.prototype.asArray = function () {
  5970. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5971. };
  5972. // Methods
  5973. /**
  5974. * Returns a new plane copied from the current Plane.
  5975. */
  5976. Plane.prototype.clone = function () {
  5977. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5978. };
  5979. /**
  5980. * Returns the string "Plane".
  5981. */
  5982. Plane.prototype.getClassName = function () {
  5983. return "Plane";
  5984. };
  5985. /**
  5986. * Returns the Plane hash code.
  5987. */
  5988. Plane.prototype.getHashCode = function () {
  5989. var hash = this.normal.getHashCode();
  5990. hash = (hash * 397) ^ (this.d || 0);
  5991. return hash;
  5992. };
  5993. /**
  5994. * Normalize the current Plane in place.
  5995. * Returns the updated Plane.
  5996. */
  5997. Plane.prototype.normalize = function () {
  5998. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5999. var magnitude = 0.0;
  6000. if (norm !== 0) {
  6001. magnitude = 1.0 / norm;
  6002. }
  6003. this.normal.x *= magnitude;
  6004. this.normal.y *= magnitude;
  6005. this.normal.z *= magnitude;
  6006. this.d *= magnitude;
  6007. return this;
  6008. };
  6009. /**
  6010. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6011. */
  6012. Plane.prototype.transform = function (transformation) {
  6013. var transposedMatrix = Matrix.Transpose(transformation);
  6014. var x = this.normal.x;
  6015. var y = this.normal.y;
  6016. var z = this.normal.z;
  6017. var d = this.d;
  6018. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6019. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6020. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6021. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6022. return new Plane(normalX, normalY, normalZ, finalD);
  6023. };
  6024. /**
  6025. * Returns the dot product (float) of the point coordinates and the plane normal.
  6026. */
  6027. Plane.prototype.dotCoordinate = function (point) {
  6028. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6029. };
  6030. /**
  6031. * Updates the current Plane from the plane defined by the three passed points.
  6032. * Returns the updated Plane.
  6033. */
  6034. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6035. var x1 = point2.x - point1.x;
  6036. var y1 = point2.y - point1.y;
  6037. var z1 = point2.z - point1.z;
  6038. var x2 = point3.x - point1.x;
  6039. var y2 = point3.y - point1.y;
  6040. var z2 = point3.z - point1.z;
  6041. var yz = (y1 * z2) - (z1 * y2);
  6042. var xz = (z1 * x2) - (x1 * z2);
  6043. var xy = (x1 * y2) - (y1 * x2);
  6044. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6045. var invPyth;
  6046. if (pyth !== 0) {
  6047. invPyth = 1.0 / pyth;
  6048. }
  6049. else {
  6050. invPyth = 0.0;
  6051. }
  6052. this.normal.x = yz * invPyth;
  6053. this.normal.y = xz * invPyth;
  6054. this.normal.z = xy * invPyth;
  6055. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6056. return this;
  6057. };
  6058. /**
  6059. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6060. */
  6061. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6062. var dot = Vector3.Dot(this.normal, direction);
  6063. return (dot <= epsilon);
  6064. };
  6065. /**
  6066. * Returns the signed distance (float) from the passed point to the Plane.
  6067. */
  6068. Plane.prototype.signedDistanceTo = function (point) {
  6069. return Vector3.Dot(point, this.normal) + this.d;
  6070. };
  6071. // Statics
  6072. /**
  6073. * Returns a new Plane from the passed array.
  6074. */
  6075. Plane.FromArray = function (array) {
  6076. return new Plane(array[0], array[1], array[2], array[3]);
  6077. };
  6078. /**
  6079. * Returns a new Plane defined by the three passed points.
  6080. */
  6081. Plane.FromPoints = function (point1, point2, point3) {
  6082. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6083. result.copyFromPoints(point1, point2, point3);
  6084. return result;
  6085. };
  6086. /**
  6087. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6088. * Note : the vector "normal" is updated because normalized.
  6089. */
  6090. Plane.FromPositionAndNormal = function (origin, normal) {
  6091. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6092. normal.normalize();
  6093. result.normal = normal;
  6094. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6095. return result;
  6096. };
  6097. /**
  6098. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6099. */
  6100. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6101. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6102. return Vector3.Dot(point, normal) + d;
  6103. };
  6104. return Plane;
  6105. }());
  6106. BABYLON.Plane = Plane;
  6107. var Viewport = /** @class */ (function () {
  6108. /**
  6109. * Creates a Viewport object located at (x, y) and sized (width, height).
  6110. */
  6111. function Viewport(x, y, width, height) {
  6112. this.x = x;
  6113. this.y = y;
  6114. this.width = width;
  6115. this.height = height;
  6116. }
  6117. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6118. if (renderWidthOrEngine.getRenderWidth) {
  6119. var engine = renderWidthOrEngine;
  6120. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6121. }
  6122. var renderWidth = renderWidthOrEngine;
  6123. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6124. };
  6125. /**
  6126. * Returns a new Viewport copied from the current one.
  6127. */
  6128. Viewport.prototype.clone = function () {
  6129. return new Viewport(this.x, this.y, this.width, this.height);
  6130. };
  6131. return Viewport;
  6132. }());
  6133. BABYLON.Viewport = Viewport;
  6134. var Frustum = /** @class */ (function () {
  6135. function Frustum() {
  6136. }
  6137. /**
  6138. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6139. */
  6140. Frustum.GetPlanes = function (transform) {
  6141. var frustumPlanes = [];
  6142. for (var index = 0; index < 6; index++) {
  6143. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6144. }
  6145. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6146. return frustumPlanes;
  6147. };
  6148. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6149. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6150. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6151. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6152. frustumPlane.d = transform.m[15] + transform.m[14];
  6153. frustumPlane.normalize();
  6154. };
  6155. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6156. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6157. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6158. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6159. frustumPlane.d = transform.m[15] - transform.m[14];
  6160. frustumPlane.normalize();
  6161. };
  6162. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6163. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6164. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6165. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6166. frustumPlane.d = transform.m[15] + transform.m[12];
  6167. frustumPlane.normalize();
  6168. };
  6169. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6170. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6171. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6172. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6173. frustumPlane.d = transform.m[15] - transform.m[12];
  6174. frustumPlane.normalize();
  6175. };
  6176. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6177. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6178. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6179. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6180. frustumPlane.d = transform.m[15] - transform.m[13];
  6181. frustumPlane.normalize();
  6182. };
  6183. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6184. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6185. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6186. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6187. frustumPlane.d = transform.m[15] + transform.m[13];
  6188. frustumPlane.normalize();
  6189. };
  6190. /**
  6191. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6192. */
  6193. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6194. // Near
  6195. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6196. // Far
  6197. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6198. // Left
  6199. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6200. // Right
  6201. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6202. // Top
  6203. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6204. // Bottom
  6205. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6206. };
  6207. return Frustum;
  6208. }());
  6209. BABYLON.Frustum = Frustum;
  6210. var Space;
  6211. (function (Space) {
  6212. Space[Space["LOCAL"] = 0] = "LOCAL";
  6213. Space[Space["WORLD"] = 1] = "WORLD";
  6214. Space[Space["BONE"] = 2] = "BONE";
  6215. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6216. var Axis = /** @class */ (function () {
  6217. function Axis() {
  6218. }
  6219. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6220. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6221. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6222. return Axis;
  6223. }());
  6224. BABYLON.Axis = Axis;
  6225. ;
  6226. var BezierCurve = /** @class */ (function () {
  6227. function BezierCurve() {
  6228. }
  6229. /**
  6230. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6231. */
  6232. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6233. // Extract X (which is equal to time here)
  6234. var f0 = 1 - 3 * x2 + 3 * x1;
  6235. var f1 = 3 * x2 - 6 * x1;
  6236. var f2 = 3 * x1;
  6237. var refinedT = t;
  6238. for (var i = 0; i < 5; i++) {
  6239. var refinedT2 = refinedT * refinedT;
  6240. var refinedT3 = refinedT2 * refinedT;
  6241. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6242. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6243. refinedT -= (x - t) * slope;
  6244. refinedT = Math.min(1, Math.max(0, refinedT));
  6245. }
  6246. // Resolve cubic bezier for the given x
  6247. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6248. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6249. Math.pow(refinedT, 3);
  6250. };
  6251. return BezierCurve;
  6252. }());
  6253. BABYLON.BezierCurve = BezierCurve;
  6254. var Orientation;
  6255. (function (Orientation) {
  6256. Orientation[Orientation["CW"] = 0] = "CW";
  6257. Orientation[Orientation["CCW"] = 1] = "CCW";
  6258. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6259. var Angle = /** @class */ (function () {
  6260. /**
  6261. * Creates an Angle object of "radians" radians (float).
  6262. */
  6263. function Angle(radians) {
  6264. var _this = this;
  6265. /**
  6266. * Returns the Angle value in degrees (float).
  6267. */
  6268. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6269. /**
  6270. * Returns the Angle value in radians (float).
  6271. */
  6272. this.radians = function () { return _this._radians; };
  6273. this._radians = radians;
  6274. if (this._radians < 0.0)
  6275. this._radians += (2.0 * Math.PI);
  6276. }
  6277. /**
  6278. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6279. */
  6280. Angle.BetweenTwoPoints = function (a, b) {
  6281. var delta = b.subtract(a);
  6282. var theta = Math.atan2(delta.y, delta.x);
  6283. return new Angle(theta);
  6284. };
  6285. /**
  6286. * Returns a new Angle object from the passed float in radians.
  6287. */
  6288. Angle.FromRadians = function (radians) {
  6289. return new Angle(radians);
  6290. };
  6291. /**
  6292. * Returns a new Angle object from the passed float in degrees.
  6293. */
  6294. Angle.FromDegrees = function (degrees) {
  6295. return new Angle(degrees * Math.PI / 180.0);
  6296. };
  6297. return Angle;
  6298. }());
  6299. BABYLON.Angle = Angle;
  6300. var Arc2 = /** @class */ (function () {
  6301. /**
  6302. * Creates an Arc object from the three passed points : start, middle and end.
  6303. */
  6304. function Arc2(startPoint, midPoint, endPoint) {
  6305. this.startPoint = startPoint;
  6306. this.midPoint = midPoint;
  6307. this.endPoint = endPoint;
  6308. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6309. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6310. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6311. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6312. 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);
  6313. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6314. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6315. var a1 = this.startAngle.degrees();
  6316. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6317. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6318. // angles correction
  6319. if (a2 - a1 > +180.0)
  6320. a2 -= 360.0;
  6321. if (a2 - a1 < -180.0)
  6322. a2 += 360.0;
  6323. if (a3 - a2 > +180.0)
  6324. a3 -= 360.0;
  6325. if (a3 - a2 < -180.0)
  6326. a3 += 360.0;
  6327. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6328. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6329. }
  6330. return Arc2;
  6331. }());
  6332. BABYLON.Arc2 = Arc2;
  6333. var Path2 = /** @class */ (function () {
  6334. /**
  6335. * Creates a Path2 object from the starting 2D coordinates x and y.
  6336. */
  6337. function Path2(x, y) {
  6338. this._points = new Array();
  6339. this._length = 0.0;
  6340. this.closed = false;
  6341. this._points.push(new Vector2(x, y));
  6342. }
  6343. /**
  6344. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6345. * Returns the updated Path2.
  6346. */
  6347. Path2.prototype.addLineTo = function (x, y) {
  6348. if (this.closed) {
  6349. return this;
  6350. }
  6351. var newPoint = new Vector2(x, y);
  6352. var previousPoint = this._points[this._points.length - 1];
  6353. this._points.push(newPoint);
  6354. this._length += newPoint.subtract(previousPoint).length();
  6355. return this;
  6356. };
  6357. /**
  6358. * 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.
  6359. * Returns the updated Path2.
  6360. */
  6361. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6362. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6363. if (this.closed) {
  6364. return this;
  6365. }
  6366. var startPoint = this._points[this._points.length - 1];
  6367. var midPoint = new Vector2(midX, midY);
  6368. var endPoint = new Vector2(endX, endY);
  6369. var arc = new Arc2(startPoint, midPoint, endPoint);
  6370. var increment = arc.angle.radians() / numberOfSegments;
  6371. if (arc.orientation === Orientation.CW)
  6372. increment *= -1;
  6373. var currentAngle = arc.startAngle.radians() + increment;
  6374. for (var i = 0; i < numberOfSegments; i++) {
  6375. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6376. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6377. this.addLineTo(x, y);
  6378. currentAngle += increment;
  6379. }
  6380. return this;
  6381. };
  6382. /**
  6383. * Closes the Path2.
  6384. * Returns the Path2.
  6385. */
  6386. Path2.prototype.close = function () {
  6387. this.closed = true;
  6388. return this;
  6389. };
  6390. /**
  6391. * Returns the Path2 total length (float).
  6392. */
  6393. Path2.prototype.length = function () {
  6394. var result = this._length;
  6395. if (!this.closed) {
  6396. var lastPoint = this._points[this._points.length - 1];
  6397. var firstPoint = this._points[0];
  6398. result += (firstPoint.subtract(lastPoint).length());
  6399. }
  6400. return result;
  6401. };
  6402. /**
  6403. * Returns the Path2 internal array of points.
  6404. */
  6405. Path2.prototype.getPoints = function () {
  6406. return this._points;
  6407. };
  6408. /**
  6409. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6410. */
  6411. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6412. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6413. return Vector2.Zero();
  6414. }
  6415. var lengthPosition = normalizedLengthPosition * this.length();
  6416. var previousOffset = 0;
  6417. for (var i = 0; i < this._points.length; i++) {
  6418. var j = (i + 1) % this._points.length;
  6419. var a = this._points[i];
  6420. var b = this._points[j];
  6421. var bToA = b.subtract(a);
  6422. var nextOffset = (bToA.length() + previousOffset);
  6423. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6424. var dir = bToA.normalize();
  6425. var localOffset = lengthPosition - previousOffset;
  6426. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6427. }
  6428. previousOffset = nextOffset;
  6429. }
  6430. return Vector2.Zero();
  6431. };
  6432. /**
  6433. * Returns a new Path2 starting at the coordinates (x, y).
  6434. */
  6435. Path2.StartingAt = function (x, y) {
  6436. return new Path2(x, y);
  6437. };
  6438. return Path2;
  6439. }());
  6440. BABYLON.Path2 = Path2;
  6441. var Path3D = /** @class */ (function () {
  6442. /**
  6443. * new Path3D(path, normal, raw)
  6444. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6445. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6446. * path : an array of Vector3, the curve axis of the Path3D
  6447. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6448. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6449. */
  6450. function Path3D(path, firstNormal, raw) {
  6451. if (firstNormal === void 0) { firstNormal = null; }
  6452. this.path = path;
  6453. this._curve = new Array();
  6454. this._distances = new Array();
  6455. this._tangents = new Array();
  6456. this._normals = new Array();
  6457. this._binormals = new Array();
  6458. for (var p = 0; p < path.length; p++) {
  6459. this._curve[p] = path[p].clone(); // hard copy
  6460. }
  6461. this._raw = raw || false;
  6462. this._compute(firstNormal);
  6463. }
  6464. /**
  6465. * Returns the Path3D array of successive Vector3 designing its curve.
  6466. */
  6467. Path3D.prototype.getCurve = function () {
  6468. return this._curve;
  6469. };
  6470. /**
  6471. * Returns an array populated with tangent vectors on each Path3D curve point.
  6472. */
  6473. Path3D.prototype.getTangents = function () {
  6474. return this._tangents;
  6475. };
  6476. /**
  6477. * Returns an array populated with normal vectors on each Path3D curve point.
  6478. */
  6479. Path3D.prototype.getNormals = function () {
  6480. return this._normals;
  6481. };
  6482. /**
  6483. * Returns an array populated with binormal vectors on each Path3D curve point.
  6484. */
  6485. Path3D.prototype.getBinormals = function () {
  6486. return this._binormals;
  6487. };
  6488. /**
  6489. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6490. */
  6491. Path3D.prototype.getDistances = function () {
  6492. return this._distances;
  6493. };
  6494. /**
  6495. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6496. * Returns the same object updated.
  6497. */
  6498. Path3D.prototype.update = function (path, firstNormal) {
  6499. if (firstNormal === void 0) { firstNormal = null; }
  6500. for (var p = 0; p < path.length; p++) {
  6501. this._curve[p].x = path[p].x;
  6502. this._curve[p].y = path[p].y;
  6503. this._curve[p].z = path[p].z;
  6504. }
  6505. this._compute(firstNormal);
  6506. return this;
  6507. };
  6508. // private function compute() : computes tangents, normals and binormals
  6509. Path3D.prototype._compute = function (firstNormal) {
  6510. var l = this._curve.length;
  6511. // first and last tangents
  6512. this._tangents[0] = this._getFirstNonNullVector(0);
  6513. if (!this._raw) {
  6514. this._tangents[0].normalize();
  6515. }
  6516. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6517. if (!this._raw) {
  6518. this._tangents[l - 1].normalize();
  6519. }
  6520. // normals and binormals at first point : arbitrary vector with _normalVector()
  6521. var tg0 = this._tangents[0];
  6522. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6523. this._normals[0] = pp0;
  6524. if (!this._raw) {
  6525. this._normals[0].normalize();
  6526. }
  6527. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6528. if (!this._raw) {
  6529. this._binormals[0].normalize();
  6530. }
  6531. this._distances[0] = 0.0;
  6532. // normals and binormals : next points
  6533. var prev; // previous vector (segment)
  6534. var cur; // current vector (segment)
  6535. var curTang; // current tangent
  6536. // previous normal
  6537. var prevBinor; // previous binormal
  6538. for (var i = 1; i < l; i++) {
  6539. // tangents
  6540. prev = this._getLastNonNullVector(i);
  6541. if (i < l - 1) {
  6542. cur = this._getFirstNonNullVector(i);
  6543. this._tangents[i] = prev.add(cur);
  6544. this._tangents[i].normalize();
  6545. }
  6546. this._distances[i] = this._distances[i - 1] + prev.length();
  6547. // normals and binormals
  6548. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6549. curTang = this._tangents[i];
  6550. prevBinor = this._binormals[i - 1];
  6551. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6552. if (!this._raw) {
  6553. this._normals[i].normalize();
  6554. }
  6555. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6556. if (!this._raw) {
  6557. this._binormals[i].normalize();
  6558. }
  6559. }
  6560. };
  6561. // private function getFirstNonNullVector(index)
  6562. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6563. Path3D.prototype._getFirstNonNullVector = function (index) {
  6564. var i = 1;
  6565. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6566. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6567. i++;
  6568. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6569. }
  6570. return nNVector;
  6571. };
  6572. // private function getLastNonNullVector(index)
  6573. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6574. Path3D.prototype._getLastNonNullVector = function (index) {
  6575. var i = 1;
  6576. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6577. while (nLVector.length() === 0 && index > i + 1) {
  6578. i++;
  6579. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6580. }
  6581. return nLVector;
  6582. };
  6583. // private function normalVector(v0, vt, va) :
  6584. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6585. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6586. Path3D.prototype._normalVector = function (v0, vt, va) {
  6587. var normal0;
  6588. var tgl = vt.length();
  6589. if (tgl === 0.0) {
  6590. tgl = 1.0;
  6591. }
  6592. if (va === undefined || va === null) {
  6593. var point;
  6594. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6595. point = new Vector3(0.0, -1.0, 0.0);
  6596. }
  6597. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6598. point = new Vector3(1.0, 0.0, 0.0);
  6599. }
  6600. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6601. point = new Vector3(0.0, 0.0, 1.0);
  6602. }
  6603. else {
  6604. point = Vector3.Zero();
  6605. }
  6606. normal0 = Vector3.Cross(vt, point);
  6607. }
  6608. else {
  6609. normal0 = Vector3.Cross(vt, va);
  6610. Vector3.CrossToRef(normal0, vt, normal0);
  6611. }
  6612. normal0.normalize();
  6613. return normal0;
  6614. };
  6615. return Path3D;
  6616. }());
  6617. BABYLON.Path3D = Path3D;
  6618. var Curve3 = /** @class */ (function () {
  6619. /**
  6620. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6621. * A Curve3 is designed from a series of successive Vector3.
  6622. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6623. */
  6624. function Curve3(points) {
  6625. this._length = 0.0;
  6626. this._points = points;
  6627. this._length = this._computeLength(points);
  6628. }
  6629. /**
  6630. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6631. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6632. * @param v1 (Vector3) the control point
  6633. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6634. * @param nbPoints (integer) the wanted number of points in the curve
  6635. */
  6636. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6637. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6638. var bez = new Array();
  6639. var equation = function (t, val0, val1, val2) {
  6640. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6641. return res;
  6642. };
  6643. for (var i = 0; i <= nbPoints; i++) {
  6644. 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)));
  6645. }
  6646. return new Curve3(bez);
  6647. };
  6648. /**
  6649. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6650. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6651. * @param v1 (Vector3) the first control point
  6652. * @param v2 (Vector3) the second control point
  6653. * @param v3 (Vector3) the end point of the Cubic Bezier
  6654. * @param nbPoints (integer) the wanted number of points in the curve
  6655. */
  6656. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6657. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6658. var bez = new Array();
  6659. var equation = function (t, val0, val1, val2, val3) {
  6660. 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;
  6661. return res;
  6662. };
  6663. for (var i = 0; i <= nbPoints; i++) {
  6664. 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)));
  6665. }
  6666. return new Curve3(bez);
  6667. };
  6668. /**
  6669. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6670. * @param p1 (Vector3) the origin point of the Hermite Spline
  6671. * @param t1 (Vector3) the tangent vector at the origin point
  6672. * @param p2 (Vector3) the end point of the Hermite Spline
  6673. * @param t2 (Vector3) the tangent vector at the end point
  6674. * @param nbPoints (integer) the wanted number of points in the curve
  6675. */
  6676. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6677. var hermite = new Array();
  6678. var step = 1.0 / nbPoints;
  6679. for (var i = 0; i <= nbPoints; i++) {
  6680. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6681. }
  6682. return new Curve3(hermite);
  6683. };
  6684. /**
  6685. * Returns a Curve3 object along a CatmullRom Spline curve :
  6686. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6687. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6688. */
  6689. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6690. var totalPoints = new Array();
  6691. totalPoints.push(points[0].clone());
  6692. Array.prototype.push.apply(totalPoints, points);
  6693. totalPoints.push(points[points.length - 1].clone());
  6694. var catmullRom = new Array();
  6695. var step = 1.0 / nbPoints;
  6696. var amount = 0.0;
  6697. for (var i = 0; i < totalPoints.length - 3; i++) {
  6698. amount = 0;
  6699. for (var c = 0; c < nbPoints; c++) {
  6700. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6701. amount += step;
  6702. }
  6703. }
  6704. i--;
  6705. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6706. return new Curve3(catmullRom);
  6707. };
  6708. /**
  6709. * Returns the Curve3 stored array of successive Vector3
  6710. */
  6711. Curve3.prototype.getPoints = function () {
  6712. return this._points;
  6713. };
  6714. /**
  6715. * Returns the computed length (float) of the curve.
  6716. */
  6717. Curve3.prototype.length = function () {
  6718. return this._length;
  6719. };
  6720. /**
  6721. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6722. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6723. * curveA and curveB keep unchanged.
  6724. */
  6725. Curve3.prototype.continue = function (curve) {
  6726. var lastPoint = this._points[this._points.length - 1];
  6727. var continuedPoints = this._points.slice();
  6728. var curvePoints = curve.getPoints();
  6729. for (var i = 1; i < curvePoints.length; i++) {
  6730. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6731. }
  6732. var continuedCurve = new Curve3(continuedPoints);
  6733. return continuedCurve;
  6734. };
  6735. Curve3.prototype._computeLength = function (path) {
  6736. var l = 0;
  6737. for (var i = 1; i < path.length; i++) {
  6738. l += (path[i].subtract(path[i - 1])).length();
  6739. }
  6740. return l;
  6741. };
  6742. return Curve3;
  6743. }());
  6744. BABYLON.Curve3 = Curve3;
  6745. // Vertex formats
  6746. var PositionNormalVertex = /** @class */ (function () {
  6747. function PositionNormalVertex(position, normal) {
  6748. if (position === void 0) { position = Vector3.Zero(); }
  6749. if (normal === void 0) { normal = Vector3.Up(); }
  6750. this.position = position;
  6751. this.normal = normal;
  6752. }
  6753. PositionNormalVertex.prototype.clone = function () {
  6754. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6755. };
  6756. return PositionNormalVertex;
  6757. }());
  6758. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6759. var PositionNormalTextureVertex = /** @class */ (function () {
  6760. function PositionNormalTextureVertex(position, normal, uv) {
  6761. if (position === void 0) { position = Vector3.Zero(); }
  6762. if (normal === void 0) { normal = Vector3.Up(); }
  6763. if (uv === void 0) { uv = Vector2.Zero(); }
  6764. this.position = position;
  6765. this.normal = normal;
  6766. this.uv = uv;
  6767. }
  6768. PositionNormalTextureVertex.prototype.clone = function () {
  6769. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6770. };
  6771. return PositionNormalTextureVertex;
  6772. }());
  6773. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6774. // Temporary pre-allocated objects for engine internal use
  6775. // usage in any internal function :
  6776. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6777. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6778. var Tmp = /** @class */ (function () {
  6779. function Tmp() {
  6780. }
  6781. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6782. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6783. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6784. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6785. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6786. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6787. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6788. Matrix.Zero(), Matrix.Zero(),
  6789. Matrix.Zero(), Matrix.Zero(),
  6790. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6791. return Tmp;
  6792. }());
  6793. BABYLON.Tmp = Tmp;
  6794. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6795. var MathTmp = /** @class */ (function () {
  6796. function MathTmp() {
  6797. }
  6798. MathTmp.Vector3 = [Vector3.Zero()];
  6799. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6800. MathTmp.Quaternion = [Quaternion.Zero()];
  6801. return MathTmp;
  6802. }());
  6803. })(BABYLON || (BABYLON = {}));
  6804. //# sourceMappingURL=babylon.math.js.map
  6805. "use strict";
  6806. var BABYLON;
  6807. (function (BABYLON) {
  6808. var Scalar = /** @class */ (function () {
  6809. function Scalar() {
  6810. }
  6811. /**
  6812. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6813. */
  6814. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6815. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6816. var num = a - b;
  6817. return -epsilon <= num && num <= epsilon;
  6818. };
  6819. /**
  6820. * Returns a string : the upper case translation of the number i to hexadecimal.
  6821. */
  6822. Scalar.ToHex = function (i) {
  6823. var str = i.toString(16);
  6824. if (i <= 15) {
  6825. return ("0" + str).toUpperCase();
  6826. }
  6827. return str.toUpperCase();
  6828. };
  6829. /**
  6830. * Returns -1 if value is negative and +1 is value is positive.
  6831. * Returns the value itself if it's equal to zero.
  6832. */
  6833. Scalar.Sign = function (value) {
  6834. value = +value; // convert to a number
  6835. if (value === 0 || isNaN(value))
  6836. return value;
  6837. return value > 0 ? 1 : -1;
  6838. };
  6839. /**
  6840. * Returns the value itself if it's between min and max.
  6841. * Returns min if the value is lower than min.
  6842. * Returns max if the value is greater than max.
  6843. */
  6844. Scalar.Clamp = function (value, min, max) {
  6845. if (min === void 0) { min = 0; }
  6846. if (max === void 0) { max = 1; }
  6847. return Math.min(max, Math.max(min, value));
  6848. };
  6849. /**
  6850. * Returns the log2 of value.
  6851. */
  6852. Scalar.Log2 = function (value) {
  6853. return Math.log(value) * Math.LOG2E;
  6854. };
  6855. /**
  6856. * Loops the value, so that it is never larger than length and never smaller than 0.
  6857. *
  6858. * This is similar to the modulo operator but it works with floating point numbers.
  6859. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6860. * With t = 5 and length = 2.5, the result would be 0.0.
  6861. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6862. */
  6863. Scalar.Repeat = function (value, length) {
  6864. return value - Math.floor(value / length) * length;
  6865. };
  6866. /**
  6867. * Normalize the value between 0.0 and 1.0 using min and max values
  6868. */
  6869. Scalar.Normalize = function (value, min, max) {
  6870. return (value - min) / (max - min);
  6871. };
  6872. /**
  6873. * Denormalize the value from 0.0 and 1.0 using min and max values
  6874. */
  6875. Scalar.Denormalize = function (normalized, min, max) {
  6876. return (normalized * (max - min) + min);
  6877. };
  6878. /**
  6879. * Calculates the shortest difference between two given angles given in degrees.
  6880. */
  6881. Scalar.DeltaAngle = function (current, target) {
  6882. var num = Scalar.Repeat(target - current, 360.0);
  6883. if (num > 180.0) {
  6884. num -= 360.0;
  6885. }
  6886. return num;
  6887. };
  6888. /**
  6889. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6890. *
  6891. * The returned value will move back and forth between 0 and length
  6892. */
  6893. Scalar.PingPong = function (tx, length) {
  6894. var t = Scalar.Repeat(tx, length * 2.0);
  6895. return length - Math.abs(t - length);
  6896. };
  6897. /**
  6898. * Interpolates between min and max with smoothing at the limits.
  6899. *
  6900. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6901. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6902. */
  6903. Scalar.SmoothStep = function (from, to, tx) {
  6904. var t = Scalar.Clamp(tx);
  6905. t = -2.0 * t * t * t + 3.0 * t * t;
  6906. return to * t + from * (1.0 - t);
  6907. };
  6908. /**
  6909. * Moves a value current towards target.
  6910. *
  6911. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6912. * Negative values of maxDelta pushes the value away from target.
  6913. */
  6914. Scalar.MoveTowards = function (current, target, maxDelta) {
  6915. var result = 0;
  6916. if (Math.abs(target - current) <= maxDelta) {
  6917. result = target;
  6918. }
  6919. else {
  6920. result = current + Scalar.Sign(target - current) * maxDelta;
  6921. }
  6922. return result;
  6923. };
  6924. /**
  6925. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6926. *
  6927. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6928. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6929. */
  6930. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6931. var num = Scalar.DeltaAngle(current, target);
  6932. var result = 0;
  6933. if (-maxDelta < num && num < maxDelta) {
  6934. result = target;
  6935. }
  6936. else {
  6937. target = current + num;
  6938. result = Scalar.MoveTowards(current, target, maxDelta);
  6939. }
  6940. return result;
  6941. };
  6942. /**
  6943. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6944. */
  6945. Scalar.Lerp = function (start, end, amount) {
  6946. return start + ((end - start) * amount);
  6947. };
  6948. /**
  6949. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6950. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6951. */
  6952. Scalar.LerpAngle = function (start, end, amount) {
  6953. var num = Scalar.Repeat(end - start, 360.0);
  6954. if (num > 180.0) {
  6955. num -= 360.0;
  6956. }
  6957. return start + num * Scalar.Clamp(amount);
  6958. };
  6959. /**
  6960. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6961. */
  6962. Scalar.InverseLerp = function (a, b, value) {
  6963. var result = 0;
  6964. if (a != b) {
  6965. result = Scalar.Clamp((value - a) / (b - a));
  6966. }
  6967. else {
  6968. result = 0.0;
  6969. }
  6970. return result;
  6971. };
  6972. /**
  6973. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6974. */
  6975. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6976. var squared = amount * amount;
  6977. var cubed = amount * squared;
  6978. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6979. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6980. var part3 = (cubed - (2.0 * squared)) + amount;
  6981. var part4 = cubed - squared;
  6982. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6983. };
  6984. /**
  6985. * Returns a random float number between and min and max values
  6986. */
  6987. Scalar.RandomRange = function (min, max) {
  6988. if (min === max)
  6989. return min;
  6990. return ((Math.random() * (max - min)) + min);
  6991. };
  6992. /**
  6993. * This function returns percentage of a number in a given range.
  6994. *
  6995. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6996. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6997. */
  6998. Scalar.RangeToPercent = function (number, min, max) {
  6999. return ((number - min) / (max - min));
  7000. };
  7001. /**
  7002. * This function returns number that corresponds to the percentage in a given range.
  7003. *
  7004. * PercentToRange(0.34,0,100) will return 34.
  7005. */
  7006. Scalar.PercentToRange = function (percent, min, max) {
  7007. return ((max - min) * percent + min);
  7008. };
  7009. /**
  7010. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7011. * @param angle The angle to normalize in radian.
  7012. * @return The converted angle.
  7013. */
  7014. Scalar.NormalizeRadians = function (angle) {
  7015. // More precise but slower version kept for reference.
  7016. // angle = angle % Tools.TwoPi;
  7017. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7018. //if (angle > Math.PI) {
  7019. // angle -= Tools.TwoPi;
  7020. //}
  7021. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7022. return angle;
  7023. };
  7024. /**
  7025. * Two pi constants convenient for computation.
  7026. */
  7027. Scalar.TwoPi = Math.PI * 2;
  7028. return Scalar;
  7029. }());
  7030. BABYLON.Scalar = Scalar;
  7031. })(BABYLON || (BABYLON = {}));
  7032. //# sourceMappingURL=babylon.math.scalar.js.map
  7033. "use strict";
  7034. //# sourceMappingURL=babylon.mixins.js.map
  7035. "use strict";
  7036. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7037. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7038. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7039. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7040. //# sourceMappingURL=babylon.webgl2.js.map
  7041. "use strict";
  7042. var BABYLON;
  7043. (function (BABYLON) {
  7044. var __decoratorInitialStore = {};
  7045. var __mergedStore = {};
  7046. var _copySource = function (creationFunction, source, instanciate) {
  7047. var destination = creationFunction();
  7048. // Tags
  7049. if (BABYLON.Tags) {
  7050. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7051. }
  7052. var classStore = getMergedStore(destination);
  7053. // Properties
  7054. for (var property in classStore) {
  7055. var propertyDescriptor = classStore[property];
  7056. var sourceProperty = source[property];
  7057. var propertyType = propertyDescriptor.type;
  7058. if (sourceProperty !== undefined && sourceProperty !== null) {
  7059. switch (propertyType) {
  7060. case 0: // Value
  7061. case 6:// Mesh reference
  7062. destination[property] = sourceProperty;
  7063. break;
  7064. case 1:// Texture
  7065. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7066. break;
  7067. case 2: // Color3
  7068. case 3: // FresnelParameters
  7069. case 4: // Vector2
  7070. case 5: // Vector3
  7071. case 7: // Color Curves
  7072. case 10:// Quaternion
  7073. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7074. break;
  7075. }
  7076. }
  7077. }
  7078. return destination;
  7079. };
  7080. function getDirectStore(target) {
  7081. var classKey = target.getClassName();
  7082. if (!__decoratorInitialStore[classKey]) {
  7083. __decoratorInitialStore[classKey] = {};
  7084. }
  7085. return __decoratorInitialStore[classKey];
  7086. }
  7087. /**
  7088. * Return the list of properties flagged as serializable
  7089. * @param target: host object
  7090. */
  7091. function getMergedStore(target) {
  7092. var classKey = target.getClassName();
  7093. if (__mergedStore[classKey]) {
  7094. return __mergedStore[classKey];
  7095. }
  7096. __mergedStore[classKey] = {};
  7097. var store = __mergedStore[classKey];
  7098. var currentTarget = target;
  7099. var currentKey = classKey;
  7100. while (currentKey) {
  7101. var initialStore = __decoratorInitialStore[currentKey];
  7102. for (var property in initialStore) {
  7103. store[property] = initialStore[property];
  7104. }
  7105. var parent_1 = void 0;
  7106. var done = false;
  7107. do {
  7108. parent_1 = Object.getPrototypeOf(currentTarget);
  7109. if (!parent_1.getClassName) {
  7110. done = true;
  7111. break;
  7112. }
  7113. if (parent_1.getClassName() !== currentKey) {
  7114. break;
  7115. }
  7116. currentTarget = parent_1;
  7117. } while (parent_1);
  7118. if (done) {
  7119. break;
  7120. }
  7121. currentKey = parent_1.getClassName();
  7122. currentTarget = parent_1;
  7123. }
  7124. return store;
  7125. }
  7126. function generateSerializableMember(type, sourceName) {
  7127. return function (target, propertyKey) {
  7128. var classStore = getDirectStore(target);
  7129. if (!classStore[propertyKey]) {
  7130. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7131. }
  7132. };
  7133. }
  7134. function generateExpandMember(setCallback, targetKey) {
  7135. if (targetKey === void 0) { targetKey = null; }
  7136. return function (target, propertyKey) {
  7137. var key = targetKey || ("_" + propertyKey);
  7138. Object.defineProperty(target, propertyKey, {
  7139. get: function () {
  7140. return this[key];
  7141. },
  7142. set: function (value) {
  7143. if (this[key] === value) {
  7144. return;
  7145. }
  7146. this[key] = value;
  7147. target[setCallback].apply(this);
  7148. },
  7149. enumerable: true,
  7150. configurable: true
  7151. });
  7152. };
  7153. }
  7154. function expandToProperty(callback, targetKey) {
  7155. if (targetKey === void 0) { targetKey = null; }
  7156. return generateExpandMember(callback, targetKey);
  7157. }
  7158. BABYLON.expandToProperty = expandToProperty;
  7159. function serialize(sourceName) {
  7160. return generateSerializableMember(0, sourceName); // value member
  7161. }
  7162. BABYLON.serialize = serialize;
  7163. function serializeAsTexture(sourceName) {
  7164. return generateSerializableMember(1, sourceName); // texture member
  7165. }
  7166. BABYLON.serializeAsTexture = serializeAsTexture;
  7167. function serializeAsColor3(sourceName) {
  7168. return generateSerializableMember(2, sourceName); // color3 member
  7169. }
  7170. BABYLON.serializeAsColor3 = serializeAsColor3;
  7171. function serializeAsFresnelParameters(sourceName) {
  7172. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7173. }
  7174. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7175. function serializeAsVector2(sourceName) {
  7176. return generateSerializableMember(4, sourceName); // vector2 member
  7177. }
  7178. BABYLON.serializeAsVector2 = serializeAsVector2;
  7179. function serializeAsVector3(sourceName) {
  7180. return generateSerializableMember(5, sourceName); // vector3 member
  7181. }
  7182. BABYLON.serializeAsVector3 = serializeAsVector3;
  7183. function serializeAsMeshReference(sourceName) {
  7184. return generateSerializableMember(6, sourceName); // mesh reference member
  7185. }
  7186. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7187. function serializeAsColorCurves(sourceName) {
  7188. return generateSerializableMember(7, sourceName); // color curves
  7189. }
  7190. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7191. function serializeAsColor4(sourceName) {
  7192. return generateSerializableMember(8, sourceName); // color 4
  7193. }
  7194. BABYLON.serializeAsColor4 = serializeAsColor4;
  7195. function serializeAsImageProcessingConfiguration(sourceName) {
  7196. return generateSerializableMember(9, sourceName); // image processing
  7197. }
  7198. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7199. function serializeAsQuaternion(sourceName) {
  7200. return generateSerializableMember(10, sourceName); // quaternion member
  7201. }
  7202. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7203. var SerializationHelper = /** @class */ (function () {
  7204. function SerializationHelper() {
  7205. }
  7206. SerializationHelper.Serialize = function (entity, serializationObject) {
  7207. if (!serializationObject) {
  7208. serializationObject = {};
  7209. }
  7210. // Tags
  7211. if (BABYLON.Tags) {
  7212. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7213. }
  7214. var serializedProperties = getMergedStore(entity);
  7215. // Properties
  7216. for (var property in serializedProperties) {
  7217. var propertyDescriptor = serializedProperties[property];
  7218. var targetPropertyName = propertyDescriptor.sourceName || property;
  7219. var propertyType = propertyDescriptor.type;
  7220. var sourceProperty = entity[property];
  7221. if (sourceProperty !== undefined && sourceProperty !== null) {
  7222. switch (propertyType) {
  7223. case 0:// Value
  7224. serializationObject[targetPropertyName] = sourceProperty;
  7225. break;
  7226. case 1:// Texture
  7227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7228. break;
  7229. case 2:// Color3
  7230. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7231. break;
  7232. case 3:// FresnelParameters
  7233. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7234. break;
  7235. case 4:// Vector2
  7236. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7237. break;
  7238. case 5:// Vector3
  7239. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7240. break;
  7241. case 6:// Mesh reference
  7242. serializationObject[targetPropertyName] = sourceProperty.id;
  7243. break;
  7244. case 7:// Color Curves
  7245. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7246. break;
  7247. case 8:// Color 4
  7248. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7249. break;
  7250. case 9:// Image Processing
  7251. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7252. break;
  7253. }
  7254. }
  7255. }
  7256. return serializationObject;
  7257. };
  7258. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7259. if (rootUrl === void 0) { rootUrl = null; }
  7260. var destination = creationFunction();
  7261. if (!rootUrl) {
  7262. rootUrl = "";
  7263. }
  7264. // Tags
  7265. if (BABYLON.Tags) {
  7266. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7267. }
  7268. var classStore = getMergedStore(destination);
  7269. // Properties
  7270. for (var property in classStore) {
  7271. var propertyDescriptor = classStore[property];
  7272. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7273. var propertyType = propertyDescriptor.type;
  7274. if (sourceProperty !== undefined && sourceProperty !== null) {
  7275. var dest = destination;
  7276. switch (propertyType) {
  7277. case 0:// Value
  7278. dest[property] = sourceProperty;
  7279. break;
  7280. case 1:// Texture
  7281. if (scene) {
  7282. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7283. }
  7284. break;
  7285. case 2:// Color3
  7286. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7287. break;
  7288. case 3:// FresnelParameters
  7289. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7290. break;
  7291. case 4:// Vector2
  7292. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7293. break;
  7294. case 5:// Vector3
  7295. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7296. break;
  7297. case 6:// Mesh reference
  7298. if (scene) {
  7299. dest[property] = scene.getLastMeshByID(sourceProperty);
  7300. }
  7301. break;
  7302. case 7:// Color Curves
  7303. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7304. break;
  7305. case 8:// Color 4
  7306. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7307. break;
  7308. case 9:// Image Processing
  7309. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7310. break;
  7311. }
  7312. }
  7313. }
  7314. return destination;
  7315. };
  7316. SerializationHelper.Clone = function (creationFunction, source) {
  7317. return _copySource(creationFunction, source, false);
  7318. };
  7319. SerializationHelper.Instanciate = function (creationFunction, source) {
  7320. return _copySource(creationFunction, source, true);
  7321. };
  7322. return SerializationHelper;
  7323. }());
  7324. BABYLON.SerializationHelper = SerializationHelper;
  7325. })(BABYLON || (BABYLON = {}));
  7326. //# sourceMappingURL=babylon.decorators.js.map
  7327. "use strict";
  7328. var BABYLON;
  7329. (function (BABYLON) {
  7330. /**
  7331. * Wrapper class for promise with external resolve and reject.
  7332. */
  7333. var Deferred = /** @class */ (function () {
  7334. /**
  7335. * Constructor for this deferred object.
  7336. */
  7337. function Deferred() {
  7338. var _this = this;
  7339. this.promise = new Promise(function (resolve, reject) {
  7340. _this._resolve = resolve;
  7341. _this._reject = reject;
  7342. });
  7343. }
  7344. Object.defineProperty(Deferred.prototype, "resolve", {
  7345. /**
  7346. * The resolve method of the promise associated with this deferred object.
  7347. */
  7348. get: function () {
  7349. return this._resolve;
  7350. },
  7351. enumerable: true,
  7352. configurable: true
  7353. });
  7354. Object.defineProperty(Deferred.prototype, "reject", {
  7355. /**
  7356. * The reject method of the promise associated with this deferred object.
  7357. */
  7358. get: function () {
  7359. return this._reject;
  7360. },
  7361. enumerable: true,
  7362. configurable: true
  7363. });
  7364. return Deferred;
  7365. }());
  7366. BABYLON.Deferred = Deferred;
  7367. })(BABYLON || (BABYLON = {}));
  7368. //# sourceMappingURL=babylon.deferred.js.map
  7369. "use strict";
  7370. var BABYLON;
  7371. (function (BABYLON) {
  7372. /**
  7373. * A class serves as a medium between the observable and its observers
  7374. */
  7375. var EventState = /** @class */ (function () {
  7376. /**
  7377. * Create a new EventState
  7378. * @param mask defines the mask associated with this state
  7379. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7380. * @param target defines the original target of the state
  7381. * @param currentTarget defines the current target of the state
  7382. */
  7383. function EventState(mask, skipNextObservers, target, currentTarget) {
  7384. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7385. this.initalize(mask, skipNextObservers, target, currentTarget);
  7386. }
  7387. /**
  7388. * Initialize the current event state
  7389. * @param mask defines the mask associated with this state
  7390. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7391. * @param target defines the original target of the state
  7392. * @param currentTarget defines the current target of the state
  7393. * @returns the current event state
  7394. */
  7395. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7396. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7397. this.mask = mask;
  7398. this.skipNextObservers = skipNextObservers;
  7399. this.target = target;
  7400. this.currentTarget = currentTarget;
  7401. return this;
  7402. };
  7403. return EventState;
  7404. }());
  7405. BABYLON.EventState = EventState;
  7406. /**
  7407. * Represent an Observer registered to a given Observable object.
  7408. */
  7409. var Observer = /** @class */ (function () {
  7410. /**
  7411. * Creates a new observer
  7412. * @param callback defines the callback to call when the observer is notified
  7413. * @param mask defines the mask of the observer (used to filter notifications)
  7414. * @param scope defines the current scope used to restore the JS context
  7415. */
  7416. function Observer(
  7417. /**
  7418. * Defines the callback to call when the observer is notified
  7419. */
  7420. callback,
  7421. /**
  7422. * Defines the mask of the observer (used to filter notifications)
  7423. */
  7424. mask,
  7425. /**
  7426. * Defines the current scope used to restore the JS context
  7427. */
  7428. scope) {
  7429. if (scope === void 0) { scope = null; }
  7430. this.callback = callback;
  7431. this.mask = mask;
  7432. this.scope = scope;
  7433. /** @ignore */
  7434. this._willBeUnregistered = false;
  7435. /**
  7436. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7437. */
  7438. this.unregisterOnNextCall = false;
  7439. }
  7440. return Observer;
  7441. }());
  7442. BABYLON.Observer = Observer;
  7443. /**
  7444. * Represent a list of observers registered to multiple Observables object.
  7445. */
  7446. var MultiObserver = /** @class */ (function () {
  7447. function MultiObserver() {
  7448. }
  7449. /**
  7450. * Release associated resources
  7451. */
  7452. MultiObserver.prototype.dispose = function () {
  7453. if (this._observers && this._observables) {
  7454. for (var index = 0; index < this._observers.length; index++) {
  7455. this._observables[index].remove(this._observers[index]);
  7456. }
  7457. }
  7458. this._observers = null;
  7459. this._observables = null;
  7460. };
  7461. /**
  7462. * Raise a callback when one of the observable will notify
  7463. * @param observables defines a list of observables to watch
  7464. * @param callback defines the callback to call on notification
  7465. * @param mask defines the mask used to filter notifications
  7466. * @param scope defines the current scope used to restore the JS context
  7467. * @returns the new MultiObserver
  7468. */
  7469. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7470. if (mask === void 0) { mask = -1; }
  7471. if (scope === void 0) { scope = null; }
  7472. var result = new MultiObserver();
  7473. result._observers = new Array();
  7474. result._observables = observables;
  7475. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7476. var observable = observables_1[_i];
  7477. var observer = observable.add(callback, mask, false, scope);
  7478. if (observer) {
  7479. result._observers.push(observer);
  7480. }
  7481. }
  7482. return result;
  7483. };
  7484. return MultiObserver;
  7485. }());
  7486. BABYLON.MultiObserver = MultiObserver;
  7487. /**
  7488. * The Observable class is a simple implementation of the Observable pattern.
  7489. * 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.
  7490. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7491. * 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).
  7492. * 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.
  7493. */
  7494. var Observable = /** @class */ (function () {
  7495. /**
  7496. * Creates a new observable
  7497. * @param onObserverAdded defines a callback to call when a new observer is added
  7498. */
  7499. function Observable(onObserverAdded) {
  7500. this._observers = new Array();
  7501. this._eventState = new EventState(0);
  7502. if (onObserverAdded) {
  7503. this._onObserverAdded = onObserverAdded;
  7504. }
  7505. }
  7506. /**
  7507. * Create a new Observer with the specified callback
  7508. * @param callback the callback that will be executed for that Observer
  7509. * @param mask the mask used to filter observers
  7510. * @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.
  7511. * @param scope optional scope for the callback to be called from
  7512. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7513. * @returns the new observer created for the callback
  7514. */
  7515. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7516. if (mask === void 0) { mask = -1; }
  7517. if (insertFirst === void 0) { insertFirst = false; }
  7518. if (scope === void 0) { scope = null; }
  7519. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7520. if (!callback) {
  7521. return null;
  7522. }
  7523. var observer = new Observer(callback, mask, scope);
  7524. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7525. if (insertFirst) {
  7526. this._observers.unshift(observer);
  7527. }
  7528. else {
  7529. this._observers.push(observer);
  7530. }
  7531. if (this._onObserverAdded) {
  7532. this._onObserverAdded(observer);
  7533. }
  7534. return observer;
  7535. };
  7536. /**
  7537. * Remove an Observer from the Observable object
  7538. * @param observer the instance of the Observer to remove
  7539. * @returns false if it doesn't belong to this Observable
  7540. */
  7541. Observable.prototype.remove = function (observer) {
  7542. if (!observer) {
  7543. return false;
  7544. }
  7545. var index = this._observers.indexOf(observer);
  7546. if (index !== -1) {
  7547. this._observers.splice(index, 1);
  7548. return true;
  7549. }
  7550. return false;
  7551. };
  7552. /**
  7553. * Remove a callback from the Observable object
  7554. * @param callback the callback to remove
  7555. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7556. * @returns false if it doesn't belong to this Observable
  7557. */
  7558. Observable.prototype.removeCallback = function (callback, scope) {
  7559. for (var index = 0; index < this._observers.length; index++) {
  7560. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7561. this._observers.splice(index, 1);
  7562. return true;
  7563. }
  7564. }
  7565. return false;
  7566. };
  7567. Observable.prototype._deferUnregister = function (observer) {
  7568. var _this = this;
  7569. observer.unregisterOnNextCall = false;
  7570. observer._willBeUnregistered = true;
  7571. BABYLON.Tools.SetImmediate(function () {
  7572. _this.remove(observer);
  7573. });
  7574. };
  7575. /**
  7576. * Notify all Observers by calling their respective callback with the given data
  7577. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7578. * @param eventData defines the data to send to all observers
  7579. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7580. * @param target defines the original target of the state
  7581. * @param currentTarget defines the current target of the state
  7582. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7583. */
  7584. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7585. if (mask === void 0) { mask = -1; }
  7586. if (!this._observers.length) {
  7587. return true;
  7588. }
  7589. var state = this._eventState;
  7590. state.mask = mask;
  7591. state.target = target;
  7592. state.currentTarget = currentTarget;
  7593. state.skipNextObservers = false;
  7594. state.lastReturnValue = eventData;
  7595. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7596. var obs = _a[_i];
  7597. if (obs._willBeUnregistered) {
  7598. continue;
  7599. }
  7600. if (obs.mask & mask) {
  7601. if (obs.scope) {
  7602. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7603. }
  7604. else {
  7605. state.lastReturnValue = obs.callback(eventData, state);
  7606. }
  7607. if (obs.unregisterOnNextCall) {
  7608. this._deferUnregister(obs);
  7609. }
  7610. }
  7611. if (state.skipNextObservers) {
  7612. return false;
  7613. }
  7614. }
  7615. return true;
  7616. };
  7617. /**
  7618. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7619. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7620. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7621. * and it is crucial that all callbacks will be executed.
  7622. * The order of the callbacks is kept, callbacks are not executed parallel.
  7623. *
  7624. * @param eventData The data to be sent to each callback
  7625. * @param mask is used to filter observers defaults to -1
  7626. * @param target defines the callback target (see EventState)
  7627. * @param currentTarget defines he current object in the bubbling phase
  7628. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7629. */
  7630. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7631. var _this = this;
  7632. if (mask === void 0) { mask = -1; }
  7633. // create an empty promise
  7634. var p = Promise.resolve(eventData);
  7635. // no observers? return this promise.
  7636. if (!this._observers.length) {
  7637. return p;
  7638. }
  7639. var state = this._eventState;
  7640. state.mask = mask;
  7641. state.target = target;
  7642. state.currentTarget = currentTarget;
  7643. state.skipNextObservers = false;
  7644. // execute one callback after another (not using Promise.all, the order is important)
  7645. this._observers.forEach(function (obs) {
  7646. if (state.skipNextObservers) {
  7647. return;
  7648. }
  7649. if (obs._willBeUnregistered) {
  7650. return;
  7651. }
  7652. if (obs.mask & mask) {
  7653. if (obs.scope) {
  7654. p = p.then(function (lastReturnedValue) {
  7655. state.lastReturnValue = lastReturnedValue;
  7656. return obs.callback.apply(obs.scope, [eventData, state]);
  7657. });
  7658. }
  7659. else {
  7660. p = p.then(function (lastReturnedValue) {
  7661. state.lastReturnValue = lastReturnedValue;
  7662. return obs.callback(eventData, state);
  7663. });
  7664. }
  7665. if (obs.unregisterOnNextCall) {
  7666. _this._deferUnregister(obs);
  7667. }
  7668. }
  7669. });
  7670. // return the eventData
  7671. return p.then(function () { return eventData; });
  7672. };
  7673. /**
  7674. * Notify a specific observer
  7675. * @param observer defines the observer to notify
  7676. * @param eventData defines the data to be sent to each callback
  7677. * @param mask is used to filter observers defaults to -1
  7678. */
  7679. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7680. if (mask === void 0) { mask = -1; }
  7681. var state = this._eventState;
  7682. state.mask = mask;
  7683. state.skipNextObservers = false;
  7684. observer.callback(eventData, state);
  7685. };
  7686. /**
  7687. * Gets a boolean indicating if the observable has at least one observer
  7688. * @returns true is the Observable has at least one Observer registered
  7689. */
  7690. Observable.prototype.hasObservers = function () {
  7691. return this._observers.length > 0;
  7692. };
  7693. /**
  7694. * Clear the list of observers
  7695. */
  7696. Observable.prototype.clear = function () {
  7697. this._observers = new Array();
  7698. this._onObserverAdded = null;
  7699. };
  7700. /**
  7701. * Clone the current observable
  7702. * @returns a new observable
  7703. */
  7704. Observable.prototype.clone = function () {
  7705. var result = new Observable();
  7706. result._observers = this._observers.slice(0);
  7707. return result;
  7708. };
  7709. /**
  7710. * Does this observable handles observer registered with a given mask
  7711. * @param mask defines the mask to be tested
  7712. * @return whether or not one observer registered with the given mask is handeled
  7713. **/
  7714. Observable.prototype.hasSpecificMask = function (mask) {
  7715. if (mask === void 0) { mask = -1; }
  7716. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7717. var obs = _a[_i];
  7718. if (obs.mask & mask || obs.mask === mask) {
  7719. return true;
  7720. }
  7721. }
  7722. return false;
  7723. };
  7724. return Observable;
  7725. }());
  7726. BABYLON.Observable = Observable;
  7727. })(BABYLON || (BABYLON = {}));
  7728. //# sourceMappingURL=babylon.observable.js.map
  7729. "use strict";
  7730. var BABYLON;
  7731. (function (BABYLON) {
  7732. var SmartArray = /** @class */ (function () {
  7733. function SmartArray(capacity) {
  7734. this.length = 0;
  7735. this.data = new Array(capacity);
  7736. this._id = SmartArray._GlobalId++;
  7737. }
  7738. SmartArray.prototype.push = function (value) {
  7739. this.data[this.length++] = value;
  7740. if (this.length > this.data.length) {
  7741. this.data.length *= 2;
  7742. }
  7743. };
  7744. SmartArray.prototype.forEach = function (func) {
  7745. for (var index = 0; index < this.length; index++) {
  7746. func(this.data[index]);
  7747. }
  7748. };
  7749. SmartArray.prototype.sort = function (compareFn) {
  7750. this.data.sort(compareFn);
  7751. };
  7752. SmartArray.prototype.reset = function () {
  7753. this.length = 0;
  7754. };
  7755. SmartArray.prototype.dispose = function () {
  7756. this.reset();
  7757. if (this.data) {
  7758. this.data.length = 0;
  7759. this.data = [];
  7760. }
  7761. };
  7762. SmartArray.prototype.concat = function (array) {
  7763. if (array.length === 0) {
  7764. return;
  7765. }
  7766. if (this.length + array.length > this.data.length) {
  7767. this.data.length = (this.length + array.length) * 2;
  7768. }
  7769. for (var index = 0; index < array.length; index++) {
  7770. this.data[this.length++] = (array.data || array)[index];
  7771. }
  7772. };
  7773. SmartArray.prototype.indexOf = function (value) {
  7774. var position = this.data.indexOf(value);
  7775. if (position >= this.length) {
  7776. return -1;
  7777. }
  7778. return position;
  7779. };
  7780. SmartArray.prototype.contains = function (value) {
  7781. return this.data.indexOf(value) !== -1;
  7782. };
  7783. // Statics
  7784. SmartArray._GlobalId = 0;
  7785. return SmartArray;
  7786. }());
  7787. BABYLON.SmartArray = SmartArray;
  7788. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7789. __extends(SmartArrayNoDuplicate, _super);
  7790. function SmartArrayNoDuplicate() {
  7791. var _this = _super !== null && _super.apply(this, arguments) || this;
  7792. _this._duplicateId = 0;
  7793. return _this;
  7794. }
  7795. SmartArrayNoDuplicate.prototype.push = function (value) {
  7796. _super.prototype.push.call(this, value);
  7797. if (!value.__smartArrayFlags) {
  7798. value.__smartArrayFlags = {};
  7799. }
  7800. value.__smartArrayFlags[this._id] = this._duplicateId;
  7801. };
  7802. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7803. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7804. return false;
  7805. }
  7806. this.push(value);
  7807. return true;
  7808. };
  7809. SmartArrayNoDuplicate.prototype.reset = function () {
  7810. _super.prototype.reset.call(this);
  7811. this._duplicateId++;
  7812. };
  7813. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7814. if (array.length === 0) {
  7815. return;
  7816. }
  7817. if (this.length + array.length > this.data.length) {
  7818. this.data.length = (this.length + array.length) * 2;
  7819. }
  7820. for (var index = 0; index < array.length; index++) {
  7821. var item = (array.data || array)[index];
  7822. this.pushNoDuplicate(item);
  7823. }
  7824. };
  7825. return SmartArrayNoDuplicate;
  7826. }(SmartArray));
  7827. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7828. })(BABYLON || (BABYLON = {}));
  7829. //# sourceMappingURL=babylon.smartArray.js.map
  7830. "use strict";
  7831. var BABYLON;
  7832. (function (BABYLON) {
  7833. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7834. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7835. var LoadFileError = /** @class */ (function (_super) {
  7836. __extends(LoadFileError, _super);
  7837. function LoadFileError(message, request) {
  7838. var _this = _super.call(this, message) || this;
  7839. _this.request = request;
  7840. _this.name = "LoadFileError";
  7841. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7842. return _this;
  7843. }
  7844. // Polyfill for Object.setPrototypeOf if necessary.
  7845. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7846. return LoadFileError;
  7847. }(Error));
  7848. BABYLON.LoadFileError = LoadFileError;
  7849. var RetryStrategy = /** @class */ (function () {
  7850. function RetryStrategy() {
  7851. }
  7852. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7853. if (maxRetries === void 0) { maxRetries = 3; }
  7854. if (baseInterval === void 0) { baseInterval = 500; }
  7855. return function (url, request, retryIndex) {
  7856. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7857. return -1;
  7858. }
  7859. return Math.pow(2, retryIndex) * baseInterval;
  7860. };
  7861. };
  7862. return RetryStrategy;
  7863. }());
  7864. BABYLON.RetryStrategy = RetryStrategy;
  7865. // Screenshots
  7866. var screenshotCanvas;
  7867. var cloneValue = function (source, destinationObject) {
  7868. if (!source)
  7869. return null;
  7870. if (source instanceof BABYLON.Mesh) {
  7871. return null;
  7872. }
  7873. if (source instanceof BABYLON.SubMesh) {
  7874. return source.clone(destinationObject);
  7875. }
  7876. else if (source.clone) {
  7877. return source.clone();
  7878. }
  7879. return null;
  7880. };
  7881. var Tools = /** @class */ (function () {
  7882. function Tools() {
  7883. }
  7884. /**
  7885. * Interpolates between a and b via alpha
  7886. * @param a The lower value (returned when alpha = 0)
  7887. * @param b The upper value (returned when alpha = 1)
  7888. * @param alpha The interpolation-factor
  7889. * @return The mixed value
  7890. */
  7891. Tools.Mix = function (a, b, alpha) {
  7892. return a * (1 - alpha) + b * alpha;
  7893. };
  7894. Tools.Instantiate = function (className) {
  7895. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7896. return Tools.RegisteredExternalClasses[className];
  7897. }
  7898. var arr = className.split(".");
  7899. var fn = (window || this);
  7900. for (var i = 0, len = arr.length; i < len; i++) {
  7901. fn = fn[arr[i]];
  7902. }
  7903. if (typeof fn !== "function") {
  7904. return null;
  7905. }
  7906. return fn;
  7907. };
  7908. /**
  7909. * Provides a slice function that will work even on IE
  7910. * @param data defines the array to slice
  7911. * @returns the new sliced array
  7912. */
  7913. Tools.Slice = function (data) {
  7914. if (data.slice) {
  7915. return data.slice();
  7916. }
  7917. return Array.prototype.slice.call(data);
  7918. };
  7919. Tools.SetImmediate = function (action) {
  7920. if (window.setImmediate) {
  7921. window.setImmediate(action);
  7922. }
  7923. else {
  7924. setTimeout(action, 1);
  7925. }
  7926. };
  7927. Tools.IsExponentOfTwo = function (value) {
  7928. var count = 1;
  7929. do {
  7930. count *= 2;
  7931. } while (count < value);
  7932. return count === value;
  7933. };
  7934. /**
  7935. * Find the next highest power of two.
  7936. * @param x Number to start search from.
  7937. * @return Next highest power of two.
  7938. */
  7939. Tools.CeilingPOT = function (x) {
  7940. x--;
  7941. x |= x >> 1;
  7942. x |= x >> 2;
  7943. x |= x >> 4;
  7944. x |= x >> 8;
  7945. x |= x >> 16;
  7946. x++;
  7947. return x;
  7948. };
  7949. /**
  7950. * Find the next lowest power of two.
  7951. * @param x Number to start search from.
  7952. * @return Next lowest power of two.
  7953. */
  7954. Tools.FloorPOT = function (x) {
  7955. x = x | (x >> 1);
  7956. x = x | (x >> 2);
  7957. x = x | (x >> 4);
  7958. x = x | (x >> 8);
  7959. x = x | (x >> 16);
  7960. return x - (x >> 1);
  7961. };
  7962. /**
  7963. * Find the nearest power of two.
  7964. * @param x Number to start search from.
  7965. * @return Next nearest power of two.
  7966. */
  7967. Tools.NearestPOT = function (x) {
  7968. var c = Tools.CeilingPOT(x);
  7969. var f = Tools.FloorPOT(x);
  7970. return (c - x) > (x - f) ? f : c;
  7971. };
  7972. Tools.GetExponentOfTwo = function (value, max, mode) {
  7973. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7974. var pot;
  7975. switch (mode) {
  7976. case BABYLON.Engine.SCALEMODE_FLOOR:
  7977. pot = Tools.FloorPOT(value);
  7978. break;
  7979. case BABYLON.Engine.SCALEMODE_NEAREST:
  7980. pot = Tools.NearestPOT(value);
  7981. break;
  7982. case BABYLON.Engine.SCALEMODE_CEILING:
  7983. default:
  7984. pot = Tools.CeilingPOT(value);
  7985. break;
  7986. }
  7987. return Math.min(pot, max);
  7988. };
  7989. Tools.GetFilename = function (path) {
  7990. var index = path.lastIndexOf("/");
  7991. if (index < 0)
  7992. return path;
  7993. return path.substring(index + 1);
  7994. };
  7995. /**
  7996. * Extracts the "folder" part of a path (everything before the filename).
  7997. * @param uri The URI to extract the info from
  7998. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7999. * @returns The "folder" part of the path
  8000. */
  8001. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8002. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8003. var index = uri.lastIndexOf("/");
  8004. if (index < 0) {
  8005. if (returnUnchangedIfNoSlash) {
  8006. return uri;
  8007. }
  8008. return "";
  8009. }
  8010. return uri.substring(0, index + 1);
  8011. };
  8012. Tools.GetDOMTextContent = function (element) {
  8013. var result = "";
  8014. var child = element.firstChild;
  8015. while (child) {
  8016. if (child.nodeType === 3) {
  8017. result += child.textContent;
  8018. }
  8019. child = child.nextSibling;
  8020. }
  8021. return result;
  8022. };
  8023. Tools.ToDegrees = function (angle) {
  8024. return angle * 180 / Math.PI;
  8025. };
  8026. Tools.ToRadians = function (angle) {
  8027. return angle * Math.PI / 180;
  8028. };
  8029. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8030. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8031. var output = "";
  8032. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8033. var i = 0;
  8034. var bytes = new Uint8Array(buffer);
  8035. while (i < bytes.length) {
  8036. chr1 = bytes[i++];
  8037. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8038. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8039. enc1 = chr1 >> 2;
  8040. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8041. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8042. enc4 = chr3 & 63;
  8043. if (isNaN(chr2)) {
  8044. enc3 = enc4 = 64;
  8045. }
  8046. else if (isNaN(chr3)) {
  8047. enc4 = 64;
  8048. }
  8049. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8050. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8051. }
  8052. return "data:image/png;base64," + output;
  8053. };
  8054. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8055. if (bias === void 0) { bias = null; }
  8056. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8057. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8058. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8059. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8060. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8061. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8062. }
  8063. if (bias) {
  8064. minimum.x -= minimum.x * bias.x + bias.y;
  8065. minimum.y -= minimum.y * bias.x + bias.y;
  8066. minimum.z -= minimum.z * bias.x + bias.y;
  8067. maximum.x += maximum.x * bias.x + bias.y;
  8068. maximum.y += maximum.y * bias.x + bias.y;
  8069. maximum.z += maximum.z * bias.x + bias.y;
  8070. }
  8071. return {
  8072. minimum: minimum,
  8073. maximum: maximum
  8074. };
  8075. };
  8076. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8077. if (bias === void 0) { bias = null; }
  8078. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8079. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8080. if (!stride) {
  8081. stride = 3;
  8082. }
  8083. for (var index = start; index < start + count; index++) {
  8084. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8085. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8086. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8087. }
  8088. if (bias) {
  8089. minimum.x -= minimum.x * bias.x + bias.y;
  8090. minimum.y -= minimum.y * bias.x + bias.y;
  8091. minimum.z -= minimum.z * bias.x + bias.y;
  8092. maximum.x += maximum.x * bias.x + bias.y;
  8093. maximum.y += maximum.y * bias.x + bias.y;
  8094. maximum.z += maximum.z * bias.x + bias.y;
  8095. }
  8096. return {
  8097. minimum: minimum,
  8098. maximum: maximum
  8099. };
  8100. };
  8101. Tools.Vector2ArrayFeeder = function (array) {
  8102. return function (index) {
  8103. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8104. var length = isFloatArray ? array.length / 2 : array.length;
  8105. if (index >= length) {
  8106. return null;
  8107. }
  8108. if (isFloatArray) {
  8109. var fa = array;
  8110. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8111. }
  8112. var a = array;
  8113. return a[index];
  8114. };
  8115. };
  8116. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8117. if (bias === void 0) { bias = null; }
  8118. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8119. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8120. var i = 0;
  8121. var cur = feeder(i++);
  8122. while (cur) {
  8123. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8124. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8125. cur = feeder(i++);
  8126. }
  8127. if (bias) {
  8128. minimum.x -= minimum.x * bias.x + bias.y;
  8129. minimum.y -= minimum.y * bias.x + bias.y;
  8130. maximum.x += maximum.x * bias.x + bias.y;
  8131. maximum.y += maximum.y * bias.x + bias.y;
  8132. }
  8133. return {
  8134. minimum: minimum,
  8135. maximum: maximum
  8136. };
  8137. };
  8138. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8139. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8140. return null;
  8141. return Array.isArray(obj) ? obj : [obj];
  8142. };
  8143. // Misc.
  8144. Tools.GetPointerPrefix = function () {
  8145. var eventPrefix = "pointer";
  8146. // Check if pointer events are supported
  8147. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8148. eventPrefix = "mouse";
  8149. }
  8150. return eventPrefix;
  8151. };
  8152. /**
  8153. * @param func - the function to be called
  8154. * @param requester - the object that will request the next frame. Falls back to window.
  8155. */
  8156. Tools.QueueNewFrame = function (func, requester) {
  8157. if (!Tools.IsWindowObjectExist()) {
  8158. return setTimeout(func, 16);
  8159. }
  8160. if (!requester) {
  8161. requester = window;
  8162. }
  8163. if (requester.requestAnimationFrame) {
  8164. return requester.requestAnimationFrame(func);
  8165. }
  8166. else if (requester.msRequestAnimationFrame) {
  8167. return requester.msRequestAnimationFrame(func);
  8168. }
  8169. else if (requester.webkitRequestAnimationFrame) {
  8170. return requester.webkitRequestAnimationFrame(func);
  8171. }
  8172. else if (requester.mozRequestAnimationFrame) {
  8173. return requester.mozRequestAnimationFrame(func);
  8174. }
  8175. else if (requester.oRequestAnimationFrame) {
  8176. return requester.oRequestAnimationFrame(func);
  8177. }
  8178. else {
  8179. return window.setTimeout(func, 16);
  8180. }
  8181. };
  8182. Tools.RequestFullscreen = function (element) {
  8183. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8184. if (!requestFunction)
  8185. return;
  8186. requestFunction.call(element);
  8187. };
  8188. Tools.ExitFullscreen = function () {
  8189. if (document.exitFullscreen) {
  8190. document.exitFullscreen();
  8191. }
  8192. else if (document.mozCancelFullScreen) {
  8193. document.mozCancelFullScreen();
  8194. }
  8195. else if (document.webkitCancelFullScreen) {
  8196. document.webkitCancelFullScreen();
  8197. }
  8198. else if (document.msCancelFullScreen) {
  8199. document.msCancelFullScreen();
  8200. }
  8201. };
  8202. Tools.SetCorsBehavior = function (url, element) {
  8203. if (url && url.indexOf("data:") === 0) {
  8204. return;
  8205. }
  8206. if (Tools.CorsBehavior) {
  8207. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8208. element.crossOrigin = Tools.CorsBehavior;
  8209. }
  8210. else {
  8211. var result = Tools.CorsBehavior(url);
  8212. if (result) {
  8213. element.crossOrigin = result;
  8214. }
  8215. }
  8216. }
  8217. };
  8218. // External files
  8219. Tools.CleanUrl = function (url) {
  8220. url = url.replace(/#/mg, "%23");
  8221. return url;
  8222. };
  8223. Tools.LoadImage = function (url, onLoad, onError, database) {
  8224. if (url instanceof ArrayBuffer) {
  8225. url = Tools.EncodeArrayBufferTobase64(url);
  8226. }
  8227. url = Tools.CleanUrl(url);
  8228. url = Tools.PreprocessUrl(url);
  8229. var img = new Image();
  8230. Tools.SetCorsBehavior(url, img);
  8231. var loadHandler = function () {
  8232. img.removeEventListener("load", loadHandler);
  8233. img.removeEventListener("error", errorHandler);
  8234. onLoad(img);
  8235. };
  8236. var errorHandler = function (err) {
  8237. img.removeEventListener("load", loadHandler);
  8238. img.removeEventListener("error", errorHandler);
  8239. Tools.Error("Error while trying to load image: " + url);
  8240. if (onError) {
  8241. onError("Error while trying to load image: " + url, err);
  8242. }
  8243. };
  8244. img.addEventListener("load", loadHandler);
  8245. img.addEventListener("error", errorHandler);
  8246. var noIndexedDB = function () {
  8247. img.src = url;
  8248. };
  8249. var loadFromIndexedDB = function () {
  8250. if (database) {
  8251. database.loadImageFromDB(url, img);
  8252. }
  8253. };
  8254. //ANY database to do!
  8255. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8256. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8257. }
  8258. else {
  8259. if (url.indexOf("file:") !== -1) {
  8260. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8261. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8262. try {
  8263. var blobURL;
  8264. try {
  8265. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8266. }
  8267. catch (ex) {
  8268. // Chrome doesn't support oneTimeOnly parameter
  8269. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8270. }
  8271. img.src = blobURL;
  8272. }
  8273. catch (e) {
  8274. img.src = "";
  8275. }
  8276. return img;
  8277. }
  8278. }
  8279. noIndexedDB();
  8280. }
  8281. return img;
  8282. };
  8283. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8284. url = Tools.CleanUrl(url);
  8285. url = Tools.PreprocessUrl(url);
  8286. // If file and file input are set
  8287. if (url.indexOf("file:") !== -1) {
  8288. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8289. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8290. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8291. }
  8292. }
  8293. var loadUrl = Tools.BaseUrl + url;
  8294. var aborted = false;
  8295. var fileRequest = {
  8296. onCompleteObservable: new BABYLON.Observable(),
  8297. abort: function () { return aborted = true; },
  8298. };
  8299. var requestFile = function () {
  8300. var request = new XMLHttpRequest();
  8301. var retryHandle = null;
  8302. fileRequest.abort = function () {
  8303. aborted = true;
  8304. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8305. request.abort();
  8306. }
  8307. if (retryHandle !== null) {
  8308. clearTimeout(retryHandle);
  8309. retryHandle = null;
  8310. }
  8311. };
  8312. var retryLoop = function (retryIndex) {
  8313. request.open('GET', loadUrl, true);
  8314. if (useArrayBuffer) {
  8315. request.responseType = "arraybuffer";
  8316. }
  8317. if (onProgress) {
  8318. request.addEventListener("progress", onProgress);
  8319. }
  8320. var onLoadEnd = function () {
  8321. request.removeEventListener("loadend", onLoadEnd);
  8322. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8323. fileRequest.onCompleteObservable.clear();
  8324. };
  8325. request.addEventListener("loadend", onLoadEnd);
  8326. var onReadyStateChange = function () {
  8327. if (aborted) {
  8328. return;
  8329. }
  8330. // In case of undefined state in some browsers.
  8331. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8332. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8333. request.removeEventListener("readystatechange", onReadyStateChange);
  8334. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8335. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8336. return;
  8337. }
  8338. var retryStrategy = Tools.DefaultRetryStrategy;
  8339. if (retryStrategy) {
  8340. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8341. if (waitTime !== -1) {
  8342. // Prevent the request from completing for retry.
  8343. request.removeEventListener("loadend", onLoadEnd);
  8344. request = new XMLHttpRequest();
  8345. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8346. return;
  8347. }
  8348. }
  8349. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8350. if (onError) {
  8351. onError(request, e);
  8352. }
  8353. else {
  8354. throw e;
  8355. }
  8356. }
  8357. };
  8358. request.addEventListener("readystatechange", onReadyStateChange);
  8359. request.send();
  8360. };
  8361. retryLoop(0);
  8362. };
  8363. // Caching all files
  8364. if (database && database.enableSceneOffline) {
  8365. var noIndexedDB_1 = function () {
  8366. if (!aborted) {
  8367. requestFile();
  8368. }
  8369. };
  8370. var loadFromIndexedDB = function () {
  8371. // TODO: database needs to support aborting and should return a IFileRequest
  8372. if (aborted) {
  8373. return;
  8374. }
  8375. if (database) {
  8376. database.loadFileFromDB(url, function (data) {
  8377. if (!aborted) {
  8378. onSuccess(data);
  8379. }
  8380. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8381. }, onProgress ? function (event) {
  8382. if (!aborted) {
  8383. onProgress(event);
  8384. }
  8385. } : undefined, noIndexedDB_1, useArrayBuffer);
  8386. }
  8387. };
  8388. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8389. }
  8390. else {
  8391. requestFile();
  8392. }
  8393. return fileRequest;
  8394. };
  8395. /**
  8396. * Load a script (identified by an url). When the url returns, the
  8397. * content of this file is added into a new script element, attached to the DOM (body element)
  8398. */
  8399. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8400. var head = document.getElementsByTagName('head')[0];
  8401. var script = document.createElement('script');
  8402. script.type = 'text/javascript';
  8403. script.src = scriptUrl;
  8404. script.onload = function () {
  8405. if (onSuccess) {
  8406. onSuccess();
  8407. }
  8408. };
  8409. script.onerror = function (e) {
  8410. if (onError) {
  8411. onError("Unable to load script", e);
  8412. }
  8413. };
  8414. head.appendChild(script);
  8415. };
  8416. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8417. var reader = new FileReader();
  8418. var request = {
  8419. onCompleteObservable: new BABYLON.Observable(),
  8420. abort: function () { return reader.abort(); },
  8421. };
  8422. reader.onloadend = function (e) {
  8423. request.onCompleteObservable.notifyObservers(request);
  8424. };
  8425. reader.onload = function (e) {
  8426. //target doesn't have result from ts 1.3
  8427. callback(e.target['result']);
  8428. };
  8429. reader.onprogress = progressCallback;
  8430. reader.readAsDataURL(fileToLoad);
  8431. return request;
  8432. };
  8433. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8434. var reader = new FileReader();
  8435. var request = {
  8436. onCompleteObservable: new BABYLON.Observable(),
  8437. abort: function () { return reader.abort(); },
  8438. };
  8439. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8440. reader.onerror = function (e) {
  8441. Tools.Log("Error while reading file: " + fileToLoad.name);
  8442. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8443. };
  8444. reader.onload = function (e) {
  8445. //target doesn't have result from ts 1.3
  8446. callback(e.target['result']);
  8447. };
  8448. if (progressCallBack) {
  8449. reader.onprogress = progressCallBack;
  8450. }
  8451. if (!useArrayBuffer) {
  8452. // Asynchronous read
  8453. reader.readAsText(fileToLoad);
  8454. }
  8455. else {
  8456. reader.readAsArrayBuffer(fileToLoad);
  8457. }
  8458. return request;
  8459. };
  8460. //returns a downloadable url to a file content.
  8461. Tools.FileAsURL = function (content) {
  8462. var fileBlob = new Blob([content]);
  8463. var url = window.URL || window.webkitURL;
  8464. var link = url.createObjectURL(fileBlob);
  8465. return link;
  8466. };
  8467. // Misc.
  8468. Tools.Format = function (value, decimals) {
  8469. if (decimals === void 0) { decimals = 2; }
  8470. return value.toFixed(decimals);
  8471. };
  8472. Tools.CheckExtends = function (v, min, max) {
  8473. if (v.x < min.x)
  8474. min.x = v.x;
  8475. if (v.y < min.y)
  8476. min.y = v.y;
  8477. if (v.z < min.z)
  8478. min.z = v.z;
  8479. if (v.x > max.x)
  8480. max.x = v.x;
  8481. if (v.y > max.y)
  8482. max.y = v.y;
  8483. if (v.z > max.z)
  8484. max.z = v.z;
  8485. };
  8486. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8487. for (var prop in source) {
  8488. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8489. continue;
  8490. }
  8491. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8492. continue;
  8493. }
  8494. var sourceValue = source[prop];
  8495. var typeOfSourceValue = typeof sourceValue;
  8496. if (typeOfSourceValue === "function") {
  8497. continue;
  8498. }
  8499. try {
  8500. if (typeOfSourceValue === "object") {
  8501. if (sourceValue instanceof Array) {
  8502. destination[prop] = [];
  8503. if (sourceValue.length > 0) {
  8504. if (typeof sourceValue[0] == "object") {
  8505. for (var index = 0; index < sourceValue.length; index++) {
  8506. var clonedValue = cloneValue(sourceValue[index], destination);
  8507. if (destination[prop].indexOf(clonedValue) === -1) {
  8508. destination[prop].push(clonedValue);
  8509. }
  8510. }
  8511. }
  8512. else {
  8513. destination[prop] = sourceValue.slice(0);
  8514. }
  8515. }
  8516. }
  8517. else {
  8518. destination[prop] = cloneValue(sourceValue, destination);
  8519. }
  8520. }
  8521. else {
  8522. destination[prop] = sourceValue;
  8523. }
  8524. }
  8525. catch (e) {
  8526. // Just ignore error (it could be because of a read-only property)
  8527. }
  8528. }
  8529. };
  8530. Tools.IsEmpty = function (obj) {
  8531. for (var i in obj) {
  8532. if (obj.hasOwnProperty(i)) {
  8533. return false;
  8534. }
  8535. }
  8536. return true;
  8537. };
  8538. Tools.RegisterTopRootEvents = function (events) {
  8539. for (var index = 0; index < events.length; index++) {
  8540. var event = events[index];
  8541. window.addEventListener(event.name, event.handler, false);
  8542. try {
  8543. if (window.parent) {
  8544. window.parent.addEventListener(event.name, event.handler, false);
  8545. }
  8546. }
  8547. catch (e) {
  8548. // Silently fails...
  8549. }
  8550. }
  8551. };
  8552. Tools.UnregisterTopRootEvents = function (events) {
  8553. for (var index = 0; index < events.length; index++) {
  8554. var event = events[index];
  8555. window.removeEventListener(event.name, event.handler);
  8556. try {
  8557. if (window.parent) {
  8558. window.parent.removeEventListener(event.name, event.handler);
  8559. }
  8560. }
  8561. catch (e) {
  8562. // Silently fails...
  8563. }
  8564. }
  8565. };
  8566. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8567. if (mimeType === void 0) { mimeType = "image/png"; }
  8568. // Read the contents of the framebuffer
  8569. var numberOfChannelsByLine = width * 4;
  8570. var halfHeight = height / 2;
  8571. //Reading datas from WebGL
  8572. var data = engine.readPixels(0, 0, width, height);
  8573. //To flip image on Y axis.
  8574. for (var i = 0; i < halfHeight; i++) {
  8575. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8576. var currentCell = j + i * numberOfChannelsByLine;
  8577. var targetLine = height - i - 1;
  8578. var targetCell = j + targetLine * numberOfChannelsByLine;
  8579. var temp = data[currentCell];
  8580. data[currentCell] = data[targetCell];
  8581. data[targetCell] = temp;
  8582. }
  8583. }
  8584. // Create a 2D canvas to store the result
  8585. if (!screenshotCanvas) {
  8586. screenshotCanvas = document.createElement('canvas');
  8587. }
  8588. screenshotCanvas.width = width;
  8589. screenshotCanvas.height = height;
  8590. var context = screenshotCanvas.getContext('2d');
  8591. if (context) {
  8592. // Copy the pixels to a 2D canvas
  8593. var imageData = context.createImageData(width, height);
  8594. var castData = (imageData.data);
  8595. castData.set(data);
  8596. context.putImageData(imageData, 0, 0);
  8597. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8598. }
  8599. };
  8600. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8601. if (mimeType === void 0) { mimeType = "image/png"; }
  8602. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8603. if (successCallback) {
  8604. successCallback(base64Image);
  8605. }
  8606. else {
  8607. // We need HTMLCanvasElement.toBlob for HD screenshots
  8608. if (!screenshotCanvas.toBlob) {
  8609. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8610. screenshotCanvas.toBlob = function (callback, type, quality) {
  8611. var _this = this;
  8612. setTimeout(function () {
  8613. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8614. for (var i = 0; i < len; i++) {
  8615. arr[i] = binStr.charCodeAt(i);
  8616. }
  8617. callback(new Blob([arr], { type: type || 'image/png' }));
  8618. });
  8619. };
  8620. }
  8621. screenshotCanvas.toBlob(function (blob) {
  8622. var url = URL.createObjectURL(blob);
  8623. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8624. if (("download" in document.createElement("a"))) {
  8625. var a = window.document.createElement("a");
  8626. a.href = url;
  8627. if (fileName) {
  8628. a.setAttribute("download", fileName);
  8629. }
  8630. else {
  8631. var date = new Date();
  8632. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8633. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8634. }
  8635. window.document.body.appendChild(a);
  8636. a.addEventListener("click", function () {
  8637. if (a.parentElement) {
  8638. a.parentElement.removeChild(a);
  8639. }
  8640. });
  8641. a.click();
  8642. }
  8643. else {
  8644. var newWindow = window.open("");
  8645. if (!newWindow)
  8646. return;
  8647. var img = newWindow.document.createElement("img");
  8648. img.onload = function () {
  8649. // no longer need to read the blob so it's revoked
  8650. URL.revokeObjectURL(url);
  8651. };
  8652. img.src = url;
  8653. newWindow.document.body.appendChild(img);
  8654. }
  8655. });
  8656. }
  8657. };
  8658. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8659. if (mimeType === void 0) { mimeType = "image/png"; }
  8660. var width;
  8661. var height;
  8662. // If a precision value is specified
  8663. if (size.precision) {
  8664. width = Math.round(engine.getRenderWidth() * size.precision);
  8665. height = Math.round(width / engine.getAspectRatio(camera));
  8666. }
  8667. else if (size.width && size.height) {
  8668. width = size.width;
  8669. height = size.height;
  8670. }
  8671. else if (size.width && !size.height) {
  8672. width = size.width;
  8673. height = Math.round(width / engine.getAspectRatio(camera));
  8674. }
  8675. else if (size.height && !size.width) {
  8676. height = size.height;
  8677. width = Math.round(height * engine.getAspectRatio(camera));
  8678. }
  8679. else if (!isNaN(size)) {
  8680. height = size;
  8681. width = size;
  8682. }
  8683. else {
  8684. Tools.Error("Invalid 'size' parameter !");
  8685. return;
  8686. }
  8687. if (!screenshotCanvas) {
  8688. screenshotCanvas = document.createElement('canvas');
  8689. }
  8690. screenshotCanvas.width = width;
  8691. screenshotCanvas.height = height;
  8692. var renderContext = screenshotCanvas.getContext("2d");
  8693. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8694. var newWidth = width;
  8695. var newHeight = newWidth / ratio;
  8696. if (newHeight > height) {
  8697. newHeight = height;
  8698. newWidth = newHeight * ratio;
  8699. }
  8700. var offsetX = Math.max(0, width - newWidth) / 2;
  8701. var offsetY = Math.max(0, height - newHeight) / 2;
  8702. var renderingCanvas = engine.getRenderingCanvas();
  8703. if (renderContext && renderingCanvas) {
  8704. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8705. }
  8706. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8707. };
  8708. /**
  8709. * Generates an image screenshot from the specified camera.
  8710. *
  8711. * @param engine The engine to use for rendering
  8712. * @param camera The camera to use for rendering
  8713. * @param size This parameter can be set to a single number or to an object with the
  8714. * following (optional) properties: precision, width, height. If a single number is passed,
  8715. * it will be used for both width and height. If an object is passed, the screenshot size
  8716. * will be derived from the parameters. The precision property is a multiplier allowing
  8717. * rendering at a higher or lower resolution.
  8718. * @param successCallback The callback receives a single parameter which contains the
  8719. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8720. * src parameter of an <img> to display it.
  8721. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8722. * Check your browser for supported MIME types.
  8723. * @param samples Texture samples (default: 1)
  8724. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8725. * @param fileName A name for for the downloaded file.
  8726. * @constructor
  8727. */
  8728. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8729. if (mimeType === void 0) { mimeType = "image/png"; }
  8730. if (samples === void 0) { samples = 1; }
  8731. if (antialiasing === void 0) { antialiasing = false; }
  8732. var width;
  8733. var height;
  8734. //If a precision value is specified
  8735. if (size.precision) {
  8736. width = Math.round(engine.getRenderWidth() * size.precision);
  8737. height = Math.round(width / engine.getAspectRatio(camera));
  8738. size = { width: width, height: height };
  8739. }
  8740. else if (size.width && size.height) {
  8741. width = size.width;
  8742. height = size.height;
  8743. }
  8744. else if (size.width && !size.height) {
  8745. width = size.width;
  8746. height = Math.round(width / engine.getAspectRatio(camera));
  8747. size = { width: width, height: height };
  8748. }
  8749. else if (size.height && !size.width) {
  8750. height = size.height;
  8751. width = Math.round(height * engine.getAspectRatio(camera));
  8752. size = { width: width, height: height };
  8753. }
  8754. else if (!isNaN(size)) {
  8755. height = size;
  8756. width = size;
  8757. }
  8758. else {
  8759. Tools.Error("Invalid 'size' parameter !");
  8760. return;
  8761. }
  8762. var scene = camera.getScene();
  8763. var previousCamera = null;
  8764. if (scene.activeCamera !== camera) {
  8765. previousCamera = scene.activeCamera;
  8766. scene.activeCamera = camera;
  8767. }
  8768. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8769. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8770. texture.renderList = null;
  8771. texture.samples = samples;
  8772. if (antialiasing) {
  8773. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8774. }
  8775. texture.onAfterRenderObservable.add(function () {
  8776. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8777. });
  8778. scene.incrementRenderId();
  8779. scene.resetCachedMaterial();
  8780. texture.render(true);
  8781. texture.dispose();
  8782. if (previousCamera) {
  8783. scene.activeCamera = previousCamera;
  8784. }
  8785. camera.getProjectionMatrix(true); // Force cache refresh;
  8786. };
  8787. // XHR response validator for local file scenario
  8788. Tools.ValidateXHRData = function (xhr, dataType) {
  8789. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8790. if (dataType === void 0) { dataType = 7; }
  8791. try {
  8792. if (dataType & 1) {
  8793. if (xhr.responseText && xhr.responseText.length > 0) {
  8794. return true;
  8795. }
  8796. else if (dataType === 1) {
  8797. return false;
  8798. }
  8799. }
  8800. if (dataType & 2) {
  8801. // Check header width and height since there is no "TGA" magic number
  8802. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8803. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8804. return true;
  8805. }
  8806. else if (dataType === 2) {
  8807. return false;
  8808. }
  8809. }
  8810. if (dataType & 4) {
  8811. // Check for the "DDS" magic number
  8812. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8813. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8814. return true;
  8815. }
  8816. else {
  8817. return false;
  8818. }
  8819. }
  8820. }
  8821. catch (e) {
  8822. // Global protection
  8823. }
  8824. return false;
  8825. };
  8826. /**
  8827. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8828. * Be aware Math.random() could cause collisions, but:
  8829. * "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"
  8830. */
  8831. Tools.RandomId = function () {
  8832. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8833. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8834. return v.toString(16);
  8835. });
  8836. };
  8837. /**
  8838. * Test if the given uri is a base64 string.
  8839. * @param uri The uri to test
  8840. * @return True if the uri is a base64 string or false otherwise.
  8841. */
  8842. Tools.IsBase64 = function (uri) {
  8843. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8844. };
  8845. /**
  8846. * Decode the given base64 uri.
  8847. * @param uri The uri to decode
  8848. * @return The decoded base64 data.
  8849. */
  8850. Tools.DecodeBase64 = function (uri) {
  8851. var decodedString = atob(uri.split(",")[1]);
  8852. var bufferLength = decodedString.length;
  8853. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8854. for (var i = 0; i < bufferLength; i++) {
  8855. bufferView[i] = decodedString.charCodeAt(i);
  8856. }
  8857. return bufferView.buffer;
  8858. };
  8859. Object.defineProperty(Tools, "NoneLogLevel", {
  8860. get: function () {
  8861. return Tools._NoneLogLevel;
  8862. },
  8863. enumerable: true,
  8864. configurable: true
  8865. });
  8866. Object.defineProperty(Tools, "MessageLogLevel", {
  8867. get: function () {
  8868. return Tools._MessageLogLevel;
  8869. },
  8870. enumerable: true,
  8871. configurable: true
  8872. });
  8873. Object.defineProperty(Tools, "WarningLogLevel", {
  8874. get: function () {
  8875. return Tools._WarningLogLevel;
  8876. },
  8877. enumerable: true,
  8878. configurable: true
  8879. });
  8880. Object.defineProperty(Tools, "ErrorLogLevel", {
  8881. get: function () {
  8882. return Tools._ErrorLogLevel;
  8883. },
  8884. enumerable: true,
  8885. configurable: true
  8886. });
  8887. Object.defineProperty(Tools, "AllLogLevel", {
  8888. get: function () {
  8889. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8890. },
  8891. enumerable: true,
  8892. configurable: true
  8893. });
  8894. Tools._AddLogEntry = function (entry) {
  8895. Tools._LogCache = entry + Tools._LogCache;
  8896. if (Tools.OnNewCacheEntry) {
  8897. Tools.OnNewCacheEntry(entry);
  8898. }
  8899. };
  8900. Tools._FormatMessage = function (message) {
  8901. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8902. var date = new Date();
  8903. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8904. };
  8905. Tools._LogDisabled = function (message) {
  8906. // nothing to do
  8907. };
  8908. Tools._LogEnabled = function (message) {
  8909. var formattedMessage = Tools._FormatMessage(message);
  8910. console.log("BJS - " + formattedMessage);
  8911. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8912. Tools._AddLogEntry(entry);
  8913. };
  8914. Tools._WarnDisabled = function (message) {
  8915. // nothing to do
  8916. };
  8917. Tools._WarnEnabled = function (message) {
  8918. var formattedMessage = Tools._FormatMessage(message);
  8919. console.warn("BJS - " + formattedMessage);
  8920. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8921. Tools._AddLogEntry(entry);
  8922. };
  8923. Tools._ErrorDisabled = function (message) {
  8924. // nothing to do
  8925. };
  8926. Tools._ErrorEnabled = function (message) {
  8927. Tools.errorsCount++;
  8928. var formattedMessage = Tools._FormatMessage(message);
  8929. console.error("BJS - " + formattedMessage);
  8930. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8931. Tools._AddLogEntry(entry);
  8932. };
  8933. Object.defineProperty(Tools, "LogCache", {
  8934. get: function () {
  8935. return Tools._LogCache;
  8936. },
  8937. enumerable: true,
  8938. configurable: true
  8939. });
  8940. Tools.ClearLogCache = function () {
  8941. Tools._LogCache = "";
  8942. Tools.errorsCount = 0;
  8943. };
  8944. Object.defineProperty(Tools, "LogLevels", {
  8945. set: function (level) {
  8946. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8947. Tools.Log = Tools._LogEnabled;
  8948. }
  8949. else {
  8950. Tools.Log = Tools._LogDisabled;
  8951. }
  8952. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8953. Tools.Warn = Tools._WarnEnabled;
  8954. }
  8955. else {
  8956. Tools.Warn = Tools._WarnDisabled;
  8957. }
  8958. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8959. Tools.Error = Tools._ErrorEnabled;
  8960. }
  8961. else {
  8962. Tools.Error = Tools._ErrorDisabled;
  8963. }
  8964. },
  8965. enumerable: true,
  8966. configurable: true
  8967. });
  8968. Tools.IsWindowObjectExist = function () {
  8969. return (typeof window) !== "undefined";
  8970. };
  8971. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8972. get: function () {
  8973. return Tools._PerformanceNoneLogLevel;
  8974. },
  8975. enumerable: true,
  8976. configurable: true
  8977. });
  8978. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8979. get: function () {
  8980. return Tools._PerformanceUserMarkLogLevel;
  8981. },
  8982. enumerable: true,
  8983. configurable: true
  8984. });
  8985. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8986. get: function () {
  8987. return Tools._PerformanceConsoleLogLevel;
  8988. },
  8989. enumerable: true,
  8990. configurable: true
  8991. });
  8992. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8993. set: function (level) {
  8994. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8995. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8996. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8997. return;
  8998. }
  8999. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9000. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9001. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9002. return;
  9003. }
  9004. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9005. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9006. },
  9007. enumerable: true,
  9008. configurable: true
  9009. });
  9010. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9011. };
  9012. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9013. };
  9014. Tools._StartUserMark = function (counterName, condition) {
  9015. if (condition === void 0) { condition = true; }
  9016. if (!Tools._performance) {
  9017. if (!Tools.IsWindowObjectExist()) {
  9018. return;
  9019. }
  9020. Tools._performance = window.performance;
  9021. }
  9022. if (!condition || !Tools._performance.mark) {
  9023. return;
  9024. }
  9025. Tools._performance.mark(counterName + "-Begin");
  9026. };
  9027. Tools._EndUserMark = function (counterName, condition) {
  9028. if (condition === void 0) { condition = true; }
  9029. if (!condition || !Tools._performance.mark) {
  9030. return;
  9031. }
  9032. Tools._performance.mark(counterName + "-End");
  9033. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9034. };
  9035. Tools._StartPerformanceConsole = function (counterName, condition) {
  9036. if (condition === void 0) { condition = true; }
  9037. if (!condition) {
  9038. return;
  9039. }
  9040. Tools._StartUserMark(counterName, condition);
  9041. if (console.time) {
  9042. console.time(counterName);
  9043. }
  9044. };
  9045. Tools._EndPerformanceConsole = function (counterName, condition) {
  9046. if (condition === void 0) { condition = true; }
  9047. if (!condition) {
  9048. return;
  9049. }
  9050. Tools._EndUserMark(counterName, condition);
  9051. if (console.time) {
  9052. console.timeEnd(counterName);
  9053. }
  9054. };
  9055. Object.defineProperty(Tools, "Now", {
  9056. get: function () {
  9057. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9058. return window.performance.now();
  9059. }
  9060. return new Date().getTime();
  9061. },
  9062. enumerable: true,
  9063. configurable: true
  9064. });
  9065. /**
  9066. * This method will return the name of the class used to create the instance of the given object.
  9067. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9068. * @param object the object to get the class name from
  9069. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9070. */
  9071. Tools.GetClassName = function (object, isType) {
  9072. if (isType === void 0) { isType = false; }
  9073. var name = null;
  9074. if (!isType && object.getClassName) {
  9075. name = object.getClassName();
  9076. }
  9077. else {
  9078. if (object instanceof Object) {
  9079. var classObj = isType ? object : Object.getPrototypeOf(object);
  9080. name = classObj.constructor["__bjsclassName__"];
  9081. }
  9082. if (!name) {
  9083. name = typeof object;
  9084. }
  9085. }
  9086. return name;
  9087. };
  9088. Tools.First = function (array, predicate) {
  9089. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9090. var el = array_1[_i];
  9091. if (predicate(el)) {
  9092. return el;
  9093. }
  9094. }
  9095. return null;
  9096. };
  9097. /**
  9098. * This method will return the name of the full name of the class, including its owning module (if any).
  9099. * 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).
  9100. * @param object the object to get the class name from
  9101. * @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.
  9102. */
  9103. Tools.getFullClassName = function (object, isType) {
  9104. if (isType === void 0) { isType = false; }
  9105. var className = null;
  9106. var moduleName = null;
  9107. if (!isType && object.getClassName) {
  9108. className = object.getClassName();
  9109. }
  9110. else {
  9111. if (object instanceof Object) {
  9112. var classObj = isType ? object : Object.getPrototypeOf(object);
  9113. className = classObj.constructor["__bjsclassName__"];
  9114. moduleName = classObj.constructor["__bjsmoduleName__"];
  9115. }
  9116. if (!className) {
  9117. className = typeof object;
  9118. }
  9119. }
  9120. if (!className) {
  9121. return null;
  9122. }
  9123. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9124. };
  9125. /**
  9126. * 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.
  9127. * @param array
  9128. */
  9129. Tools.arrayOrStringFeeder = function (array) {
  9130. return function (index) {
  9131. if (index >= array.length) {
  9132. return null;
  9133. }
  9134. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9135. if (val && val.getHashCode) {
  9136. val = val.getHashCode();
  9137. }
  9138. if (typeof val === "string") {
  9139. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9140. }
  9141. return val;
  9142. };
  9143. };
  9144. /**
  9145. * Compute the hashCode of a stream of number
  9146. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9147. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9148. * @return the hash code computed
  9149. */
  9150. Tools.hashCodeFromStream = function (feeder) {
  9151. // Based from here: http://stackoverflow.com/a/7616484/802124
  9152. var hash = 0;
  9153. var index = 0;
  9154. var chr = feeder(index++);
  9155. while (chr != null) {
  9156. hash = ((hash << 5) - hash) + chr;
  9157. hash |= 0; // Convert to 32bit integer
  9158. chr = feeder(index++);
  9159. }
  9160. return hash;
  9161. };
  9162. /**
  9163. * Returns a promise that resolves after the given amount of time.
  9164. * @param delay Number of milliseconds to delay
  9165. * @returns Promise that resolves after the given amount of time
  9166. */
  9167. Tools.DelayAsync = function (delay) {
  9168. return new Promise(function (resolve) {
  9169. setTimeout(function () {
  9170. resolve();
  9171. }, delay);
  9172. });
  9173. };
  9174. Tools.BaseUrl = "";
  9175. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9176. /**
  9177. * Default behaviour for cors in the application.
  9178. * It can be a string if the expected behavior is identical in the entire app.
  9179. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9180. */
  9181. Tools.CorsBehavior = "anonymous";
  9182. Tools.UseFallbackTexture = true;
  9183. /**
  9184. * Use this object to register external classes like custom textures or material
  9185. * to allow the laoders to instantiate them
  9186. */
  9187. Tools.RegisteredExternalClasses = {};
  9188. // Used in case of a texture loading problem
  9189. 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";
  9190. Tools.PreprocessUrl = function (url) {
  9191. return url;
  9192. };
  9193. // Logs
  9194. Tools._NoneLogLevel = 0;
  9195. Tools._MessageLogLevel = 1;
  9196. Tools._WarningLogLevel = 2;
  9197. Tools._ErrorLogLevel = 4;
  9198. Tools._LogCache = "";
  9199. Tools.errorsCount = 0;
  9200. Tools.Log = Tools._LogEnabled;
  9201. Tools.Warn = Tools._WarnEnabled;
  9202. Tools.Error = Tools._ErrorEnabled;
  9203. // Performances
  9204. Tools._PerformanceNoneLogLevel = 0;
  9205. Tools._PerformanceUserMarkLogLevel = 1;
  9206. Tools._PerformanceConsoleLogLevel = 2;
  9207. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9208. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9209. return Tools;
  9210. }());
  9211. BABYLON.Tools = Tools;
  9212. /**
  9213. * This class is used to track a performance counter which is number based.
  9214. * The user has access to many properties which give statistics of different nature
  9215. *
  9216. * The implementer can track two kinds of Performance Counter: time and count
  9217. * 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.
  9218. * 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.
  9219. */
  9220. var PerfCounter = /** @class */ (function () {
  9221. function PerfCounter() {
  9222. this._startMonitoringTime = 0;
  9223. this._min = 0;
  9224. this._max = 0;
  9225. this._average = 0;
  9226. this._lastSecAverage = 0;
  9227. this._current = 0;
  9228. this._totalValueCount = 0;
  9229. this._totalAccumulated = 0;
  9230. this._lastSecAccumulated = 0;
  9231. this._lastSecTime = 0;
  9232. this._lastSecValueCount = 0;
  9233. }
  9234. Object.defineProperty(PerfCounter.prototype, "min", {
  9235. /**
  9236. * Returns the smallest value ever
  9237. */
  9238. get: function () {
  9239. return this._min;
  9240. },
  9241. enumerable: true,
  9242. configurable: true
  9243. });
  9244. Object.defineProperty(PerfCounter.prototype, "max", {
  9245. /**
  9246. * Returns the biggest value ever
  9247. */
  9248. get: function () {
  9249. return this._max;
  9250. },
  9251. enumerable: true,
  9252. configurable: true
  9253. });
  9254. Object.defineProperty(PerfCounter.prototype, "average", {
  9255. /**
  9256. * Returns the average value since the performance counter is running
  9257. */
  9258. get: function () {
  9259. return this._average;
  9260. },
  9261. enumerable: true,
  9262. configurable: true
  9263. });
  9264. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9265. /**
  9266. * Returns the average value of the last second the counter was monitored
  9267. */
  9268. get: function () {
  9269. return this._lastSecAverage;
  9270. },
  9271. enumerable: true,
  9272. configurable: true
  9273. });
  9274. Object.defineProperty(PerfCounter.prototype, "current", {
  9275. /**
  9276. * Returns the current value
  9277. */
  9278. get: function () {
  9279. return this._current;
  9280. },
  9281. enumerable: true,
  9282. configurable: true
  9283. });
  9284. Object.defineProperty(PerfCounter.prototype, "total", {
  9285. get: function () {
  9286. return this._totalAccumulated;
  9287. },
  9288. enumerable: true,
  9289. configurable: true
  9290. });
  9291. Object.defineProperty(PerfCounter.prototype, "count", {
  9292. get: function () {
  9293. return this._totalValueCount;
  9294. },
  9295. enumerable: true,
  9296. configurable: true
  9297. });
  9298. /**
  9299. * Call this method to start monitoring a new frame.
  9300. * 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.
  9301. */
  9302. PerfCounter.prototype.fetchNewFrame = function () {
  9303. this._totalValueCount++;
  9304. this._current = 0;
  9305. this._lastSecValueCount++;
  9306. };
  9307. /**
  9308. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9309. * @param newCount the count value to add to the monitored count
  9310. * @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.
  9311. */
  9312. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9313. if (!PerfCounter.Enabled) {
  9314. return;
  9315. }
  9316. this._current += newCount;
  9317. if (fetchResult) {
  9318. this._fetchResult();
  9319. }
  9320. };
  9321. /**
  9322. * Start monitoring this performance counter
  9323. */
  9324. PerfCounter.prototype.beginMonitoring = function () {
  9325. if (!PerfCounter.Enabled) {
  9326. return;
  9327. }
  9328. this._startMonitoringTime = Tools.Now;
  9329. };
  9330. /**
  9331. * Compute the time lapsed since the previous beginMonitoring() call.
  9332. * @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
  9333. */
  9334. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9335. if (newFrame === void 0) { newFrame = true; }
  9336. if (!PerfCounter.Enabled) {
  9337. return;
  9338. }
  9339. if (newFrame) {
  9340. this.fetchNewFrame();
  9341. }
  9342. var currentTime = Tools.Now;
  9343. this._current = currentTime - this._startMonitoringTime;
  9344. if (newFrame) {
  9345. this._fetchResult();
  9346. }
  9347. };
  9348. PerfCounter.prototype._fetchResult = function () {
  9349. this._totalAccumulated += this._current;
  9350. this._lastSecAccumulated += this._current;
  9351. // Min/Max update
  9352. this._min = Math.min(this._min, this._current);
  9353. this._max = Math.max(this._max, this._current);
  9354. this._average = this._totalAccumulated / this._totalValueCount;
  9355. // Reset last sec?
  9356. var now = Tools.Now;
  9357. if ((now - this._lastSecTime) > 1000) {
  9358. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9359. this._lastSecTime = now;
  9360. this._lastSecAccumulated = 0;
  9361. this._lastSecValueCount = 0;
  9362. }
  9363. };
  9364. PerfCounter.Enabled = true;
  9365. return PerfCounter;
  9366. }());
  9367. BABYLON.PerfCounter = PerfCounter;
  9368. /**
  9369. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9370. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9371. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9372. * @param name The name of the class, case should be preserved
  9373. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9374. */
  9375. function className(name, module) {
  9376. return function (target) {
  9377. target["__bjsclassName__"] = name;
  9378. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9379. };
  9380. }
  9381. BABYLON.className = className;
  9382. /**
  9383. * An implementation of a loop for asynchronous functions.
  9384. */
  9385. var AsyncLoop = /** @class */ (function () {
  9386. /**
  9387. * Constroctor.
  9388. * @param iterations the number of iterations.
  9389. * @param _fn the function to run each iteration
  9390. * @param _successCallback the callback that will be called upon succesful execution
  9391. * @param offset starting offset.
  9392. */
  9393. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9394. if (offset === void 0) { offset = 0; }
  9395. this.iterations = iterations;
  9396. this._fn = _fn;
  9397. this._successCallback = _successCallback;
  9398. this.index = offset - 1;
  9399. this._done = false;
  9400. }
  9401. /**
  9402. * Execute the next iteration. Must be called after the last iteration was finished.
  9403. */
  9404. AsyncLoop.prototype.executeNext = function () {
  9405. if (!this._done) {
  9406. if (this.index + 1 < this.iterations) {
  9407. ++this.index;
  9408. this._fn(this);
  9409. }
  9410. else {
  9411. this.breakLoop();
  9412. }
  9413. }
  9414. };
  9415. /**
  9416. * Break the loop and run the success callback.
  9417. */
  9418. AsyncLoop.prototype.breakLoop = function () {
  9419. this._done = true;
  9420. this._successCallback();
  9421. };
  9422. /**
  9423. * Helper function
  9424. */
  9425. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9426. if (offset === void 0) { offset = 0; }
  9427. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9428. loop.executeNext();
  9429. return loop;
  9430. };
  9431. /**
  9432. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9433. * @param iterations total number of iterations
  9434. * @param syncedIterations number of synchronous iterations in each async iteration.
  9435. * @param fn the function to call each iteration.
  9436. * @param callback a success call back that will be called when iterating stops.
  9437. * @param breakFunction a break condition (optional)
  9438. * @param timeout timeout settings for the setTimeout function. default - 0.
  9439. * @constructor
  9440. */
  9441. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9442. if (timeout === void 0) { timeout = 0; }
  9443. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9444. if (breakFunction && breakFunction())
  9445. loop.breakLoop();
  9446. else {
  9447. setTimeout(function () {
  9448. for (var i = 0; i < syncedIterations; ++i) {
  9449. var iteration = (loop.index * syncedIterations) + i;
  9450. if (iteration >= iterations)
  9451. break;
  9452. fn(iteration);
  9453. if (breakFunction && breakFunction()) {
  9454. loop.breakLoop();
  9455. break;
  9456. }
  9457. }
  9458. loop.executeNext();
  9459. }, timeout);
  9460. }
  9461. }, callback);
  9462. };
  9463. return AsyncLoop;
  9464. }());
  9465. BABYLON.AsyncLoop = AsyncLoop;
  9466. })(BABYLON || (BABYLON = {}));
  9467. //# sourceMappingURL=babylon.tools.js.map
  9468. "use strict";
  9469. var BABYLON;
  9470. (function (BABYLON) {
  9471. var PromiseStates;
  9472. (function (PromiseStates) {
  9473. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9474. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9475. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9476. })(PromiseStates || (PromiseStates = {}));
  9477. var FulFillmentAgregator = /** @class */ (function () {
  9478. function FulFillmentAgregator() {
  9479. this.count = 0;
  9480. this.target = 0;
  9481. this.results = [];
  9482. }
  9483. return FulFillmentAgregator;
  9484. }());
  9485. var InternalPromise = /** @class */ (function () {
  9486. function InternalPromise(resolver) {
  9487. var _this = this;
  9488. this._state = PromiseStates.Pending;
  9489. this._children = new Array();
  9490. this._rejectWasConsumed = false;
  9491. if (!resolver) {
  9492. return;
  9493. }
  9494. try {
  9495. resolver(function (value) {
  9496. _this._resolve(value);
  9497. }, function (reason) {
  9498. _this._reject(reason);
  9499. });
  9500. }
  9501. catch (e) {
  9502. this._reject(e);
  9503. }
  9504. }
  9505. InternalPromise.prototype.catch = function (onRejected) {
  9506. return this.then(undefined, onRejected);
  9507. };
  9508. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9509. var _this = this;
  9510. var newPromise = new InternalPromise();
  9511. newPromise._onFulfilled = onFulfilled;
  9512. newPromise._onRejected = onRejected;
  9513. // Composition
  9514. this._children.push(newPromise);
  9515. if (this._state !== PromiseStates.Pending) {
  9516. BABYLON.Tools.SetImmediate(function () {
  9517. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9518. var returnedValue = newPromise._resolve(_this._result);
  9519. if (returnedValue !== undefined && returnedValue !== null) {
  9520. if (returnedValue._state !== undefined) {
  9521. var returnedPromise = returnedValue;
  9522. newPromise._children.push(returnedPromise);
  9523. newPromise = returnedPromise;
  9524. }
  9525. else {
  9526. newPromise._result = returnedValue;
  9527. }
  9528. }
  9529. }
  9530. else {
  9531. newPromise._reject(_this._reason);
  9532. }
  9533. });
  9534. }
  9535. return newPromise;
  9536. };
  9537. InternalPromise.prototype._moveChildren = function (children) {
  9538. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9539. if (this._state === PromiseStates.Fulfilled) {
  9540. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9541. var child = _b[_i];
  9542. child._resolve(this._result);
  9543. }
  9544. }
  9545. else if (this._state === PromiseStates.Rejected) {
  9546. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9547. var child = _d[_c];
  9548. child._reject(this._reason);
  9549. }
  9550. }
  9551. var _a;
  9552. };
  9553. InternalPromise.prototype._resolve = function (value) {
  9554. try {
  9555. this._state = PromiseStates.Fulfilled;
  9556. var returnedValue = null;
  9557. if (this._onFulfilled) {
  9558. returnedValue = this._onFulfilled(value);
  9559. }
  9560. if (returnedValue !== undefined && returnedValue !== null) {
  9561. if (returnedValue._state !== undefined) {
  9562. // Transmit children
  9563. var returnedPromise = returnedValue;
  9564. returnedPromise._moveChildren(this._children);
  9565. value = returnedPromise._result;
  9566. }
  9567. else {
  9568. value = returnedValue;
  9569. }
  9570. }
  9571. this._result = value;
  9572. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9573. var child = _a[_i];
  9574. child._resolve(value);
  9575. }
  9576. this._children.length = 0;
  9577. delete this._onFulfilled;
  9578. delete this._onRejected;
  9579. }
  9580. catch (e) {
  9581. this._reject(e, true);
  9582. }
  9583. };
  9584. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9585. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9586. this._state = PromiseStates.Rejected;
  9587. this._reason = reason;
  9588. if (this._onRejected && !onLocalThrow) {
  9589. try {
  9590. this._onRejected(reason);
  9591. this._rejectWasConsumed = true;
  9592. }
  9593. catch (e) {
  9594. reason = e;
  9595. }
  9596. }
  9597. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9598. var child = _a[_i];
  9599. if (this._rejectWasConsumed) {
  9600. child._resolve(null);
  9601. }
  9602. else {
  9603. child._reject(reason);
  9604. }
  9605. }
  9606. this._children.length = 0;
  9607. delete this._onFulfilled;
  9608. delete this._onRejected;
  9609. };
  9610. InternalPromise.resolve = function (value) {
  9611. var newPromise = new InternalPromise();
  9612. newPromise._resolve(value);
  9613. return newPromise;
  9614. };
  9615. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9616. promise.then(function (value) {
  9617. agregator.results[index] = value;
  9618. agregator.count++;
  9619. if (agregator.count === agregator.target) {
  9620. agregator.rootPromise._resolve(agregator.results);
  9621. }
  9622. return null;
  9623. }, function (reason) {
  9624. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9625. agregator.rootPromise._reject(reason);
  9626. }
  9627. });
  9628. };
  9629. InternalPromise.all = function (promises) {
  9630. var newPromise = new InternalPromise();
  9631. var agregator = new FulFillmentAgregator();
  9632. agregator.target = promises.length;
  9633. agregator.rootPromise = newPromise;
  9634. if (promises.length) {
  9635. for (var index = 0; index < promises.length; index++) {
  9636. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9637. }
  9638. }
  9639. else {
  9640. newPromise._resolve([]);
  9641. }
  9642. return newPromise;
  9643. };
  9644. InternalPromise.race = function (promises) {
  9645. var newPromise = new InternalPromise();
  9646. if (promises.length) {
  9647. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9648. var promise = promises_1[_i];
  9649. promise.then(function (value) {
  9650. if (newPromise) {
  9651. newPromise._resolve(value);
  9652. newPromise = null;
  9653. }
  9654. return null;
  9655. }, function (reason) {
  9656. if (newPromise) {
  9657. newPromise._reject(reason);
  9658. newPromise = null;
  9659. }
  9660. });
  9661. }
  9662. }
  9663. return newPromise;
  9664. };
  9665. return InternalPromise;
  9666. }());
  9667. /**
  9668. * Helper class that provides a small promise polyfill
  9669. */
  9670. var PromisePolyfill = /** @class */ (function () {
  9671. function PromisePolyfill() {
  9672. }
  9673. /**
  9674. * Static function used to check if the polyfill is required
  9675. * If this is the case then the function will inject the polyfill to window.Promise
  9676. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9677. */
  9678. PromisePolyfill.Apply = function (force) {
  9679. if (force === void 0) { force = false; }
  9680. if (force || typeof Promise === 'undefined') {
  9681. var root = window;
  9682. root.Promise = InternalPromise;
  9683. }
  9684. };
  9685. return PromisePolyfill;
  9686. }());
  9687. BABYLON.PromisePolyfill = PromisePolyfill;
  9688. })(BABYLON || (BABYLON = {}));
  9689. //# sourceMappingURL=babylon.promise.js.map
  9690. "use strict";
  9691. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9692. var BABYLON;
  9693. (function (BABYLON) {
  9694. /**
  9695. * Helper class to push actions to a pool of workers.
  9696. */
  9697. var WorkerPool = /** @class */ (function () {
  9698. /**
  9699. * Constructor
  9700. * @param workers Array of workers to use for actions
  9701. */
  9702. function WorkerPool(workers) {
  9703. this._pendingActions = new Array();
  9704. this._workerInfos = workers.map(function (worker) { return ({
  9705. worker: worker,
  9706. active: false
  9707. }); });
  9708. }
  9709. /**
  9710. * Terminates all workers and clears any pending actions.
  9711. */
  9712. WorkerPool.prototype.dispose = function () {
  9713. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9714. var workerInfo = _a[_i];
  9715. workerInfo.worker.terminate();
  9716. }
  9717. delete this._workerInfos;
  9718. delete this._pendingActions;
  9719. };
  9720. /**
  9721. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9722. * pended until a worker has completed its action.
  9723. * @param action The action to perform. Call onComplete when the action is complete.
  9724. */
  9725. WorkerPool.prototype.push = function (action) {
  9726. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9727. var workerInfo = _a[_i];
  9728. if (!workerInfo.active) {
  9729. this._execute(workerInfo, action);
  9730. return;
  9731. }
  9732. }
  9733. this._pendingActions.push(action);
  9734. };
  9735. WorkerPool.prototype._execute = function (workerInfo, action) {
  9736. var _this = this;
  9737. workerInfo.active = true;
  9738. action(workerInfo.worker, function () {
  9739. workerInfo.active = false;
  9740. var nextAction = _this._pendingActions.shift();
  9741. if (nextAction) {
  9742. _this._execute(workerInfo, nextAction);
  9743. }
  9744. });
  9745. };
  9746. return WorkerPool;
  9747. }());
  9748. BABYLON.WorkerPool = WorkerPool;
  9749. })(BABYLON || (BABYLON = {}));
  9750. //# sourceMappingURL=babylon.workerPool.js.map
  9751. "use strict";
  9752. var BABYLON;
  9753. (function (BABYLON) {
  9754. var _AlphaState = /** @class */ (function () {
  9755. /**
  9756. * Initializes the state.
  9757. */
  9758. function _AlphaState() {
  9759. this._isAlphaBlendDirty = false;
  9760. this._isBlendFunctionParametersDirty = false;
  9761. this._isBlendEquationParametersDirty = false;
  9762. this._isBlendConstantsDirty = false;
  9763. this._alphaBlend = false;
  9764. this._blendFunctionParameters = new Array(4);
  9765. this._blendEquationParameters = new Array(2);
  9766. this._blendConstants = new Array(4);
  9767. this.reset();
  9768. }
  9769. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9770. get: function () {
  9771. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9772. },
  9773. enumerable: true,
  9774. configurable: true
  9775. });
  9776. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9777. get: function () {
  9778. return this._alphaBlend;
  9779. },
  9780. set: function (value) {
  9781. if (this._alphaBlend === value) {
  9782. return;
  9783. }
  9784. this._alphaBlend = value;
  9785. this._isAlphaBlendDirty = true;
  9786. },
  9787. enumerable: true,
  9788. configurable: true
  9789. });
  9790. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9791. if (this._blendConstants[0] === r &&
  9792. this._blendConstants[1] === g &&
  9793. this._blendConstants[2] === b &&
  9794. this._blendConstants[3] === a) {
  9795. return;
  9796. }
  9797. this._blendConstants[0] = r;
  9798. this._blendConstants[1] = g;
  9799. this._blendConstants[2] = b;
  9800. this._blendConstants[3] = a;
  9801. this._isBlendConstantsDirty = true;
  9802. };
  9803. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9804. if (this._blendFunctionParameters[0] === value0 &&
  9805. this._blendFunctionParameters[1] === value1 &&
  9806. this._blendFunctionParameters[2] === value2 &&
  9807. this._blendFunctionParameters[3] === value3) {
  9808. return;
  9809. }
  9810. this._blendFunctionParameters[0] = value0;
  9811. this._blendFunctionParameters[1] = value1;
  9812. this._blendFunctionParameters[2] = value2;
  9813. this._blendFunctionParameters[3] = value3;
  9814. this._isBlendFunctionParametersDirty = true;
  9815. };
  9816. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9817. if (this._blendEquationParameters[0] === rgb &&
  9818. this._blendEquationParameters[1] === alpha) {
  9819. return;
  9820. }
  9821. this._blendEquationParameters[0] = rgb;
  9822. this._blendEquationParameters[1] = alpha;
  9823. this._isBlendEquationParametersDirty = true;
  9824. };
  9825. _AlphaState.prototype.reset = function () {
  9826. this._alphaBlend = false;
  9827. this._blendFunctionParameters[0] = null;
  9828. this._blendFunctionParameters[1] = null;
  9829. this._blendFunctionParameters[2] = null;
  9830. this._blendFunctionParameters[3] = null;
  9831. this._blendEquationParameters[0] = null;
  9832. this._blendEquationParameters[1] = null;
  9833. this._blendConstants[0] = null;
  9834. this._blendConstants[1] = null;
  9835. this._blendConstants[2] = null;
  9836. this._blendConstants[3] = null;
  9837. this._isAlphaBlendDirty = true;
  9838. this._isBlendFunctionParametersDirty = false;
  9839. this._isBlendEquationParametersDirty = false;
  9840. this._isBlendConstantsDirty = false;
  9841. };
  9842. _AlphaState.prototype.apply = function (gl) {
  9843. if (!this.isDirty) {
  9844. return;
  9845. }
  9846. // Alpha blend
  9847. if (this._isAlphaBlendDirty) {
  9848. if (this._alphaBlend) {
  9849. gl.enable(gl.BLEND);
  9850. }
  9851. else {
  9852. gl.disable(gl.BLEND);
  9853. }
  9854. this._isAlphaBlendDirty = false;
  9855. }
  9856. // Alpha function
  9857. if (this._isBlendFunctionParametersDirty) {
  9858. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9859. this._isBlendFunctionParametersDirty = false;
  9860. }
  9861. // Alpha equation
  9862. if (this._isBlendEquationParametersDirty) {
  9863. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9864. this._isBlendEquationParametersDirty = false;
  9865. }
  9866. // Constants
  9867. if (this._isBlendConstantsDirty) {
  9868. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9869. this._isBlendConstantsDirty = false;
  9870. }
  9871. };
  9872. return _AlphaState;
  9873. }());
  9874. BABYLON._AlphaState = _AlphaState;
  9875. })(BABYLON || (BABYLON = {}));
  9876. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9877. "use strict";
  9878. var BABYLON;
  9879. (function (BABYLON) {
  9880. var _DepthCullingState = /** @class */ (function () {
  9881. /**
  9882. * Initializes the state.
  9883. */
  9884. function _DepthCullingState() {
  9885. this._isDepthTestDirty = false;
  9886. this._isDepthMaskDirty = false;
  9887. this._isDepthFuncDirty = false;
  9888. this._isCullFaceDirty = false;
  9889. this._isCullDirty = false;
  9890. this._isZOffsetDirty = false;
  9891. this._isFrontFaceDirty = false;
  9892. this.reset();
  9893. }
  9894. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9895. get: function () {
  9896. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9897. },
  9898. enumerable: true,
  9899. configurable: true
  9900. });
  9901. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9902. get: function () {
  9903. return this._zOffset;
  9904. },
  9905. set: function (value) {
  9906. if (this._zOffset === value) {
  9907. return;
  9908. }
  9909. this._zOffset = value;
  9910. this._isZOffsetDirty = true;
  9911. },
  9912. enumerable: true,
  9913. configurable: true
  9914. });
  9915. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9916. get: function () {
  9917. return this._cullFace;
  9918. },
  9919. set: function (value) {
  9920. if (this._cullFace === value) {
  9921. return;
  9922. }
  9923. this._cullFace = value;
  9924. this._isCullFaceDirty = true;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9930. get: function () {
  9931. return this._cull;
  9932. },
  9933. set: function (value) {
  9934. if (this._cull === value) {
  9935. return;
  9936. }
  9937. this._cull = value;
  9938. this._isCullDirty = true;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9944. get: function () {
  9945. return this._depthFunc;
  9946. },
  9947. set: function (value) {
  9948. if (this._depthFunc === value) {
  9949. return;
  9950. }
  9951. this._depthFunc = value;
  9952. this._isDepthFuncDirty = true;
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9958. get: function () {
  9959. return this._depthMask;
  9960. },
  9961. set: function (value) {
  9962. if (this._depthMask === value) {
  9963. return;
  9964. }
  9965. this._depthMask = value;
  9966. this._isDepthMaskDirty = true;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9972. get: function () {
  9973. return this._depthTest;
  9974. },
  9975. set: function (value) {
  9976. if (this._depthTest === value) {
  9977. return;
  9978. }
  9979. this._depthTest = value;
  9980. this._isDepthTestDirty = true;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9986. get: function () {
  9987. return this._frontFace;
  9988. },
  9989. set: function (value) {
  9990. if (this._frontFace === value) {
  9991. return;
  9992. }
  9993. this._frontFace = value;
  9994. this._isFrontFaceDirty = true;
  9995. },
  9996. enumerable: true,
  9997. configurable: true
  9998. });
  9999. _DepthCullingState.prototype.reset = function () {
  10000. this._depthMask = true;
  10001. this._depthTest = true;
  10002. this._depthFunc = null;
  10003. this._cullFace = null;
  10004. this._cull = null;
  10005. this._zOffset = 0;
  10006. this._frontFace = null;
  10007. this._isDepthTestDirty = true;
  10008. this._isDepthMaskDirty = true;
  10009. this._isDepthFuncDirty = false;
  10010. this._isCullFaceDirty = false;
  10011. this._isCullDirty = false;
  10012. this._isZOffsetDirty = false;
  10013. this._isFrontFaceDirty = false;
  10014. };
  10015. _DepthCullingState.prototype.apply = function (gl) {
  10016. if (!this.isDirty) {
  10017. return;
  10018. }
  10019. // Cull
  10020. if (this._isCullDirty) {
  10021. if (this.cull) {
  10022. gl.enable(gl.CULL_FACE);
  10023. }
  10024. else {
  10025. gl.disable(gl.CULL_FACE);
  10026. }
  10027. this._isCullDirty = false;
  10028. }
  10029. // Cull face
  10030. if (this._isCullFaceDirty) {
  10031. gl.cullFace(this.cullFace);
  10032. this._isCullFaceDirty = false;
  10033. }
  10034. // Depth mask
  10035. if (this._isDepthMaskDirty) {
  10036. gl.depthMask(this.depthMask);
  10037. this._isDepthMaskDirty = false;
  10038. }
  10039. // Depth test
  10040. if (this._isDepthTestDirty) {
  10041. if (this.depthTest) {
  10042. gl.enable(gl.DEPTH_TEST);
  10043. }
  10044. else {
  10045. gl.disable(gl.DEPTH_TEST);
  10046. }
  10047. this._isDepthTestDirty = false;
  10048. }
  10049. // Depth func
  10050. if (this._isDepthFuncDirty) {
  10051. gl.depthFunc(this.depthFunc);
  10052. this._isDepthFuncDirty = false;
  10053. }
  10054. // zOffset
  10055. if (this._isZOffsetDirty) {
  10056. if (this.zOffset) {
  10057. gl.enable(gl.POLYGON_OFFSET_FILL);
  10058. gl.polygonOffset(this.zOffset, 0);
  10059. }
  10060. else {
  10061. gl.disable(gl.POLYGON_OFFSET_FILL);
  10062. }
  10063. this._isZOffsetDirty = false;
  10064. }
  10065. // Front face
  10066. if (this._isFrontFaceDirty) {
  10067. gl.frontFace(this.frontFace);
  10068. this._isFrontFaceDirty = false;
  10069. }
  10070. };
  10071. return _DepthCullingState;
  10072. }());
  10073. BABYLON._DepthCullingState = _DepthCullingState;
  10074. })(BABYLON || (BABYLON = {}));
  10075. //# sourceMappingURL=babylon.depthCullingState.js.map
  10076. "use strict";
  10077. var BABYLON;
  10078. (function (BABYLON) {
  10079. var _StencilState = /** @class */ (function () {
  10080. function _StencilState() {
  10081. this._isStencilTestDirty = false;
  10082. this._isStencilMaskDirty = false;
  10083. this._isStencilFuncDirty = false;
  10084. this._isStencilOpDirty = false;
  10085. this.reset();
  10086. }
  10087. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10088. get: function () {
  10089. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10090. },
  10091. enumerable: true,
  10092. configurable: true
  10093. });
  10094. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10095. get: function () {
  10096. return this._stencilFunc;
  10097. },
  10098. set: function (value) {
  10099. if (this._stencilFunc === value) {
  10100. return;
  10101. }
  10102. this._stencilFunc = value;
  10103. this._isStencilFuncDirty = true;
  10104. },
  10105. enumerable: true,
  10106. configurable: true
  10107. });
  10108. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10109. get: function () {
  10110. return this._stencilFuncRef;
  10111. },
  10112. set: function (value) {
  10113. if (this._stencilFuncRef === value) {
  10114. return;
  10115. }
  10116. this._stencilFuncRef = value;
  10117. this._isStencilFuncDirty = true;
  10118. },
  10119. enumerable: true,
  10120. configurable: true
  10121. });
  10122. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10123. get: function () {
  10124. return this._stencilFuncMask;
  10125. },
  10126. set: function (value) {
  10127. if (this._stencilFuncMask === value) {
  10128. return;
  10129. }
  10130. this._stencilFuncMask = value;
  10131. this._isStencilFuncDirty = true;
  10132. },
  10133. enumerable: true,
  10134. configurable: true
  10135. });
  10136. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10137. get: function () {
  10138. return this._stencilOpStencilFail;
  10139. },
  10140. set: function (value) {
  10141. if (this._stencilOpStencilFail === value) {
  10142. return;
  10143. }
  10144. this._stencilOpStencilFail = value;
  10145. this._isStencilOpDirty = true;
  10146. },
  10147. enumerable: true,
  10148. configurable: true
  10149. });
  10150. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10151. get: function () {
  10152. return this._stencilOpDepthFail;
  10153. },
  10154. set: function (value) {
  10155. if (this._stencilOpDepthFail === value) {
  10156. return;
  10157. }
  10158. this._stencilOpDepthFail = value;
  10159. this._isStencilOpDirty = true;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10165. get: function () {
  10166. return this._stencilOpStencilDepthPass;
  10167. },
  10168. set: function (value) {
  10169. if (this._stencilOpStencilDepthPass === value) {
  10170. return;
  10171. }
  10172. this._stencilOpStencilDepthPass = value;
  10173. this._isStencilOpDirty = true;
  10174. },
  10175. enumerable: true,
  10176. configurable: true
  10177. });
  10178. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10179. get: function () {
  10180. return this._stencilMask;
  10181. },
  10182. set: function (value) {
  10183. if (this._stencilMask === value) {
  10184. return;
  10185. }
  10186. this._stencilMask = value;
  10187. this._isStencilMaskDirty = true;
  10188. },
  10189. enumerable: true,
  10190. configurable: true
  10191. });
  10192. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10193. get: function () {
  10194. return this._stencilTest;
  10195. },
  10196. set: function (value) {
  10197. if (this._stencilTest === value) {
  10198. return;
  10199. }
  10200. this._stencilTest = value;
  10201. this._isStencilTestDirty = true;
  10202. },
  10203. enumerable: true,
  10204. configurable: true
  10205. });
  10206. _StencilState.prototype.reset = function () {
  10207. this._stencilTest = false;
  10208. this._stencilMask = 0xFF;
  10209. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10210. this._stencilFuncRef = 1;
  10211. this._stencilFuncMask = 0xFF;
  10212. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10213. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10214. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10215. this._isStencilTestDirty = true;
  10216. this._isStencilMaskDirty = true;
  10217. this._isStencilFuncDirty = true;
  10218. this._isStencilOpDirty = true;
  10219. };
  10220. _StencilState.prototype.apply = function (gl) {
  10221. if (!this.isDirty) {
  10222. return;
  10223. }
  10224. // Stencil test
  10225. if (this._isStencilTestDirty) {
  10226. if (this.stencilTest) {
  10227. gl.enable(gl.STENCIL_TEST);
  10228. }
  10229. else {
  10230. gl.disable(gl.STENCIL_TEST);
  10231. }
  10232. this._isStencilTestDirty = false;
  10233. }
  10234. // Stencil mask
  10235. if (this._isStencilMaskDirty) {
  10236. gl.stencilMask(this.stencilMask);
  10237. this._isStencilMaskDirty = false;
  10238. }
  10239. // Stencil func
  10240. if (this._isStencilFuncDirty) {
  10241. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10242. this._isStencilFuncDirty = false;
  10243. }
  10244. // Stencil op
  10245. if (this._isStencilOpDirty) {
  10246. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10247. this._isStencilOpDirty = false;
  10248. }
  10249. };
  10250. return _StencilState;
  10251. }());
  10252. BABYLON._StencilState = _StencilState;
  10253. })(BABYLON || (BABYLON = {}));
  10254. //# sourceMappingURL=babylon.stencilState.js.map
  10255. "use strict";
  10256. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10257. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10258. s = arguments[i];
  10259. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10260. t[p] = s[p];
  10261. }
  10262. return t;
  10263. };
  10264. var BABYLON;
  10265. (function (BABYLON) {
  10266. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10267. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10268. };
  10269. var compileRawShader = function (gl, source, type) {
  10270. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10271. gl.shaderSource(shader, source);
  10272. gl.compileShader(shader);
  10273. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10274. var log = gl.getShaderInfoLog(shader);
  10275. if (log) {
  10276. throw new Error(log);
  10277. }
  10278. }
  10279. if (!shader) {
  10280. throw new Error("Something went wrong while compile the shader.");
  10281. }
  10282. return shader;
  10283. };
  10284. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10285. var magFilter = gl.NEAREST;
  10286. var minFilter = gl.NEAREST;
  10287. switch (samplingMode) {
  10288. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10289. magFilter = gl.LINEAR;
  10290. if (generateMipMaps) {
  10291. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10292. }
  10293. else {
  10294. minFilter = gl.LINEAR;
  10295. }
  10296. break;
  10297. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10298. magFilter = gl.LINEAR;
  10299. if (generateMipMaps) {
  10300. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10301. }
  10302. else {
  10303. minFilter = gl.LINEAR;
  10304. }
  10305. break;
  10306. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10307. magFilter = gl.NEAREST;
  10308. if (generateMipMaps) {
  10309. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10310. }
  10311. else {
  10312. minFilter = gl.NEAREST;
  10313. }
  10314. break;
  10315. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10316. magFilter = gl.NEAREST;
  10317. if (generateMipMaps) {
  10318. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10319. }
  10320. else {
  10321. minFilter = gl.NEAREST;
  10322. }
  10323. break;
  10324. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10325. magFilter = gl.NEAREST;
  10326. if (generateMipMaps) {
  10327. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10328. }
  10329. else {
  10330. minFilter = gl.LINEAR;
  10331. }
  10332. break;
  10333. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10334. magFilter = gl.NEAREST;
  10335. if (generateMipMaps) {
  10336. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10337. }
  10338. else {
  10339. minFilter = gl.LINEAR;
  10340. }
  10341. break;
  10342. case BABYLON.Texture.NEAREST_LINEAR:
  10343. magFilter = gl.NEAREST;
  10344. minFilter = gl.LINEAR;
  10345. break;
  10346. case BABYLON.Texture.NEAREST_NEAREST:
  10347. magFilter = gl.NEAREST;
  10348. minFilter = gl.NEAREST;
  10349. break;
  10350. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10351. magFilter = gl.LINEAR;
  10352. if (generateMipMaps) {
  10353. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10354. }
  10355. else {
  10356. minFilter = gl.NEAREST;
  10357. }
  10358. break;
  10359. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10360. magFilter = gl.LINEAR;
  10361. if (generateMipMaps) {
  10362. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10363. }
  10364. else {
  10365. minFilter = gl.NEAREST;
  10366. }
  10367. break;
  10368. case BABYLON.Texture.LINEAR_LINEAR:
  10369. magFilter = gl.LINEAR;
  10370. minFilter = gl.LINEAR;
  10371. break;
  10372. case BABYLON.Texture.LINEAR_NEAREST:
  10373. magFilter = gl.LINEAR;
  10374. minFilter = gl.NEAREST;
  10375. break;
  10376. }
  10377. return {
  10378. min: minFilter,
  10379. mag: magFilter
  10380. };
  10381. };
  10382. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10383. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10384. var img;
  10385. var onload = function () {
  10386. loadedImages[index] = img;
  10387. loadedImages._internalCount++;
  10388. if (scene) {
  10389. scene._removePendingData(img);
  10390. }
  10391. if (loadedImages._internalCount === 6) {
  10392. onfinish(loadedImages);
  10393. }
  10394. };
  10395. var onerror = function (message, exception) {
  10396. if (scene) {
  10397. scene._removePendingData(img);
  10398. }
  10399. if (onErrorCallBack) {
  10400. onErrorCallBack(message, exception);
  10401. }
  10402. };
  10403. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10404. if (scene) {
  10405. scene._addPendingData(img);
  10406. }
  10407. };
  10408. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10409. if (onError === void 0) { onError = null; }
  10410. var loadedImages = [];
  10411. loadedImages._internalCount = 0;
  10412. for (var index = 0; index < 6; index++) {
  10413. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10414. }
  10415. };
  10416. var BufferPointer = /** @class */ (function () {
  10417. function BufferPointer() {
  10418. }
  10419. return BufferPointer;
  10420. }());
  10421. var InstancingAttributeInfo = /** @class */ (function () {
  10422. function InstancingAttributeInfo() {
  10423. }
  10424. return InstancingAttributeInfo;
  10425. }());
  10426. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10427. /**
  10428. * Define options used to create a render target texture
  10429. */
  10430. var RenderTargetCreationOptions = /** @class */ (function () {
  10431. function RenderTargetCreationOptions() {
  10432. }
  10433. return RenderTargetCreationOptions;
  10434. }());
  10435. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10436. /**
  10437. * Define options used to create a depth texture
  10438. */
  10439. var DepthTextureCreationOptions = /** @class */ (function () {
  10440. function DepthTextureCreationOptions() {
  10441. }
  10442. return DepthTextureCreationOptions;
  10443. }());
  10444. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10445. /**
  10446. * Regroup several parameters relative to the browser in use
  10447. */
  10448. var EngineCapabilities = /** @class */ (function () {
  10449. function EngineCapabilities() {
  10450. }
  10451. return EngineCapabilities;
  10452. }());
  10453. BABYLON.EngineCapabilities = EngineCapabilities;
  10454. /**
  10455. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10456. */
  10457. var Engine = /** @class */ (function () {
  10458. /**
  10459. * @constructor
  10460. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10461. * @param antialias defines enable antialiasing (default: false)
  10462. * @param options defines further options to be sent to the getContext() function
  10463. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10464. */
  10465. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10466. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10467. var _this = this;
  10468. // Public members
  10469. this.forcePOTTextures = false;
  10470. this.isFullscreen = false;
  10471. this.isPointerLock = false;
  10472. this.cullBackFaces = true;
  10473. this.renderEvenInBackground = true;
  10474. this.preventCacheWipeBetweenFrames = false;
  10475. /**
  10476. * To enable/disable IDB support and avoid XHR on .manifest
  10477. **/
  10478. this.enableOfflineSupport = false;
  10479. this.scenes = new Array();
  10480. this.postProcesses = new Array();
  10481. // Observables
  10482. /**
  10483. * Observable event triggered each time the rendering canvas is resized
  10484. */
  10485. this.onResizeObservable = new BABYLON.Observable();
  10486. /**
  10487. * Observable event triggered each time the canvas loses focus
  10488. */
  10489. this.onCanvasBlurObservable = new BABYLON.Observable();
  10490. /**
  10491. * Observable event triggered each time the canvas gains focus
  10492. */
  10493. this.onCanvasFocusObservable = new BABYLON.Observable();
  10494. /**
  10495. * Observable event triggered each time the canvas receives pointerout event
  10496. */
  10497. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10498. /**
  10499. * Observable event triggered before each texture is initialized
  10500. */
  10501. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10502. //WebVR
  10503. this._vrDisplay = undefined;
  10504. this._vrSupported = false;
  10505. this._vrExclusivePointerMode = false;
  10506. // Uniform buffers list
  10507. this.disableUniformBuffers = false;
  10508. this._uniformBuffers = new Array();
  10509. // Observables
  10510. /**
  10511. * Observable raised when the engine begins a new frame
  10512. */
  10513. this.onBeginFrameObservable = new BABYLON.Observable();
  10514. /**
  10515. * Observable raised when the engine ends the current frame
  10516. */
  10517. this.onEndFrameObservable = new BABYLON.Observable();
  10518. /**
  10519. * Observable raised when the engine is about to compile a shader
  10520. */
  10521. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10522. /**
  10523. * Observable raised when the engine has jsut compiled a shader
  10524. */
  10525. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10526. this._windowIsBackground = false;
  10527. this._webGLVersion = 1.0;
  10528. this._badOS = false;
  10529. this._badDesktopOS = false;
  10530. /**
  10531. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10532. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10533. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10534. */
  10535. this.disableTextureBindingOptimization = false;
  10536. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10537. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10538. this.onVRRequestPresentStart = new BABYLON.Observable();
  10539. this._colorWrite = true;
  10540. this._drawCalls = new BABYLON.PerfCounter();
  10541. this._textureCollisions = new BABYLON.PerfCounter();
  10542. this._renderingQueueLaunched = false;
  10543. this._activeRenderLoops = new Array();
  10544. // Deterministic lockstepMaxSteps
  10545. this._deterministicLockstep = false;
  10546. this._lockstepMaxSteps = 4;
  10547. // Lost context
  10548. this.onContextLostObservable = new BABYLON.Observable();
  10549. this.onContextRestoredObservable = new BABYLON.Observable();
  10550. this._contextWasLost = false;
  10551. this._doNotHandleContextLost = false;
  10552. // FPS
  10553. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10554. this._fps = 60;
  10555. this._deltaTime = 0;
  10556. /**
  10557. * Turn this value on if you want to pause FPS computation when in background
  10558. */
  10559. this.disablePerformanceMonitorInBackground = false;
  10560. // States
  10561. this._depthCullingState = new BABYLON._DepthCullingState();
  10562. this._stencilState = new BABYLON._StencilState();
  10563. this._alphaState = new BABYLON._AlphaState();
  10564. this._alphaMode = Engine.ALPHA_DISABLE;
  10565. // Cache
  10566. this._internalTexturesCache = new Array();
  10567. this._activeChannel = 0;
  10568. this._currentTextureChannel = -1;
  10569. this._boundTexturesCache = {};
  10570. this._compiledEffects = {};
  10571. this._vertexAttribArraysEnabled = [];
  10572. this._uintIndicesCurrentlySet = false;
  10573. this._currentBoundBuffer = new Array();
  10574. this._currentBufferPointers = new Array();
  10575. this._currentInstanceLocations = new Array();
  10576. this._currentInstanceBuffers = new Array();
  10577. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10578. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10579. this._vaoRecordInProgress = false;
  10580. this._mustWipeVertexAttributes = false;
  10581. this._nextFreeTextureSlots = new Array();
  10582. this._maxSimultaneousTextures = 0;
  10583. this._activeRequests = new Array();
  10584. // Hardware supported Compressed Textures
  10585. this._texturesSupported = new Array();
  10586. this._onVRFullScreenTriggered = function () {
  10587. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10588. //get the old size before we change
  10589. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10590. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10591. //get the width and height, change the render size
  10592. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10593. _this.setHardwareScalingLevel(1);
  10594. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10595. }
  10596. else {
  10597. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10598. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10599. }
  10600. };
  10601. this._boundUniforms = {};
  10602. // Register promises
  10603. BABYLON.PromisePolyfill.Apply();
  10604. var canvas = null;
  10605. Engine.Instances.push(this);
  10606. if (!canvasOrContext) {
  10607. return;
  10608. }
  10609. options = options || {};
  10610. if (canvasOrContext.getContext) {
  10611. canvas = canvasOrContext;
  10612. this._renderingCanvas = canvas;
  10613. if (antialias != null) {
  10614. options.antialias = antialias;
  10615. }
  10616. if (options.deterministicLockstep === undefined) {
  10617. options.deterministicLockstep = false;
  10618. }
  10619. if (options.lockstepMaxSteps === undefined) {
  10620. options.lockstepMaxSteps = 4;
  10621. }
  10622. if (options.preserveDrawingBuffer === undefined) {
  10623. options.preserveDrawingBuffer = false;
  10624. }
  10625. if (options.audioEngine === undefined) {
  10626. options.audioEngine = true;
  10627. }
  10628. if (options.stencil === undefined) {
  10629. options.stencil = true;
  10630. }
  10631. this._deterministicLockstep = options.deterministicLockstep;
  10632. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10633. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10634. // Exceptions
  10635. if (navigator && navigator.userAgent) {
  10636. var ua = navigator.userAgent;
  10637. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10638. var exception = _a[_i];
  10639. var key = exception.key;
  10640. var targets = exception.targets;
  10641. if (ua.indexOf(key) > -1) {
  10642. if (exception.capture && exception.captureConstraint) {
  10643. var capture = exception.capture;
  10644. var constraint = exception.captureConstraint;
  10645. var regex = new RegExp(capture);
  10646. var matches = regex.exec(ua);
  10647. if (matches && matches.length > 0) {
  10648. var capturedValue = parseInt(matches[matches.length - 1]);
  10649. if (capturedValue >= constraint) {
  10650. continue;
  10651. }
  10652. }
  10653. }
  10654. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10655. var target = targets_1[_b];
  10656. switch (target) {
  10657. case "uniformBuffer":
  10658. this.disableUniformBuffers = true;
  10659. break;
  10660. case "textureBindingOptimization":
  10661. this.disableTextureBindingOptimization = true;
  10662. break;
  10663. }
  10664. }
  10665. }
  10666. }
  10667. }
  10668. // GL
  10669. if (!options.disableWebGL2Support) {
  10670. try {
  10671. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10672. if (this._gl) {
  10673. this._webGLVersion = 2.0;
  10674. }
  10675. }
  10676. catch (e) {
  10677. // Do nothing
  10678. }
  10679. }
  10680. if (!this._gl) {
  10681. if (!canvas) {
  10682. throw new Error("The provided canvas is null or undefined.");
  10683. }
  10684. try {
  10685. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10686. }
  10687. catch (e) {
  10688. throw new Error("WebGL not supported");
  10689. }
  10690. }
  10691. if (!this._gl) {
  10692. throw new Error("WebGL not supported");
  10693. }
  10694. this._onCanvasFocus = function () {
  10695. _this.onCanvasFocusObservable.notifyObservers(_this);
  10696. };
  10697. this._onCanvasBlur = function () {
  10698. _this.onCanvasBlurObservable.notifyObservers(_this);
  10699. };
  10700. canvas.addEventListener("focus", this._onCanvasFocus);
  10701. canvas.addEventListener("blur", this._onCanvasBlur);
  10702. this._onBlur = function () {
  10703. if (_this.disablePerformanceMonitorInBackground) {
  10704. _this._performanceMonitor.disable();
  10705. }
  10706. _this._windowIsBackground = true;
  10707. };
  10708. this._onFocus = function () {
  10709. if (_this.disablePerformanceMonitorInBackground) {
  10710. _this._performanceMonitor.enable();
  10711. }
  10712. _this._windowIsBackground = false;
  10713. };
  10714. this._onCanvasPointerOut = function (ev) {
  10715. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10716. };
  10717. window.addEventListener("blur", this._onBlur);
  10718. window.addEventListener("focus", this._onFocus);
  10719. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10720. // Context lost
  10721. if (!this._doNotHandleContextLost) {
  10722. this._onContextLost = function (evt) {
  10723. evt.preventDefault();
  10724. _this._contextWasLost = true;
  10725. BABYLON.Tools.Warn("WebGL context lost.");
  10726. _this.onContextLostObservable.notifyObservers(_this);
  10727. };
  10728. this._onContextRestored = function (evt) {
  10729. // Adding a timeout to avoid race condition at browser level
  10730. setTimeout(function () {
  10731. // Rebuild gl context
  10732. _this._initGLContext();
  10733. // Rebuild effects
  10734. _this._rebuildEffects();
  10735. // Rebuild textures
  10736. _this._rebuildInternalTextures();
  10737. // Rebuild buffers
  10738. _this._rebuildBuffers();
  10739. // Cache
  10740. _this.wipeCaches(true);
  10741. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10742. _this.onContextRestoredObservable.notifyObservers(_this);
  10743. _this._contextWasLost = false;
  10744. }, 0);
  10745. };
  10746. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10747. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10748. }
  10749. }
  10750. else {
  10751. this._gl = canvasOrContext;
  10752. this._renderingCanvas = this._gl.canvas;
  10753. if (this._gl.renderbufferStorageMultisample) {
  10754. this._webGLVersion = 2.0;
  10755. }
  10756. options.stencil = this._gl.getContextAttributes().stencil;
  10757. }
  10758. // Viewport
  10759. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10760. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10761. this.resize();
  10762. this._isStencilEnable = options.stencil ? true : false;
  10763. this._initGLContext();
  10764. if (canvas) {
  10765. // Fullscreen
  10766. this._onFullscreenChange = function () {
  10767. if (document.fullscreen !== undefined) {
  10768. _this.isFullscreen = document.fullscreen;
  10769. }
  10770. else if (document.mozFullScreen !== undefined) {
  10771. _this.isFullscreen = document.mozFullScreen;
  10772. }
  10773. else if (document.webkitIsFullScreen !== undefined) {
  10774. _this.isFullscreen = document.webkitIsFullScreen;
  10775. }
  10776. else if (document.msIsFullScreen !== undefined) {
  10777. _this.isFullscreen = document.msIsFullScreen;
  10778. }
  10779. // Pointer lock
  10780. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10781. canvas.requestPointerLock = canvas.requestPointerLock ||
  10782. canvas.msRequestPointerLock ||
  10783. canvas.mozRequestPointerLock ||
  10784. canvas.webkitRequestPointerLock;
  10785. if (canvas.requestPointerLock) {
  10786. canvas.requestPointerLock();
  10787. }
  10788. }
  10789. };
  10790. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10791. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10792. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10793. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10794. // Pointer lock
  10795. this._onPointerLockChange = function () {
  10796. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10797. document.webkitPointerLockElement === canvas ||
  10798. document.msPointerLockElement === canvas ||
  10799. document.pointerLockElement === canvas);
  10800. };
  10801. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10802. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10803. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10804. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10805. this._onVRDisplayPointerRestricted = function () {
  10806. if (canvas) {
  10807. canvas.requestPointerLock();
  10808. }
  10809. };
  10810. this._onVRDisplayPointerUnrestricted = function () {
  10811. document.exitPointerLock();
  10812. };
  10813. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10814. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10815. }
  10816. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10817. Engine.audioEngine = new BABYLON.AudioEngine();
  10818. }
  10819. // Prepare buffer pointers
  10820. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10821. this._currentBufferPointers[i] = new BufferPointer();
  10822. }
  10823. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10824. // Load WebVR Devices
  10825. if (options.autoEnableWebVR) {
  10826. this.initWebVR();
  10827. }
  10828. // Detect if we are running on a faulty buggy OS.
  10829. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10830. // Detect if we are running on a faulty buggy desktop OS.
  10831. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10832. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10833. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10834. }
  10835. Object.defineProperty(Engine, "LastCreatedEngine", {
  10836. get: function () {
  10837. if (Engine.Instances.length === 0) {
  10838. return null;
  10839. }
  10840. return Engine.Instances[Engine.Instances.length - 1];
  10841. },
  10842. enumerable: true,
  10843. configurable: true
  10844. });
  10845. Object.defineProperty(Engine, "LastCreatedScene", {
  10846. get: function () {
  10847. var lastCreatedEngine = Engine.LastCreatedEngine;
  10848. if (!lastCreatedEngine) {
  10849. return null;
  10850. }
  10851. if (lastCreatedEngine.scenes.length === 0) {
  10852. return null;
  10853. }
  10854. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10855. },
  10856. enumerable: true,
  10857. configurable: true
  10858. });
  10859. /**
  10860. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10861. */
  10862. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10863. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10864. var engine = Engine.Instances[engineIndex];
  10865. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10866. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10867. }
  10868. }
  10869. };
  10870. Object.defineProperty(Engine, "NEVER", {
  10871. get: function () {
  10872. return Engine._NEVER;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(Engine, "ALWAYS", {
  10878. get: function () {
  10879. return Engine._ALWAYS;
  10880. },
  10881. enumerable: true,
  10882. configurable: true
  10883. });
  10884. Object.defineProperty(Engine, "LESS", {
  10885. get: function () {
  10886. return Engine._LESS;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(Engine, "EQUAL", {
  10892. get: function () {
  10893. return Engine._EQUAL;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. Object.defineProperty(Engine, "LEQUAL", {
  10899. get: function () {
  10900. return Engine._LEQUAL;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(Engine, "GREATER", {
  10906. get: function () {
  10907. return Engine._GREATER;
  10908. },
  10909. enumerable: true,
  10910. configurable: true
  10911. });
  10912. Object.defineProperty(Engine, "GEQUAL", {
  10913. get: function () {
  10914. return Engine._GEQUAL;
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. Object.defineProperty(Engine, "NOTEQUAL", {
  10920. get: function () {
  10921. return Engine._NOTEQUAL;
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. Object.defineProperty(Engine, "KEEP", {
  10927. get: function () {
  10928. return Engine._KEEP;
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. Object.defineProperty(Engine, "REPLACE", {
  10934. get: function () {
  10935. return Engine._REPLACE;
  10936. },
  10937. enumerable: true,
  10938. configurable: true
  10939. });
  10940. Object.defineProperty(Engine, "INCR", {
  10941. get: function () {
  10942. return Engine._INCR;
  10943. },
  10944. enumerable: true,
  10945. configurable: true
  10946. });
  10947. Object.defineProperty(Engine, "DECR", {
  10948. get: function () {
  10949. return Engine._DECR;
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(Engine, "INVERT", {
  10955. get: function () {
  10956. return Engine._INVERT;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. Object.defineProperty(Engine, "INCR_WRAP", {
  10962. get: function () {
  10963. return Engine._INCR_WRAP;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(Engine, "DECR_WRAP", {
  10969. get: function () {
  10970. return Engine._DECR_WRAP;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10976. get: function () {
  10977. return Engine._ALPHA_DISABLE;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10983. get: function () {
  10984. return Engine._ALPHA_ONEONE;
  10985. },
  10986. enumerable: true,
  10987. configurable: true
  10988. });
  10989. Object.defineProperty(Engine, "ALPHA_ADD", {
  10990. get: function () {
  10991. return Engine._ALPHA_ADD;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10997. get: function () {
  10998. return Engine._ALPHA_COMBINE;
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11004. get: function () {
  11005. return Engine._ALPHA_SUBTRACT;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11011. get: function () {
  11012. return Engine._ALPHA_MULTIPLY;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11018. get: function () {
  11019. return Engine._ALPHA_MAXIMIZED;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11025. get: function () {
  11026. return Engine._ALPHA_PREMULTIPLIED;
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11032. get: function () {
  11033. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11039. get: function () {
  11040. return Engine._ALPHA_INTERPOLATE;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11046. get: function () {
  11047. return Engine._ALPHA_SCREENMODE;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11053. get: function () {
  11054. return Engine._DELAYLOADSTATE_NONE;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11060. get: function () {
  11061. return Engine._DELAYLOADSTATE_LOADED;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11067. get: function () {
  11068. return Engine._DELAYLOADSTATE_LOADING;
  11069. },
  11070. enumerable: true,
  11071. configurable: true
  11072. });
  11073. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11074. get: function () {
  11075. return Engine._DELAYLOADSTATE_NOTLOADED;
  11076. },
  11077. enumerable: true,
  11078. configurable: true
  11079. });
  11080. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11081. get: function () {
  11082. return Engine._TEXTUREFORMAT_ALPHA;
  11083. },
  11084. enumerable: true,
  11085. configurable: true
  11086. });
  11087. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11088. get: function () {
  11089. return Engine._TEXTUREFORMAT_LUMINANCE;
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11095. /**
  11096. * R32F
  11097. */
  11098. get: function () {
  11099. return Engine._TEXTUREFORMAT_R32F;
  11100. },
  11101. enumerable: true,
  11102. configurable: true
  11103. });
  11104. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11105. /**
  11106. * RG32F
  11107. */
  11108. get: function () {
  11109. return Engine._TEXTUREFORMAT_RG32F;
  11110. },
  11111. enumerable: true,
  11112. configurable: true
  11113. });
  11114. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11115. /**
  11116. * RGB32F
  11117. */
  11118. get: function () {
  11119. return Engine._TEXTUREFORMAT_RGB32F;
  11120. },
  11121. enumerable: true,
  11122. configurable: true
  11123. });
  11124. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11125. /**
  11126. * RGBA32F
  11127. */
  11128. get: function () {
  11129. return Engine._TEXTUREFORMAT_RGBA32F;
  11130. },
  11131. enumerable: true,
  11132. configurable: true
  11133. });
  11134. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11135. get: function () {
  11136. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11137. },
  11138. enumerable: true,
  11139. configurable: true
  11140. });
  11141. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11142. get: function () {
  11143. return Engine._TEXTUREFORMAT_RGB;
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11149. get: function () {
  11150. return Engine._TEXTUREFORMAT_RGBA;
  11151. },
  11152. enumerable: true,
  11153. configurable: true
  11154. });
  11155. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11156. get: function () {
  11157. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11158. },
  11159. enumerable: true,
  11160. configurable: true
  11161. });
  11162. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11163. get: function () {
  11164. return Engine._TEXTURETYPE_FLOAT;
  11165. },
  11166. enumerable: true,
  11167. configurable: true
  11168. });
  11169. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11170. get: function () {
  11171. return Engine._TEXTURETYPE_HALF_FLOAT;
  11172. },
  11173. enumerable: true,
  11174. configurable: true
  11175. });
  11176. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11177. get: function () {
  11178. return Engine._SCALEMODE_FLOOR;
  11179. },
  11180. enumerable: true,
  11181. configurable: true
  11182. });
  11183. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11184. get: function () {
  11185. return Engine._SCALEMODE_NEAREST;
  11186. },
  11187. enumerable: true,
  11188. configurable: true
  11189. });
  11190. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11191. get: function () {
  11192. return Engine._SCALEMODE_CEILING;
  11193. },
  11194. enumerable: true,
  11195. configurable: true
  11196. });
  11197. Object.defineProperty(Engine, "Version", {
  11198. get: function () {
  11199. return "3.2.0-beta.2";
  11200. },
  11201. enumerable: true,
  11202. configurable: true
  11203. });
  11204. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11205. get: function () {
  11206. return this._vrExclusivePointerMode;
  11207. },
  11208. enumerable: true,
  11209. configurable: true
  11210. });
  11211. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11212. get: function () {
  11213. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11214. },
  11215. enumerable: true,
  11216. configurable: true
  11217. });
  11218. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11219. get: function () {
  11220. return this._webGLVersion < 2 || this.forcePOTTextures;
  11221. },
  11222. enumerable: true,
  11223. configurable: true
  11224. });
  11225. Object.defineProperty(Engine.prototype, "badOS", {
  11226. get: function () {
  11227. return this._badOS;
  11228. },
  11229. enumerable: true,
  11230. configurable: true
  11231. });
  11232. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11233. get: function () {
  11234. return this._badDesktopOS;
  11235. },
  11236. enumerable: true,
  11237. configurable: true
  11238. });
  11239. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11240. get: function () {
  11241. return this._performanceMonitor;
  11242. },
  11243. enumerable: true,
  11244. configurable: true
  11245. });
  11246. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11247. get: function () {
  11248. return this._texturesSupported;
  11249. },
  11250. enumerable: true,
  11251. configurable: true
  11252. });
  11253. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11254. get: function () {
  11255. return this._textureFormatInUse;
  11256. },
  11257. enumerable: true,
  11258. configurable: true
  11259. });
  11260. Object.defineProperty(Engine.prototype, "currentViewport", {
  11261. get: function () {
  11262. return this._cachedViewport;
  11263. },
  11264. enumerable: true,
  11265. configurable: true
  11266. });
  11267. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11268. // Empty texture
  11269. get: function () {
  11270. if (!this._emptyTexture) {
  11271. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11272. }
  11273. return this._emptyTexture;
  11274. },
  11275. enumerable: true,
  11276. configurable: true
  11277. });
  11278. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11279. get: function () {
  11280. if (!this._emptyTexture3D) {
  11281. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11282. }
  11283. return this._emptyTexture3D;
  11284. },
  11285. enumerable: true,
  11286. configurable: true
  11287. });
  11288. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11289. get: function () {
  11290. if (!this._emptyCubeTexture) {
  11291. var faceData = new Uint8Array(4);
  11292. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11293. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11294. }
  11295. return this._emptyCubeTexture;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Engine.prototype._rebuildInternalTextures = function () {
  11301. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11302. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11303. var internalTexture = currentState_1[_i];
  11304. internalTexture._rebuild();
  11305. }
  11306. };
  11307. Engine.prototype._rebuildEffects = function () {
  11308. for (var key in this._compiledEffects) {
  11309. var effect = this._compiledEffects[key];
  11310. effect._prepareEffect();
  11311. }
  11312. BABYLON.Effect.ResetCache();
  11313. };
  11314. Engine.prototype._rebuildBuffers = function () {
  11315. // Index / Vertex
  11316. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11317. var scene = _a[_i];
  11318. scene.resetCachedMaterial();
  11319. scene._rebuildGeometries();
  11320. scene._rebuildTextures();
  11321. }
  11322. // Uniforms
  11323. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11324. var uniformBuffer = _c[_b];
  11325. uniformBuffer._rebuild();
  11326. }
  11327. };
  11328. Engine.prototype._initGLContext = function () {
  11329. // Caps
  11330. this._caps = new EngineCapabilities();
  11331. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11332. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11333. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11334. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11335. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11336. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11337. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11338. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11339. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11340. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11341. // Infos
  11342. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11343. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11344. if (rendererInfo != null) {
  11345. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11346. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11347. }
  11348. if (!this._glVendor) {
  11349. this._glVendor = "Unknown vendor";
  11350. }
  11351. if (!this._glRenderer) {
  11352. this._glRenderer = "Unknown renderer";
  11353. }
  11354. // Constants
  11355. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11356. if (this._gl.RGBA16F !== 0x881A) {
  11357. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11358. }
  11359. if (this._gl.RGBA32F !== 0x8814) {
  11360. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11361. }
  11362. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11363. this._gl.DEPTH24_STENCIL8 = 35056;
  11364. }
  11365. // Extensions
  11366. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11367. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11368. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11369. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11370. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11371. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11372. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11373. 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');
  11374. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11375. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11376. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11377. this._caps.highPrecisionShaderSupported = true;
  11378. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11379. if (this._caps.timerQuery) {
  11380. if (this._webGLVersion === 1) {
  11381. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11382. }
  11383. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11384. }
  11385. // Checks if some of the format renders first to allow the use of webgl inspector.
  11386. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11387. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11388. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11389. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11390. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11391. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11392. if (this._webGLVersion > 1) {
  11393. this._gl.HALF_FLOAT_OES = 0x140B;
  11394. }
  11395. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11396. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11397. // Draw buffers
  11398. if (this._webGLVersion > 1) {
  11399. this._caps.drawBuffersExtension = true;
  11400. }
  11401. else {
  11402. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11403. if (drawBuffersExtension !== null) {
  11404. this._caps.drawBuffersExtension = true;
  11405. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11406. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11407. for (var i = 0; i < 16; i++) {
  11408. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11409. }
  11410. }
  11411. else {
  11412. this._caps.drawBuffersExtension = false;
  11413. }
  11414. }
  11415. // Depth Texture
  11416. if (this._webGLVersion > 1) {
  11417. this._caps.depthTextureExtension = true;
  11418. }
  11419. else {
  11420. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11421. if (depthTextureExtension != null) {
  11422. this._caps.depthTextureExtension = true;
  11423. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11424. }
  11425. }
  11426. // Vertex array object
  11427. if (this._webGLVersion > 1) {
  11428. this._caps.vertexArrayObject = true;
  11429. }
  11430. else {
  11431. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11432. if (vertexArrayObjectExtension != null) {
  11433. this._caps.vertexArrayObject = true;
  11434. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11435. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11436. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11437. }
  11438. else {
  11439. this._caps.vertexArrayObject = false;
  11440. }
  11441. }
  11442. // Instances count
  11443. if (this._webGLVersion > 1) {
  11444. this._caps.instancedArrays = true;
  11445. }
  11446. else {
  11447. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11448. if (instanceExtension != null) {
  11449. this._caps.instancedArrays = true;
  11450. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11451. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11452. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11453. }
  11454. else {
  11455. this._caps.instancedArrays = false;
  11456. }
  11457. }
  11458. // Intelligently add supported compressed formats in order to check for.
  11459. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11460. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11461. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11462. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11463. if (this._caps.astc)
  11464. this.texturesSupported.push('-astc.ktx');
  11465. if (this._caps.s3tc)
  11466. this.texturesSupported.push('-dxt.ktx');
  11467. if (this._caps.pvrtc)
  11468. this.texturesSupported.push('-pvrtc.ktx');
  11469. if (this._caps.etc2)
  11470. this.texturesSupported.push('-etc2.ktx');
  11471. if (this._caps.etc1)
  11472. this.texturesSupported.push('-etc1.ktx');
  11473. if (this._gl.getShaderPrecisionFormat) {
  11474. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11475. if (highp) {
  11476. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11477. }
  11478. }
  11479. // Depth buffer
  11480. this.setDepthBuffer(true);
  11481. this.setDepthFunctionToLessOrEqual();
  11482. this.setDepthWrite(true);
  11483. // Texture maps
  11484. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11485. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11486. this._nextFreeTextureSlots.push(slot);
  11487. }
  11488. };
  11489. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11490. get: function () {
  11491. return this._webGLVersion;
  11492. },
  11493. enumerable: true,
  11494. configurable: true
  11495. });
  11496. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11497. /**
  11498. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11499. */
  11500. get: function () {
  11501. return this._isStencilEnable;
  11502. },
  11503. enumerable: true,
  11504. configurable: true
  11505. });
  11506. Engine.prototype._prepareWorkingCanvas = function () {
  11507. if (this._workingCanvas) {
  11508. return;
  11509. }
  11510. this._workingCanvas = document.createElement("canvas");
  11511. var context = this._workingCanvas.getContext("2d");
  11512. if (context) {
  11513. this._workingContext = context;
  11514. }
  11515. };
  11516. Engine.prototype.resetTextureCache = function () {
  11517. for (var key in this._boundTexturesCache) {
  11518. var boundTexture = this._boundTexturesCache[key];
  11519. if (boundTexture) {
  11520. this._removeDesignatedSlot(boundTexture);
  11521. }
  11522. this._boundTexturesCache[key] = null;
  11523. }
  11524. if (!this.disableTextureBindingOptimization) {
  11525. this._nextFreeTextureSlots = [];
  11526. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11527. this._nextFreeTextureSlots.push(slot);
  11528. }
  11529. }
  11530. this._currentTextureChannel = -1;
  11531. };
  11532. Engine.prototype.isDeterministicLockStep = function () {
  11533. return this._deterministicLockstep;
  11534. };
  11535. Engine.prototype.getLockstepMaxSteps = function () {
  11536. return this._lockstepMaxSteps;
  11537. };
  11538. Engine.prototype.getGlInfo = function () {
  11539. return {
  11540. vendor: this._glVendor,
  11541. renderer: this._glRenderer,
  11542. version: this._glVersion
  11543. };
  11544. };
  11545. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11546. if (useScreen === void 0) { useScreen = false; }
  11547. var viewport = camera.viewport;
  11548. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11549. };
  11550. Engine.prototype.getRenderWidth = function (useScreen) {
  11551. if (useScreen === void 0) { useScreen = false; }
  11552. if (!useScreen && this._currentRenderTarget) {
  11553. return this._currentRenderTarget.width;
  11554. }
  11555. return this._gl.drawingBufferWidth;
  11556. };
  11557. Engine.prototype.getRenderHeight = function (useScreen) {
  11558. if (useScreen === void 0) { useScreen = false; }
  11559. if (!useScreen && this._currentRenderTarget) {
  11560. return this._currentRenderTarget.height;
  11561. }
  11562. return this._gl.drawingBufferHeight;
  11563. };
  11564. Engine.prototype.getRenderingCanvas = function () {
  11565. return this._renderingCanvas;
  11566. };
  11567. Engine.prototype.getRenderingCanvasClientRect = function () {
  11568. if (!this._renderingCanvas) {
  11569. return null;
  11570. }
  11571. return this._renderingCanvas.getBoundingClientRect();
  11572. };
  11573. Engine.prototype.setHardwareScalingLevel = function (level) {
  11574. this._hardwareScalingLevel = level;
  11575. this.resize();
  11576. };
  11577. Engine.prototype.getHardwareScalingLevel = function () {
  11578. return this._hardwareScalingLevel;
  11579. };
  11580. Engine.prototype.getLoadedTexturesCache = function () {
  11581. return this._internalTexturesCache;
  11582. };
  11583. Engine.prototype.getCaps = function () {
  11584. return this._caps;
  11585. };
  11586. Object.defineProperty(Engine.prototype, "drawCalls", {
  11587. /** The number of draw calls submitted last frame */
  11588. get: function () {
  11589. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11590. return 0;
  11591. },
  11592. enumerable: true,
  11593. configurable: true
  11594. });
  11595. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11596. get: function () {
  11597. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11598. return null;
  11599. },
  11600. enumerable: true,
  11601. configurable: true
  11602. });
  11603. Engine.prototype.getDepthFunction = function () {
  11604. return this._depthCullingState.depthFunc;
  11605. };
  11606. Engine.prototype.setDepthFunction = function (depthFunc) {
  11607. this._depthCullingState.depthFunc = depthFunc;
  11608. };
  11609. Engine.prototype.setDepthFunctionToGreater = function () {
  11610. this._depthCullingState.depthFunc = this._gl.GREATER;
  11611. };
  11612. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11613. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11614. };
  11615. Engine.prototype.setDepthFunctionToLess = function () {
  11616. this._depthCullingState.depthFunc = this._gl.LESS;
  11617. };
  11618. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11619. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11620. };
  11621. Engine.prototype.getStencilBuffer = function () {
  11622. return this._stencilState.stencilTest;
  11623. };
  11624. Engine.prototype.setStencilBuffer = function (enable) {
  11625. this._stencilState.stencilTest = enable;
  11626. };
  11627. Engine.prototype.getStencilMask = function () {
  11628. return this._stencilState.stencilMask;
  11629. };
  11630. Engine.prototype.setStencilMask = function (mask) {
  11631. this._stencilState.stencilMask = mask;
  11632. };
  11633. Engine.prototype.getStencilFunction = function () {
  11634. return this._stencilState.stencilFunc;
  11635. };
  11636. Engine.prototype.getStencilFunctionReference = function () {
  11637. return this._stencilState.stencilFuncRef;
  11638. };
  11639. Engine.prototype.getStencilFunctionMask = function () {
  11640. return this._stencilState.stencilFuncMask;
  11641. };
  11642. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11643. this._stencilState.stencilFunc = stencilFunc;
  11644. };
  11645. Engine.prototype.setStencilFunctionReference = function (reference) {
  11646. this._stencilState.stencilFuncRef = reference;
  11647. };
  11648. Engine.prototype.setStencilFunctionMask = function (mask) {
  11649. this._stencilState.stencilFuncMask = mask;
  11650. };
  11651. Engine.prototype.getStencilOperationFail = function () {
  11652. return this._stencilState.stencilOpStencilFail;
  11653. };
  11654. Engine.prototype.getStencilOperationDepthFail = function () {
  11655. return this._stencilState.stencilOpDepthFail;
  11656. };
  11657. Engine.prototype.getStencilOperationPass = function () {
  11658. return this._stencilState.stencilOpStencilDepthPass;
  11659. };
  11660. Engine.prototype.setStencilOperationFail = function (operation) {
  11661. this._stencilState.stencilOpStencilFail = operation;
  11662. };
  11663. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11664. this._stencilState.stencilOpDepthFail = operation;
  11665. };
  11666. Engine.prototype.setStencilOperationPass = function (operation) {
  11667. this._stencilState.stencilOpStencilDepthPass = operation;
  11668. };
  11669. Engine.prototype.setDitheringState = function (value) {
  11670. if (value) {
  11671. this._gl.enable(this._gl.DITHER);
  11672. }
  11673. else {
  11674. this._gl.disable(this._gl.DITHER);
  11675. }
  11676. };
  11677. Engine.prototype.setRasterizerState = function (value) {
  11678. if (value) {
  11679. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11680. }
  11681. else {
  11682. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11683. }
  11684. };
  11685. /**
  11686. * stop executing a render loop function and remove it from the execution array
  11687. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11688. */
  11689. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11690. if (!renderFunction) {
  11691. this._activeRenderLoops = [];
  11692. return;
  11693. }
  11694. var index = this._activeRenderLoops.indexOf(renderFunction);
  11695. if (index >= 0) {
  11696. this._activeRenderLoops.splice(index, 1);
  11697. }
  11698. };
  11699. Engine.prototype._renderLoop = function () {
  11700. if (!this._contextWasLost) {
  11701. var shouldRender = true;
  11702. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11703. shouldRender = false;
  11704. }
  11705. if (shouldRender) {
  11706. // Start new frame
  11707. this.beginFrame();
  11708. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11709. var renderFunction = this._activeRenderLoops[index];
  11710. renderFunction();
  11711. }
  11712. // Present
  11713. this.endFrame();
  11714. }
  11715. }
  11716. if (this._activeRenderLoops.length > 0) {
  11717. // Register new frame
  11718. var requester = null;
  11719. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11720. requester = this._vrDisplay;
  11721. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11722. }
  11723. else {
  11724. this._renderingQueueLaunched = false;
  11725. }
  11726. };
  11727. /**
  11728. * Register and execute a render loop. The engine can have more than one render function.
  11729. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11730. * @example
  11731. * engine.runRenderLoop(function () {
  11732. * scene.render()
  11733. * })
  11734. */
  11735. Engine.prototype.runRenderLoop = function (renderFunction) {
  11736. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11737. return;
  11738. }
  11739. this._activeRenderLoops.push(renderFunction);
  11740. if (!this._renderingQueueLaunched) {
  11741. this._renderingQueueLaunched = true;
  11742. this._bindedRenderFunction = this._renderLoop.bind(this);
  11743. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11744. }
  11745. };
  11746. /**
  11747. * Toggle full screen mode.
  11748. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11749. * @param {any} options - an options object to be sent to the requestFullscreen function
  11750. */
  11751. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11752. if (this.isFullscreen) {
  11753. BABYLON.Tools.ExitFullscreen();
  11754. }
  11755. else {
  11756. this._pointerLockRequested = requestPointerLock;
  11757. if (this._renderingCanvas) {
  11758. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11759. }
  11760. }
  11761. };
  11762. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11763. if (stencil === void 0) { stencil = false; }
  11764. this.applyStates();
  11765. var mode = 0;
  11766. if (backBuffer && color) {
  11767. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11768. mode |= this._gl.COLOR_BUFFER_BIT;
  11769. }
  11770. if (depth) {
  11771. this._gl.clearDepth(1.0);
  11772. mode |= this._gl.DEPTH_BUFFER_BIT;
  11773. }
  11774. if (stencil) {
  11775. this._gl.clearStencil(0);
  11776. mode |= this._gl.STENCIL_BUFFER_BIT;
  11777. }
  11778. this._gl.clear(mode);
  11779. };
  11780. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11781. var gl = this._gl;
  11782. // Save state
  11783. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11784. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11785. // Change state
  11786. gl.enable(gl.SCISSOR_TEST);
  11787. gl.scissor(x, y, width, height);
  11788. // Clear
  11789. this.clear(clearColor, true, true, true);
  11790. // Restore state
  11791. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11792. if (curScissor === true) {
  11793. gl.enable(gl.SCISSOR_TEST);
  11794. }
  11795. else {
  11796. gl.disable(gl.SCISSOR_TEST);
  11797. }
  11798. };
  11799. /**
  11800. * Set the WebGL's viewport
  11801. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11802. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11803. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11804. */
  11805. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11806. var width = requiredWidth || this.getRenderWidth();
  11807. var height = requiredHeight || this.getRenderHeight();
  11808. var x = viewport.x || 0;
  11809. var y = viewport.y || 0;
  11810. this._cachedViewport = viewport;
  11811. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11812. };
  11813. /**
  11814. * Directly set the WebGL Viewport
  11815. * The x, y, width & height are directly passed to the WebGL call
  11816. * @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.
  11817. */
  11818. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11819. var currentViewport = this._cachedViewport;
  11820. this._cachedViewport = null;
  11821. this._gl.viewport(x, y, width, height);
  11822. return currentViewport;
  11823. };
  11824. Engine.prototype.beginFrame = function () {
  11825. this.onBeginFrameObservable.notifyObservers(this);
  11826. this._measureFps();
  11827. };
  11828. Engine.prototype.endFrame = function () {
  11829. //force a flush in case we are using a bad OS.
  11830. if (this._badOS) {
  11831. this.flushFramebuffer();
  11832. }
  11833. //submit frame to the vr device, if enabled
  11834. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11835. // TODO: We should only submit the frame if we read frameData successfully.
  11836. this._vrDisplay.submitFrame();
  11837. }
  11838. this.onEndFrameObservable.notifyObservers(this);
  11839. };
  11840. /**
  11841. * resize the view according to the canvas' size.
  11842. * @example
  11843. * window.addEventListener("resize", function () {
  11844. * engine.resize();
  11845. * });
  11846. */
  11847. Engine.prototype.resize = function () {
  11848. // We're not resizing the size of the canvas while in VR mode & presenting
  11849. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11850. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11851. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11852. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11853. }
  11854. };
  11855. /**
  11856. * force a specific size of the canvas
  11857. * @param {number} width - the new canvas' width
  11858. * @param {number} height - the new canvas' height
  11859. */
  11860. Engine.prototype.setSize = function (width, height) {
  11861. if (!this._renderingCanvas) {
  11862. return;
  11863. }
  11864. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11865. return;
  11866. }
  11867. this._renderingCanvas.width = width;
  11868. this._renderingCanvas.height = height;
  11869. for (var index = 0; index < this.scenes.length; index++) {
  11870. var scene = this.scenes[index];
  11871. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11872. var cam = scene.cameras[camIndex];
  11873. cam._currentRenderId = 0;
  11874. }
  11875. }
  11876. if (this.onResizeObservable.hasObservers) {
  11877. this.onResizeObservable.notifyObservers(this);
  11878. }
  11879. };
  11880. // WebVR functions
  11881. Engine.prototype.isVRDevicePresent = function () {
  11882. return !!this._vrDisplay;
  11883. };
  11884. Engine.prototype.getVRDevice = function () {
  11885. return this._vrDisplay;
  11886. };
  11887. /**
  11888. * Initializes a webVR display and starts listening to display change events.
  11889. * The onVRDisplayChangedObservable will be notified upon these changes.
  11890. * @returns The onVRDisplayChangedObservable.
  11891. */
  11892. Engine.prototype.initWebVR = function () {
  11893. this.initWebVRAsync();
  11894. return this.onVRDisplayChangedObservable;
  11895. };
  11896. /**
  11897. * Initializes a webVR display and starts listening to display change events.
  11898. * The onVRDisplayChangedObservable will be notified upon these changes.
  11899. * @returns A promise containing a VRDisplay and if vr is supported.
  11900. */
  11901. Engine.prototype.initWebVRAsync = function () {
  11902. var _this = this;
  11903. var notifyObservers = function () {
  11904. var eventArgs = {
  11905. vrDisplay: _this._vrDisplay,
  11906. vrSupported: _this._vrSupported
  11907. };
  11908. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11909. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11910. };
  11911. if (!this._onVrDisplayConnect) {
  11912. this._onVrDisplayConnect = function (event) {
  11913. _this._vrDisplay = event.display;
  11914. notifyObservers();
  11915. };
  11916. this._onVrDisplayDisconnect = function () {
  11917. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11918. _this._vrDisplay = undefined;
  11919. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11920. notifyObservers();
  11921. };
  11922. this._onVrDisplayPresentChange = function () {
  11923. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11924. };
  11925. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11926. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11927. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11928. }
  11929. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11930. this._webVRInitPromise.then(notifyObservers);
  11931. return this._webVRInitPromise;
  11932. };
  11933. Engine.prototype.enableVR = function () {
  11934. var _this = this;
  11935. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11936. var onResolved = function () {
  11937. _this.onVRRequestPresentComplete.notifyObservers(true);
  11938. _this._onVRFullScreenTriggered();
  11939. };
  11940. var onRejected = function () {
  11941. _this.onVRRequestPresentComplete.notifyObservers(false);
  11942. };
  11943. this.onVRRequestPresentStart.notifyObservers(this);
  11944. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11945. }
  11946. };
  11947. Engine.prototype.disableVR = function () {
  11948. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11949. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11950. }
  11951. };
  11952. Engine.prototype._getVRDisplaysAsync = function () {
  11953. var _this = this;
  11954. return new Promise(function (res, rej) {
  11955. if (navigator.getVRDisplays) {
  11956. navigator.getVRDisplays().then(function (devices) {
  11957. _this._vrSupported = true;
  11958. // note that devices may actually be an empty array. This is fine;
  11959. // we expect this._vrDisplay to be undefined in this case.
  11960. _this._vrDisplay = devices[0];
  11961. res({
  11962. vrDisplay: _this._vrDisplay,
  11963. vrSupported: _this._vrSupported
  11964. });
  11965. });
  11966. }
  11967. else {
  11968. _this._vrDisplay = undefined;
  11969. _this._vrSupported = false;
  11970. res({
  11971. vrDisplay: _this._vrDisplay,
  11972. vrSupported: _this._vrSupported
  11973. });
  11974. }
  11975. });
  11976. };
  11977. /**
  11978. * Binds the frame buffer to the specified texture.
  11979. * @param texture The texture to render to or null for the default canvas
  11980. * @param faceIndex The face of the texture to render to in case of cube texture
  11981. * @param requiredWidth The width of the target to render to
  11982. * @param requiredHeight The height of the target to render to
  11983. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11984. * @param depthStencilTexture The depth stencil texture to use to render
  11985. */
  11986. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11987. if (this._currentRenderTarget) {
  11988. this.unBindFramebuffer(this._currentRenderTarget);
  11989. }
  11990. this._currentRenderTarget = texture;
  11991. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11992. var gl = this._gl;
  11993. if (texture.isCube) {
  11994. if (faceIndex === undefined) {
  11995. faceIndex = 0;
  11996. }
  11997. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11998. if (depthStencilTexture) {
  11999. if (depthStencilTexture._generateStencilBuffer) {
  12000. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12001. }
  12002. else {
  12003. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12004. }
  12005. }
  12006. }
  12007. if (this._cachedViewport && !forceFullscreenViewport) {
  12008. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12009. }
  12010. else {
  12011. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12012. }
  12013. this.wipeCaches();
  12014. };
  12015. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12016. if (this._currentFramebuffer !== framebuffer) {
  12017. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12018. this._currentFramebuffer = framebuffer;
  12019. }
  12020. };
  12021. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12022. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12023. this._currentRenderTarget = null;
  12024. // If MSAA, we need to bitblt back to main texture
  12025. var gl = this._gl;
  12026. if (texture._MSAAFramebuffer) {
  12027. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12028. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12029. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12030. }
  12031. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12032. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12033. gl.generateMipmap(gl.TEXTURE_2D);
  12034. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12035. }
  12036. if (onBeforeUnbind) {
  12037. if (texture._MSAAFramebuffer) {
  12038. // Bind the correct framebuffer
  12039. this.bindUnboundFramebuffer(texture._framebuffer);
  12040. }
  12041. onBeforeUnbind();
  12042. }
  12043. this.bindUnboundFramebuffer(null);
  12044. };
  12045. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12046. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12047. this._currentRenderTarget = null;
  12048. // If MSAA, we need to bitblt back to main texture
  12049. var gl = this._gl;
  12050. if (textures[0]._MSAAFramebuffer) {
  12051. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12052. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12053. var attachments = textures[0]._attachments;
  12054. if (!attachments) {
  12055. attachments = new Array(textures.length);
  12056. textures[0]._attachments = attachments;
  12057. }
  12058. for (var i = 0; i < textures.length; i++) {
  12059. var texture = textures[i];
  12060. for (var j = 0; j < attachments.length; j++) {
  12061. attachments[j] = gl.NONE;
  12062. }
  12063. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12064. gl.readBuffer(attachments[i]);
  12065. gl.drawBuffers(attachments);
  12066. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12067. }
  12068. for (var i = 0; i < attachments.length; i++) {
  12069. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12070. }
  12071. gl.drawBuffers(attachments);
  12072. }
  12073. for (var i = 0; i < textures.length; i++) {
  12074. var texture = textures[i];
  12075. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12076. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12077. gl.generateMipmap(gl.TEXTURE_2D);
  12078. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12079. }
  12080. }
  12081. if (onBeforeUnbind) {
  12082. if (textures[0]._MSAAFramebuffer) {
  12083. // Bind the correct framebuffer
  12084. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12085. }
  12086. onBeforeUnbind();
  12087. }
  12088. this.bindUnboundFramebuffer(null);
  12089. };
  12090. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12091. if (texture.generateMipMaps) {
  12092. var gl = this._gl;
  12093. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12094. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12095. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12096. }
  12097. };
  12098. Engine.prototype.flushFramebuffer = function () {
  12099. this._gl.flush();
  12100. };
  12101. Engine.prototype.restoreDefaultFramebuffer = function () {
  12102. if (this._currentRenderTarget) {
  12103. this.unBindFramebuffer(this._currentRenderTarget);
  12104. }
  12105. else {
  12106. this.bindUnboundFramebuffer(null);
  12107. }
  12108. if (this._cachedViewport) {
  12109. this.setViewport(this._cachedViewport);
  12110. }
  12111. this.wipeCaches();
  12112. };
  12113. // UBOs
  12114. Engine.prototype.createUniformBuffer = function (elements) {
  12115. var ubo = this._gl.createBuffer();
  12116. if (!ubo) {
  12117. throw new Error("Unable to create uniform buffer");
  12118. }
  12119. this.bindUniformBuffer(ubo);
  12120. if (elements instanceof Float32Array) {
  12121. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12122. }
  12123. else {
  12124. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12125. }
  12126. this.bindUniformBuffer(null);
  12127. ubo.references = 1;
  12128. return ubo;
  12129. };
  12130. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12131. var ubo = this._gl.createBuffer();
  12132. if (!ubo) {
  12133. throw new Error("Unable to create dynamic uniform buffer");
  12134. }
  12135. this.bindUniformBuffer(ubo);
  12136. if (elements instanceof Float32Array) {
  12137. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12138. }
  12139. else {
  12140. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12141. }
  12142. this.bindUniformBuffer(null);
  12143. ubo.references = 1;
  12144. return ubo;
  12145. };
  12146. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12147. this.bindUniformBuffer(uniformBuffer);
  12148. if (offset === undefined) {
  12149. offset = 0;
  12150. }
  12151. if (count === undefined) {
  12152. if (elements instanceof Float32Array) {
  12153. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12154. }
  12155. else {
  12156. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12157. }
  12158. }
  12159. else {
  12160. if (elements instanceof Float32Array) {
  12161. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12162. }
  12163. else {
  12164. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12165. }
  12166. }
  12167. this.bindUniformBuffer(null);
  12168. };
  12169. // VBOs
  12170. Engine.prototype._resetVertexBufferBinding = function () {
  12171. this.bindArrayBuffer(null);
  12172. this._cachedVertexBuffers = null;
  12173. };
  12174. Engine.prototype.createVertexBuffer = function (vertices) {
  12175. var vbo = this._gl.createBuffer();
  12176. if (!vbo) {
  12177. throw new Error("Unable to create vertex buffer");
  12178. }
  12179. this.bindArrayBuffer(vbo);
  12180. if (vertices instanceof Float32Array) {
  12181. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12182. }
  12183. else {
  12184. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12185. }
  12186. this._resetVertexBufferBinding();
  12187. vbo.references = 1;
  12188. return vbo;
  12189. };
  12190. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12191. var vbo = this._gl.createBuffer();
  12192. if (!vbo) {
  12193. throw new Error("Unable to create dynamic vertex buffer");
  12194. }
  12195. this.bindArrayBuffer(vbo);
  12196. if (vertices instanceof Float32Array) {
  12197. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12198. }
  12199. else {
  12200. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12201. }
  12202. this._resetVertexBufferBinding();
  12203. vbo.references = 1;
  12204. return vbo;
  12205. };
  12206. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12207. if (offset === void 0) { offset = 0; }
  12208. // Force cache update
  12209. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12210. this.bindIndexBuffer(indexBuffer);
  12211. var arrayBuffer;
  12212. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12213. arrayBuffer = indices;
  12214. }
  12215. else {
  12216. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12217. }
  12218. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12219. this._resetIndexBufferBinding();
  12220. };
  12221. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12222. this.bindArrayBuffer(vertexBuffer);
  12223. if (offset === undefined) {
  12224. offset = 0;
  12225. }
  12226. if (count === undefined) {
  12227. if (vertices instanceof Float32Array) {
  12228. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12229. }
  12230. else {
  12231. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12232. }
  12233. }
  12234. else {
  12235. if (vertices instanceof Float32Array) {
  12236. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12237. }
  12238. else {
  12239. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12240. }
  12241. }
  12242. this._resetVertexBufferBinding();
  12243. };
  12244. Engine.prototype._resetIndexBufferBinding = function () {
  12245. this.bindIndexBuffer(null);
  12246. this._cachedIndexBuffer = null;
  12247. };
  12248. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12249. var vbo = this._gl.createBuffer();
  12250. if (!vbo) {
  12251. throw new Error("Unable to create index buffer");
  12252. }
  12253. this.bindIndexBuffer(vbo);
  12254. // Check for 32 bits indices
  12255. var arrayBuffer;
  12256. var need32Bits = false;
  12257. if (indices instanceof Uint16Array) {
  12258. arrayBuffer = indices;
  12259. }
  12260. else {
  12261. //check 32 bit support
  12262. if (this._caps.uintIndices) {
  12263. if (indices instanceof Uint32Array) {
  12264. arrayBuffer = indices;
  12265. need32Bits = true;
  12266. }
  12267. else {
  12268. //number[] or Int32Array, check if 32 bit is necessary
  12269. for (var index = 0; index < indices.length; index++) {
  12270. if (indices[index] > 65535) {
  12271. need32Bits = true;
  12272. break;
  12273. }
  12274. }
  12275. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12276. }
  12277. }
  12278. else {
  12279. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12280. arrayBuffer = new Uint16Array(indices);
  12281. }
  12282. }
  12283. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12284. this._resetIndexBufferBinding();
  12285. vbo.references = 1;
  12286. vbo.is32Bits = need32Bits;
  12287. return vbo;
  12288. };
  12289. Engine.prototype.bindArrayBuffer = function (buffer) {
  12290. if (!this._vaoRecordInProgress) {
  12291. this._unbindVertexArrayObject();
  12292. }
  12293. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12294. };
  12295. Engine.prototype.bindUniformBuffer = function (buffer) {
  12296. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12297. };
  12298. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12299. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12300. };
  12301. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12302. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12303. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12304. };
  12305. ;
  12306. Engine.prototype.bindIndexBuffer = function (buffer) {
  12307. if (!this._vaoRecordInProgress) {
  12308. this._unbindVertexArrayObject();
  12309. }
  12310. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12311. };
  12312. Engine.prototype.bindBuffer = function (buffer, target) {
  12313. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12314. this._gl.bindBuffer(target, buffer);
  12315. this._currentBoundBuffer[target] = buffer;
  12316. }
  12317. };
  12318. Engine.prototype.updateArrayBuffer = function (data) {
  12319. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12320. };
  12321. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12322. var pointer = this._currentBufferPointers[indx];
  12323. var changed = false;
  12324. if (!pointer.active) {
  12325. changed = true;
  12326. pointer.active = true;
  12327. pointer.index = indx;
  12328. pointer.size = size;
  12329. pointer.type = type;
  12330. pointer.normalized = normalized;
  12331. pointer.stride = stride;
  12332. pointer.offset = offset;
  12333. pointer.buffer = buffer;
  12334. }
  12335. else {
  12336. if (pointer.buffer !== buffer) {
  12337. pointer.buffer = buffer;
  12338. changed = true;
  12339. }
  12340. if (pointer.size !== size) {
  12341. pointer.size = size;
  12342. changed = true;
  12343. }
  12344. if (pointer.type !== type) {
  12345. pointer.type = type;
  12346. changed = true;
  12347. }
  12348. if (pointer.normalized !== normalized) {
  12349. pointer.normalized = normalized;
  12350. changed = true;
  12351. }
  12352. if (pointer.stride !== stride) {
  12353. pointer.stride = stride;
  12354. changed = true;
  12355. }
  12356. if (pointer.offset !== offset) {
  12357. pointer.offset = offset;
  12358. changed = true;
  12359. }
  12360. }
  12361. if (changed || this._vaoRecordInProgress) {
  12362. this.bindArrayBuffer(buffer);
  12363. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12364. }
  12365. };
  12366. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12367. if (indexBuffer == null) {
  12368. return;
  12369. }
  12370. if (this._cachedIndexBuffer !== indexBuffer) {
  12371. this._cachedIndexBuffer = indexBuffer;
  12372. this.bindIndexBuffer(indexBuffer);
  12373. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12374. }
  12375. };
  12376. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12377. var attributes = effect.getAttributesNames();
  12378. if (!this._vaoRecordInProgress) {
  12379. this._unbindVertexArrayObject();
  12380. }
  12381. this.unbindAllAttributes();
  12382. for (var index = 0; index < attributes.length; index++) {
  12383. var order = effect.getAttributeLocation(index);
  12384. if (order >= 0) {
  12385. var vertexBuffer = vertexBuffers[attributes[index]];
  12386. if (!vertexBuffer) {
  12387. continue;
  12388. }
  12389. this._gl.enableVertexAttribArray(order);
  12390. if (!this._vaoRecordInProgress) {
  12391. this._vertexAttribArraysEnabled[order] = true;
  12392. }
  12393. var buffer = vertexBuffer.getBuffer();
  12394. if (buffer) {
  12395. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12396. if (vertexBuffer.getIsInstanced()) {
  12397. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12398. if (!this._vaoRecordInProgress) {
  12399. this._currentInstanceLocations.push(order);
  12400. this._currentInstanceBuffers.push(buffer);
  12401. }
  12402. }
  12403. }
  12404. }
  12405. }
  12406. };
  12407. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12408. var vao = this._gl.createVertexArray();
  12409. this._vaoRecordInProgress = true;
  12410. this._gl.bindVertexArray(vao);
  12411. this._mustWipeVertexAttributes = true;
  12412. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12413. this.bindIndexBuffer(indexBuffer);
  12414. this._vaoRecordInProgress = false;
  12415. this._gl.bindVertexArray(null);
  12416. return vao;
  12417. };
  12418. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12419. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12420. this._cachedVertexArrayObject = vertexArrayObject;
  12421. this._gl.bindVertexArray(vertexArrayObject);
  12422. this._cachedVertexBuffers = null;
  12423. this._cachedIndexBuffer = null;
  12424. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12425. this._mustWipeVertexAttributes = true;
  12426. }
  12427. };
  12428. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12429. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12430. this._cachedVertexBuffers = vertexBuffer;
  12431. this._cachedEffectForVertexBuffers = effect;
  12432. var attributesCount = effect.getAttributesCount();
  12433. this._unbindVertexArrayObject();
  12434. this.unbindAllAttributes();
  12435. var offset = 0;
  12436. for (var index = 0; index < attributesCount; index++) {
  12437. if (index < vertexDeclaration.length) {
  12438. var order = effect.getAttributeLocation(index);
  12439. if (order >= 0) {
  12440. this._gl.enableVertexAttribArray(order);
  12441. this._vertexAttribArraysEnabled[order] = true;
  12442. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12443. }
  12444. offset += vertexDeclaration[index] * 4;
  12445. }
  12446. }
  12447. }
  12448. this._bindIndexBufferWithCache(indexBuffer);
  12449. };
  12450. Engine.prototype._unbindVertexArrayObject = function () {
  12451. if (!this._cachedVertexArrayObject) {
  12452. return;
  12453. }
  12454. this._cachedVertexArrayObject = null;
  12455. this._gl.bindVertexArray(null);
  12456. };
  12457. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12458. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12459. this._cachedVertexBuffers = vertexBuffers;
  12460. this._cachedEffectForVertexBuffers = effect;
  12461. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12462. }
  12463. this._bindIndexBufferWithCache(indexBuffer);
  12464. };
  12465. Engine.prototype.unbindInstanceAttributes = function () {
  12466. var boundBuffer;
  12467. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12468. var instancesBuffer = this._currentInstanceBuffers[i];
  12469. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12470. boundBuffer = instancesBuffer;
  12471. this.bindArrayBuffer(instancesBuffer);
  12472. }
  12473. var offsetLocation = this._currentInstanceLocations[i];
  12474. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12475. }
  12476. this._currentInstanceBuffers.length = 0;
  12477. this._currentInstanceLocations.length = 0;
  12478. };
  12479. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12480. this._gl.deleteVertexArray(vao);
  12481. };
  12482. Engine.prototype._releaseBuffer = function (buffer) {
  12483. buffer.references--;
  12484. if (buffer.references === 0) {
  12485. this._gl.deleteBuffer(buffer);
  12486. return true;
  12487. }
  12488. return false;
  12489. };
  12490. Engine.prototype.createInstancesBuffer = function (capacity) {
  12491. var buffer = this._gl.createBuffer();
  12492. if (!buffer) {
  12493. throw new Error("Unable to create instance buffer");
  12494. }
  12495. buffer.capacity = capacity;
  12496. this.bindArrayBuffer(buffer);
  12497. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12498. return buffer;
  12499. };
  12500. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12501. this._gl.deleteBuffer(buffer);
  12502. };
  12503. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12504. this.bindArrayBuffer(instancesBuffer);
  12505. if (data) {
  12506. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12507. }
  12508. if (offsetLocations[0].index !== undefined) {
  12509. var stride = 0;
  12510. for (var i = 0; i < offsetLocations.length; i++) {
  12511. var ai = offsetLocations[i];
  12512. stride += ai.attributeSize * 4;
  12513. }
  12514. for (var i = 0; i < offsetLocations.length; i++) {
  12515. var ai = offsetLocations[i];
  12516. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12517. this._gl.enableVertexAttribArray(ai.index);
  12518. this._vertexAttribArraysEnabled[ai.index] = true;
  12519. }
  12520. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12521. this._gl.vertexAttribDivisor(ai.index, 1);
  12522. this._currentInstanceLocations.push(ai.index);
  12523. this._currentInstanceBuffers.push(instancesBuffer);
  12524. }
  12525. }
  12526. else {
  12527. for (var index = 0; index < 4; index++) {
  12528. var offsetLocation = offsetLocations[index];
  12529. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12530. this._gl.enableVertexAttribArray(offsetLocation);
  12531. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12532. }
  12533. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12534. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12535. this._currentInstanceLocations.push(offsetLocation);
  12536. this._currentInstanceBuffers.push(instancesBuffer);
  12537. }
  12538. }
  12539. };
  12540. Engine.prototype.applyStates = function () {
  12541. this._depthCullingState.apply(this._gl);
  12542. this._stencilState.apply(this._gl);
  12543. this._alphaState.apply(this._gl);
  12544. };
  12545. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12546. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12547. };
  12548. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12549. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12550. };
  12551. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12552. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12553. };
  12554. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12555. // Apply states
  12556. this.applyStates();
  12557. this._drawCalls.addCount(1, false);
  12558. // Render
  12559. var drawMode = this._drawMode(fillMode);
  12560. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12561. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12562. if (instancesCount) {
  12563. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12564. }
  12565. else {
  12566. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12567. }
  12568. };
  12569. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12570. // Apply states
  12571. this.applyStates();
  12572. this._drawCalls.addCount(1, false);
  12573. var drawMode = this._drawMode(fillMode);
  12574. if (instancesCount) {
  12575. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12576. }
  12577. else {
  12578. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12579. }
  12580. };
  12581. Engine.prototype._drawMode = function (fillMode) {
  12582. switch (fillMode) {
  12583. // Triangle views
  12584. case BABYLON.Material.TriangleFillMode:
  12585. return this._gl.TRIANGLES;
  12586. case BABYLON.Material.PointFillMode:
  12587. return this._gl.POINTS;
  12588. case BABYLON.Material.WireFrameFillMode:
  12589. return this._gl.LINES;
  12590. // Draw modes
  12591. case BABYLON.Material.PointListDrawMode:
  12592. return this._gl.POINTS;
  12593. case BABYLON.Material.LineListDrawMode:
  12594. return this._gl.LINES;
  12595. case BABYLON.Material.LineLoopDrawMode:
  12596. return this._gl.LINE_LOOP;
  12597. case BABYLON.Material.LineStripDrawMode:
  12598. return this._gl.LINE_STRIP;
  12599. case BABYLON.Material.TriangleStripDrawMode:
  12600. return this._gl.TRIANGLE_STRIP;
  12601. case BABYLON.Material.TriangleFanDrawMode:
  12602. return this._gl.TRIANGLE_FAN;
  12603. default:
  12604. return this._gl.TRIANGLES;
  12605. }
  12606. };
  12607. // Shaders
  12608. Engine.prototype._releaseEffect = function (effect) {
  12609. if (this._compiledEffects[effect._key]) {
  12610. delete this._compiledEffects[effect._key];
  12611. this._deleteProgram(effect.getProgram());
  12612. }
  12613. };
  12614. Engine.prototype._deleteProgram = function (program) {
  12615. if (program) {
  12616. program.__SPECTOR_rebuildProgram = null;
  12617. if (program.transformFeedback) {
  12618. this.deleteTransformFeedback(program.transformFeedback);
  12619. program.transformFeedback = null;
  12620. }
  12621. this._gl.deleteProgram(program);
  12622. }
  12623. };
  12624. /**
  12625. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12626. * @param samplers An array of string used to represent textures
  12627. */
  12628. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12629. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12630. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12631. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12632. if (this._compiledEffects[name]) {
  12633. var compiledEffect = this._compiledEffects[name];
  12634. if (onCompiled && compiledEffect.isReady()) {
  12635. onCompiled(compiledEffect);
  12636. }
  12637. return compiledEffect;
  12638. }
  12639. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12640. effect._key = name;
  12641. this._compiledEffects[name] = effect;
  12642. return effect;
  12643. };
  12644. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12645. if (uniformsNames === void 0) { uniformsNames = []; }
  12646. if (samplers === void 0) { samplers = []; }
  12647. if (defines === void 0) { defines = ""; }
  12648. return this.createEffect({
  12649. vertex: "particles",
  12650. fragmentElement: fragmentName
  12651. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12652. };
  12653. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12654. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12655. context = context || this._gl;
  12656. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12657. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12658. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12659. };
  12660. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12661. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12662. context = context || this._gl;
  12663. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12664. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12665. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12666. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12667. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12668. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12669. return program;
  12670. };
  12671. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12672. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12673. var shaderProgram = context.createProgram();
  12674. if (!shaderProgram) {
  12675. throw new Error("Unable to create program");
  12676. }
  12677. context.attachShader(shaderProgram, vertexShader);
  12678. context.attachShader(shaderProgram, fragmentShader);
  12679. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12680. var transformFeedback = this.createTransformFeedback();
  12681. this.bindTransformFeedback(transformFeedback);
  12682. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12683. shaderProgram.transformFeedback = transformFeedback;
  12684. }
  12685. context.linkProgram(shaderProgram);
  12686. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12687. this.bindTransformFeedback(null);
  12688. }
  12689. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12690. if (!linked) {
  12691. context.validateProgram(shaderProgram);
  12692. var error = context.getProgramInfoLog(shaderProgram);
  12693. if (error) {
  12694. throw new Error(error);
  12695. }
  12696. }
  12697. context.deleteShader(vertexShader);
  12698. context.deleteShader(fragmentShader);
  12699. return shaderProgram;
  12700. };
  12701. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12702. var results = new Array();
  12703. for (var index = 0; index < uniformsNames.length; index++) {
  12704. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12705. }
  12706. return results;
  12707. };
  12708. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12709. var results = [];
  12710. for (var index = 0; index < attributesNames.length; index++) {
  12711. try {
  12712. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12713. }
  12714. catch (e) {
  12715. results.push(-1);
  12716. }
  12717. }
  12718. return results;
  12719. };
  12720. Engine.prototype.enableEffect = function (effect) {
  12721. if (!effect) {
  12722. return;
  12723. }
  12724. // Use program
  12725. this.bindSamplers(effect);
  12726. this._currentEffect = effect;
  12727. if (effect.onBind) {
  12728. effect.onBind(effect);
  12729. }
  12730. effect.onBindObservable.notifyObservers(effect);
  12731. };
  12732. Engine.prototype.setIntArray = function (uniform, array) {
  12733. if (!uniform)
  12734. return;
  12735. this._gl.uniform1iv(uniform, array);
  12736. };
  12737. Engine.prototype.setIntArray2 = function (uniform, array) {
  12738. if (!uniform || array.length % 2 !== 0)
  12739. return;
  12740. this._gl.uniform2iv(uniform, array);
  12741. };
  12742. Engine.prototype.setIntArray3 = function (uniform, array) {
  12743. if (!uniform || array.length % 3 !== 0)
  12744. return;
  12745. this._gl.uniform3iv(uniform, array);
  12746. };
  12747. Engine.prototype.setIntArray4 = function (uniform, array) {
  12748. if (!uniform || array.length % 4 !== 0)
  12749. return;
  12750. this._gl.uniform4iv(uniform, array);
  12751. };
  12752. Engine.prototype.setFloatArray = function (uniform, array) {
  12753. if (!uniform)
  12754. return;
  12755. this._gl.uniform1fv(uniform, array);
  12756. };
  12757. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12758. if (!uniform || array.length % 2 !== 0)
  12759. return;
  12760. this._gl.uniform2fv(uniform, array);
  12761. };
  12762. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12763. if (!uniform || array.length % 3 !== 0)
  12764. return;
  12765. this._gl.uniform3fv(uniform, array);
  12766. };
  12767. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12768. if (!uniform || array.length % 4 !== 0)
  12769. return;
  12770. this._gl.uniform4fv(uniform, array);
  12771. };
  12772. Engine.prototype.setArray = function (uniform, array) {
  12773. if (!uniform)
  12774. return;
  12775. this._gl.uniform1fv(uniform, array);
  12776. };
  12777. Engine.prototype.setArray2 = function (uniform, array) {
  12778. if (!uniform || array.length % 2 !== 0)
  12779. return;
  12780. this._gl.uniform2fv(uniform, array);
  12781. };
  12782. Engine.prototype.setArray3 = function (uniform, array) {
  12783. if (!uniform || array.length % 3 !== 0)
  12784. return;
  12785. this._gl.uniform3fv(uniform, array);
  12786. };
  12787. Engine.prototype.setArray4 = function (uniform, array) {
  12788. if (!uniform || array.length % 4 !== 0)
  12789. return;
  12790. this._gl.uniform4fv(uniform, array);
  12791. };
  12792. Engine.prototype.setMatrices = function (uniform, matrices) {
  12793. if (!uniform)
  12794. return;
  12795. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12796. };
  12797. Engine.prototype.setMatrix = function (uniform, matrix) {
  12798. if (!uniform)
  12799. return;
  12800. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12801. };
  12802. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12803. if (!uniform)
  12804. return;
  12805. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12806. };
  12807. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12808. if (!uniform)
  12809. return;
  12810. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12811. };
  12812. Engine.prototype.setInt = function (uniform, value) {
  12813. if (!uniform)
  12814. return;
  12815. this._gl.uniform1i(uniform, value);
  12816. };
  12817. Engine.prototype.setFloat = function (uniform, value) {
  12818. if (!uniform)
  12819. return;
  12820. this._gl.uniform1f(uniform, value);
  12821. };
  12822. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12823. if (!uniform)
  12824. return;
  12825. this._gl.uniform2f(uniform, x, y);
  12826. };
  12827. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12828. if (!uniform)
  12829. return;
  12830. this._gl.uniform3f(uniform, x, y, z);
  12831. };
  12832. Engine.prototype.setBool = function (uniform, bool) {
  12833. if (!uniform)
  12834. return;
  12835. this._gl.uniform1i(uniform, bool);
  12836. };
  12837. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12838. if (!uniform)
  12839. return;
  12840. this._gl.uniform4f(uniform, x, y, z, w);
  12841. };
  12842. Engine.prototype.setColor3 = function (uniform, color3) {
  12843. if (!uniform)
  12844. return;
  12845. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12846. };
  12847. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12848. if (!uniform)
  12849. return;
  12850. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12851. };
  12852. /**
  12853. * Sets a Color4 on a uniform variable
  12854. * @param uniform defines the uniform location
  12855. * @param color4 defines the value to be set
  12856. */
  12857. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12858. if (!uniform)
  12859. return;
  12860. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12861. };
  12862. // States
  12863. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12864. if (zOffset === void 0) { zOffset = 0; }
  12865. if (reverseSide === void 0) { reverseSide = false; }
  12866. // Culling
  12867. if (this._depthCullingState.cull !== culling || force) {
  12868. this._depthCullingState.cull = culling;
  12869. }
  12870. // Cull face
  12871. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12872. if (this._depthCullingState.cullFace !== cullFace || force) {
  12873. this._depthCullingState.cullFace = cullFace;
  12874. }
  12875. // Z offset
  12876. this.setZOffset(zOffset);
  12877. // Front face
  12878. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12879. if (this._depthCullingState.frontFace !== frontFace || force) {
  12880. this._depthCullingState.frontFace = frontFace;
  12881. }
  12882. };
  12883. Engine.prototype.setZOffset = function (value) {
  12884. this._depthCullingState.zOffset = value;
  12885. };
  12886. Engine.prototype.getZOffset = function () {
  12887. return this._depthCullingState.zOffset;
  12888. };
  12889. Engine.prototype.setDepthBuffer = function (enable) {
  12890. this._depthCullingState.depthTest = enable;
  12891. };
  12892. Engine.prototype.getDepthWrite = function () {
  12893. return this._depthCullingState.depthMask;
  12894. };
  12895. Engine.prototype.setDepthWrite = function (enable) {
  12896. this._depthCullingState.depthMask = enable;
  12897. };
  12898. Engine.prototype.setColorWrite = function (enable) {
  12899. this._gl.colorMask(enable, enable, enable, enable);
  12900. this._colorWrite = enable;
  12901. };
  12902. Engine.prototype.getColorWrite = function () {
  12903. return this._colorWrite;
  12904. };
  12905. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12906. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12907. };
  12908. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12909. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12910. if (this._alphaMode === mode) {
  12911. return;
  12912. }
  12913. switch (mode) {
  12914. case Engine.ALPHA_DISABLE:
  12915. this._alphaState.alphaBlend = false;
  12916. break;
  12917. case Engine.ALPHA_PREMULTIPLIED:
  12918. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12919. this._alphaState.alphaBlend = true;
  12920. break;
  12921. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12922. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12923. this._alphaState.alphaBlend = true;
  12924. break;
  12925. case Engine.ALPHA_COMBINE:
  12926. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12927. this._alphaState.alphaBlend = true;
  12928. break;
  12929. case Engine.ALPHA_ONEONE:
  12930. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12931. this._alphaState.alphaBlend = true;
  12932. break;
  12933. case Engine.ALPHA_ADD:
  12934. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12935. this._alphaState.alphaBlend = true;
  12936. break;
  12937. case Engine.ALPHA_SUBTRACT:
  12938. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12939. this._alphaState.alphaBlend = true;
  12940. break;
  12941. case Engine.ALPHA_MULTIPLY:
  12942. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12943. this._alphaState.alphaBlend = true;
  12944. break;
  12945. case Engine.ALPHA_MAXIMIZED:
  12946. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12947. this._alphaState.alphaBlend = true;
  12948. break;
  12949. case Engine.ALPHA_INTERPOLATE:
  12950. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12951. this._alphaState.alphaBlend = true;
  12952. break;
  12953. case Engine.ALPHA_SCREENMODE:
  12954. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12955. this._alphaState.alphaBlend = true;
  12956. break;
  12957. }
  12958. if (!noDepthWriteChange) {
  12959. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12960. }
  12961. this._alphaMode = mode;
  12962. };
  12963. Engine.prototype.getAlphaMode = function () {
  12964. return this._alphaMode;
  12965. };
  12966. // Textures
  12967. Engine.prototype.wipeCaches = function (bruteForce) {
  12968. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12969. return;
  12970. }
  12971. this._currentEffect = null;
  12972. // 6/8/2017: deltakosh: Should not be required anymore.
  12973. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12974. if (bruteForce) {
  12975. this.resetTextureCache();
  12976. this._currentProgram = null;
  12977. this._stencilState.reset();
  12978. this._depthCullingState.reset();
  12979. this.setDepthFunctionToLessOrEqual();
  12980. this._alphaState.reset();
  12981. }
  12982. this._resetVertexBufferBinding();
  12983. this._cachedIndexBuffer = null;
  12984. this._cachedEffectForVertexBuffers = null;
  12985. this._unbindVertexArrayObject();
  12986. this.bindIndexBuffer(null);
  12987. };
  12988. /**
  12989. * Set the compressed texture format to use, based on the formats you have, and the formats
  12990. * supported by the hardware / browser.
  12991. *
  12992. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12993. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12994. * to API arguments needed to compressed textures. This puts the burden on the container
  12995. * generator to house the arcane code for determining these for current & future formats.
  12996. *
  12997. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12998. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12999. *
  13000. * Note: The result of this call is not taken into account when a texture is base64.
  13001. *
  13002. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13003. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13004. *
  13005. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13006. * @returns The extension selected.
  13007. */
  13008. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13009. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13010. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13011. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13012. return this._textureFormatInUse = this._texturesSupported[i];
  13013. }
  13014. }
  13015. }
  13016. // actively set format to nothing, to allow this to be called more than once
  13017. // and possibly fail the 2nd time
  13018. this._textureFormatInUse = null;
  13019. return null;
  13020. };
  13021. Engine.prototype._createTexture = function () {
  13022. var texture = this._gl.createTexture();
  13023. if (!texture) {
  13024. throw new Error("Unable to create texture");
  13025. }
  13026. return texture;
  13027. };
  13028. /**
  13029. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13030. * @param {string} urlArg- This contains one of the following:
  13031. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13032. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13033. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13034. *
  13035. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13036. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13037. * @param {Scene} scene- Needed for loading to the correct scene.
  13038. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13039. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13040. * @param {callback} onError- Optional callback to be called upon failure.
  13041. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13042. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13043. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13044. *
  13045. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13046. */
  13047. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13048. var _this = this;
  13049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13050. if (onLoad === void 0) { onLoad = null; }
  13051. if (onError === void 0) { onError = null; }
  13052. if (buffer === void 0) { buffer = null; }
  13053. if (fallBack === void 0) { fallBack = null; }
  13054. if (format === void 0) { format = null; }
  13055. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13056. var fromData = url.substr(0, 5) === "data:";
  13057. var fromBlob = url.substr(0, 5) === "blob:";
  13058. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13059. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13060. // establish the file extension, if possible
  13061. var lastDot = url.lastIndexOf('.');
  13062. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13063. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13064. var isTGA = (extension.indexOf(".tga") === 0);
  13065. // determine if a ktx file should be substituted
  13066. var isKTX = false;
  13067. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13068. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13069. isKTX = true;
  13070. }
  13071. if (scene) {
  13072. scene._addPendingData(texture);
  13073. }
  13074. texture.url = url;
  13075. texture.generateMipMaps = !noMipmap;
  13076. texture.samplingMode = samplingMode;
  13077. texture.invertY = invertY;
  13078. if (!this._doNotHandleContextLost) {
  13079. // Keep a link to the buffer only if we plan to handle context lost
  13080. texture._buffer = buffer;
  13081. }
  13082. var onLoadObserver = null;
  13083. if (onLoad && !fallBack) {
  13084. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13085. }
  13086. if (!fallBack)
  13087. this._internalTexturesCache.push(texture);
  13088. var onerror = function (message, exception) {
  13089. if (scene) {
  13090. scene._removePendingData(texture);
  13091. }
  13092. if (onLoadObserver) {
  13093. texture.onLoadedObservable.remove(onLoadObserver);
  13094. }
  13095. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13096. if (isKTX) {
  13097. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13098. }
  13099. else if (BABYLON.Tools.UseFallbackTexture) {
  13100. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13101. }
  13102. if (onError) {
  13103. onError(message || "Unknown error", exception);
  13104. }
  13105. };
  13106. var callback = null;
  13107. // processing for non-image formats
  13108. if (isKTX || isTGA || isDDS) {
  13109. if (isKTX) {
  13110. callback = function (data) {
  13111. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13112. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13113. ktx.uploadLevels(_this._gl, !noMipmap);
  13114. return false;
  13115. }, samplingMode);
  13116. };
  13117. }
  13118. else if (isTGA) {
  13119. callback = function (arrayBuffer) {
  13120. var data = new Uint8Array(arrayBuffer);
  13121. var header = BABYLON.TGATools.GetTGAHeader(data);
  13122. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13123. BABYLON.TGATools.UploadContent(_this._gl, data);
  13124. return false;
  13125. }, samplingMode);
  13126. };
  13127. }
  13128. else if (isDDS) {
  13129. callback = function (data) {
  13130. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13131. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13132. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13133. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13134. return false;
  13135. }, samplingMode);
  13136. };
  13137. }
  13138. if (!buffer) {
  13139. this._loadFile(url, function (data) {
  13140. if (callback) {
  13141. callback(data);
  13142. }
  13143. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13144. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13145. });
  13146. }
  13147. else {
  13148. if (callback) {
  13149. callback(buffer);
  13150. }
  13151. }
  13152. // image format processing
  13153. }
  13154. else {
  13155. var onload = function (img) {
  13156. if (fromBlob && !_this._doNotHandleContextLost) {
  13157. // We need to store the image if we need to rebuild the texture
  13158. // in case of a webgl context lost
  13159. texture._buffer = img;
  13160. }
  13161. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13162. var gl = _this._gl;
  13163. var isPot = (img.width === potWidth && img.height === potHeight);
  13164. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13165. if (isPot) {
  13166. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13167. return false;
  13168. }
  13169. // Using shaders to rescale because canvas.drawImage is lossy
  13170. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13171. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13172. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13177. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13178. _this._releaseTexture(source);
  13179. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13180. continuationCallback();
  13181. });
  13182. return true;
  13183. }, samplingMode);
  13184. };
  13185. if (!fromData || isBase64)
  13186. if (buffer instanceof HTMLImageElement) {
  13187. onload(buffer);
  13188. }
  13189. else {
  13190. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13191. }
  13192. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13193. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13194. else
  13195. onload(buffer);
  13196. }
  13197. return texture;
  13198. };
  13199. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13200. var _this = this;
  13201. var rtt = this.createRenderTargetTexture({
  13202. width: destination.width,
  13203. height: destination.height,
  13204. }, {
  13205. generateMipMaps: false,
  13206. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13207. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13208. generateDepthBuffer: false,
  13209. generateStencilBuffer: false
  13210. });
  13211. if (!this._rescalePostProcess) {
  13212. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13213. }
  13214. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13215. _this._rescalePostProcess.onApply = function (effect) {
  13216. effect._bindTexture("textureSampler", source);
  13217. };
  13218. var hostingScene = scene;
  13219. if (!hostingScene) {
  13220. hostingScene = _this.scenes[_this.scenes.length - 1];
  13221. }
  13222. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13223. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13224. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13225. _this.unBindFramebuffer(rtt);
  13226. _this._releaseTexture(rtt);
  13227. if (onComplete) {
  13228. onComplete();
  13229. }
  13230. });
  13231. };
  13232. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13233. if (compression === void 0) { compression = null; }
  13234. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13235. if (!texture) {
  13236. return;
  13237. }
  13238. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13239. var internalFormat = this._getInternalFormat(format);
  13240. var textureType = this._getWebGLTextureType(type);
  13241. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13242. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13243. if (!this._doNotHandleContextLost) {
  13244. texture._bufferView = data;
  13245. texture.format = format;
  13246. texture.type = type;
  13247. texture.invertY = invertY;
  13248. texture._compression = compression;
  13249. }
  13250. if (texture.width % 4 !== 0) {
  13251. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13252. }
  13253. if (compression && data) {
  13254. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13255. }
  13256. else {
  13257. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13258. }
  13259. if (texture.generateMipMaps) {
  13260. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13261. }
  13262. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13263. // this.resetTextureCache();
  13264. texture.isReady = true;
  13265. };
  13266. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13267. if (compression === void 0) { compression = null; }
  13268. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13269. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13270. texture.baseWidth = width;
  13271. texture.baseHeight = height;
  13272. texture.width = width;
  13273. texture.height = height;
  13274. texture.format = format;
  13275. texture.generateMipMaps = generateMipMaps;
  13276. texture.samplingMode = samplingMode;
  13277. texture.invertY = invertY;
  13278. texture._compression = compression;
  13279. texture.type = type;
  13280. if (!this._doNotHandleContextLost) {
  13281. texture._bufferView = data;
  13282. }
  13283. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13284. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13285. // Filters
  13286. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13287. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13288. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13289. if (generateMipMaps) {
  13290. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13291. }
  13292. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13293. this._internalTexturesCache.push(texture);
  13294. return texture;
  13295. };
  13296. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13297. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13298. texture.baseWidth = width;
  13299. texture.baseHeight = height;
  13300. if (generateMipMaps) {
  13301. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13302. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13303. }
  13304. // this.resetTextureCache();
  13305. texture.width = width;
  13306. texture.height = height;
  13307. texture.isReady = false;
  13308. texture.generateMipMaps = generateMipMaps;
  13309. texture.samplingMode = samplingMode;
  13310. this.updateTextureSamplingMode(samplingMode, texture);
  13311. this._internalTexturesCache.push(texture);
  13312. return texture;
  13313. };
  13314. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13315. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13316. if (texture.isCube) {
  13317. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13318. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13319. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13320. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13321. }
  13322. else if (texture.is3D) {
  13323. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13324. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13325. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13326. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13327. }
  13328. else {
  13329. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13330. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13332. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13333. }
  13334. texture.samplingMode = samplingMode;
  13335. };
  13336. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13337. if (premulAlpha === void 0) { premulAlpha = false; }
  13338. if (!texture) {
  13339. return;
  13340. }
  13341. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13342. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13343. if (premulAlpha) {
  13344. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13345. }
  13346. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13347. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13348. if (texture.generateMipMaps) {
  13349. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13350. }
  13351. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13352. if (premulAlpha) {
  13353. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13354. }
  13355. texture.isReady = true;
  13356. };
  13357. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13358. if (!texture || texture._isDisabled) {
  13359. return;
  13360. }
  13361. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13362. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13363. try {
  13364. // Testing video texture support
  13365. if (this._videoTextureSupported === undefined) {
  13366. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13367. if (this._gl.getError() !== 0) {
  13368. this._videoTextureSupported = false;
  13369. }
  13370. else {
  13371. this._videoTextureSupported = true;
  13372. }
  13373. }
  13374. // Copy video through the current working canvas if video texture is not supported
  13375. if (!this._videoTextureSupported) {
  13376. if (!texture._workingCanvas) {
  13377. texture._workingCanvas = document.createElement("canvas");
  13378. var context = texture._workingCanvas.getContext("2d");
  13379. if (!context) {
  13380. throw new Error("Unable to get 2d context");
  13381. }
  13382. texture._workingContext = context;
  13383. texture._workingCanvas.width = texture.width;
  13384. texture._workingCanvas.height = texture.height;
  13385. }
  13386. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13387. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13388. }
  13389. else {
  13390. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13391. }
  13392. if (texture.generateMipMaps) {
  13393. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13394. }
  13395. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13396. // this.resetTextureCache();
  13397. texture.isReady = true;
  13398. }
  13399. catch (ex) {
  13400. // Something unexpected
  13401. // Let's disable the texture
  13402. texture._isDisabled = true;
  13403. }
  13404. };
  13405. /**
  13406. * Updates a depth texture Comparison Mode and Function.
  13407. * If the comparison Function is equal to 0, the mode will be set to none.
  13408. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13409. * @param texture The texture to set the comparison function for
  13410. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13411. */
  13412. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13413. if (this.webGLVersion === 1) {
  13414. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13415. return;
  13416. }
  13417. var gl = this._gl;
  13418. if (texture.isCube) {
  13419. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13420. if (comparisonFunction === 0) {
  13421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13423. }
  13424. else {
  13425. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13426. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13427. }
  13428. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13429. }
  13430. else {
  13431. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13432. if (comparisonFunction === 0) {
  13433. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13435. }
  13436. else {
  13437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13439. }
  13440. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13441. }
  13442. texture._comparisonFunction = comparisonFunction;
  13443. };
  13444. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13445. var width = size.width || size;
  13446. var height = size.height || size;
  13447. internalTexture.baseWidth = width;
  13448. internalTexture.baseHeight = height;
  13449. internalTexture.width = width;
  13450. internalTexture.height = height;
  13451. internalTexture.isReady = true;
  13452. internalTexture.samples = 1;
  13453. internalTexture.generateMipMaps = false;
  13454. internalTexture._generateDepthBuffer = true;
  13455. internalTexture._generateStencilBuffer = generateStencil;
  13456. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13457. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13458. internalTexture._comparisonFunction = comparisonFunction;
  13459. var gl = this._gl;
  13460. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13461. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13462. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13463. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13464. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13465. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13466. if (comparisonFunction === 0) {
  13467. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13468. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13469. }
  13470. else {
  13471. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13472. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13473. }
  13474. };
  13475. /**
  13476. * Creates a depth stencil texture.
  13477. * This is only available in WebGL 2 or with the depth texture extension available.
  13478. * @param size The size of face edge in the texture.
  13479. * @param options The options defining the texture.
  13480. * @returns The texture
  13481. */
  13482. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13483. if (options.isCube) {
  13484. var width = size.width || size;
  13485. return this._createDepthStencilCubeTexture(width, options);
  13486. }
  13487. else {
  13488. return this._createDepthStencilTexture(size, options);
  13489. }
  13490. };
  13491. /**
  13492. * Creates a depth stencil texture.
  13493. * This is only available in WebGL 2 or with the depth texture extension available.
  13494. * @param size The size of face edge in the texture.
  13495. * @param options The options defining the texture.
  13496. * @returns The texture
  13497. */
  13498. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13499. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13500. if (!this._caps.depthTextureExtension) {
  13501. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13502. return internalTexture;
  13503. }
  13504. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13505. var gl = this._gl;
  13506. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13507. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13508. if (this.webGLVersion > 1) {
  13509. if (internalOptions.generateStencil) {
  13510. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13511. }
  13512. else {
  13513. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13514. }
  13515. }
  13516. else {
  13517. if (internalOptions.generateStencil) {
  13518. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13519. }
  13520. else {
  13521. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13522. }
  13523. }
  13524. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13525. return internalTexture;
  13526. };
  13527. /**
  13528. * Creates a depth stencil cube texture.
  13529. * This is only available in WebGL 2.
  13530. * @param size The size of face edge in the cube texture.
  13531. * @param options The options defining the cube texture.
  13532. * @returns The cube texture
  13533. */
  13534. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13535. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13536. internalTexture.isCube = true;
  13537. if (this.webGLVersion === 1) {
  13538. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13539. return internalTexture;
  13540. }
  13541. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13542. var gl = this._gl;
  13543. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13544. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13545. // Create the depth/stencil buffer
  13546. for (var face = 0; face < 6; face++) {
  13547. if (internalOptions.generateStencil) {
  13548. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13549. }
  13550. else {
  13551. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13552. }
  13553. }
  13554. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13555. return internalTexture;
  13556. };
  13557. /**
  13558. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13559. * @param renderTarget The render target to set the frame buffer for
  13560. */
  13561. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13562. // Create the framebuffer
  13563. var internalTexture = renderTarget.getInternalTexture();
  13564. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13565. return;
  13566. }
  13567. var gl = this._gl;
  13568. var depthStencilTexture = renderTarget.depthStencilTexture;
  13569. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13570. if (depthStencilTexture.isCube) {
  13571. if (depthStencilTexture._generateStencilBuffer) {
  13572. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13573. }
  13574. else {
  13575. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13576. }
  13577. }
  13578. else {
  13579. if (depthStencilTexture._generateStencilBuffer) {
  13580. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13581. }
  13582. else {
  13583. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13584. }
  13585. }
  13586. this.bindUnboundFramebuffer(null);
  13587. };
  13588. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13589. var fullOptions = new RenderTargetCreationOptions();
  13590. if (options !== undefined && typeof options === "object") {
  13591. fullOptions.generateMipMaps = options.generateMipMaps;
  13592. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13593. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13594. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13595. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13596. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13597. }
  13598. else {
  13599. fullOptions.generateMipMaps = options;
  13600. fullOptions.generateDepthBuffer = true;
  13601. fullOptions.generateStencilBuffer = false;
  13602. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13603. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13604. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13605. }
  13606. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13607. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13608. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13609. }
  13610. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13611. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13612. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13613. }
  13614. var gl = this._gl;
  13615. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13616. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13617. var width = size.width || size;
  13618. var height = size.height || size;
  13619. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13620. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13621. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13622. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13623. }
  13624. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13625. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13628. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13629. // Create the framebuffer
  13630. var framebuffer = gl.createFramebuffer();
  13631. this.bindUnboundFramebuffer(framebuffer);
  13632. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13633. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13634. if (fullOptions.generateMipMaps) {
  13635. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13636. }
  13637. // Unbind
  13638. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13639. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13640. this.bindUnboundFramebuffer(null);
  13641. texture._framebuffer = framebuffer;
  13642. texture.baseWidth = width;
  13643. texture.baseHeight = height;
  13644. texture.width = width;
  13645. texture.height = height;
  13646. texture.isReady = true;
  13647. texture.samples = 1;
  13648. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13649. texture.samplingMode = fullOptions.samplingMode;
  13650. texture.type = fullOptions.type;
  13651. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13652. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13653. // this.resetTextureCache();
  13654. this._internalTexturesCache.push(texture);
  13655. return texture;
  13656. };
  13657. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13658. var generateMipMaps = false;
  13659. var generateDepthBuffer = true;
  13660. var generateStencilBuffer = false;
  13661. var generateDepthTexture = false;
  13662. var textureCount = 1;
  13663. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13664. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13665. var types = [], samplingModes = [];
  13666. if (options !== undefined) {
  13667. generateMipMaps = options.generateMipMaps;
  13668. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13669. generateStencilBuffer = options.generateStencilBuffer;
  13670. generateDepthTexture = options.generateDepthTexture;
  13671. textureCount = options.textureCount || 1;
  13672. if (options.types) {
  13673. types = options.types;
  13674. }
  13675. if (options.samplingModes) {
  13676. samplingModes = options.samplingModes;
  13677. }
  13678. }
  13679. var gl = this._gl;
  13680. // Create the framebuffer
  13681. var framebuffer = gl.createFramebuffer();
  13682. this.bindUnboundFramebuffer(framebuffer);
  13683. var width = size.width || size;
  13684. var height = size.height || size;
  13685. var textures = [];
  13686. var attachments = [];
  13687. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13688. for (var i = 0; i < textureCount; i++) {
  13689. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13690. var type = types[i] || defaultType;
  13691. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13692. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13693. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13694. }
  13695. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13696. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13697. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13698. }
  13699. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13700. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13701. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13702. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13703. }
  13704. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13705. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13706. textures.push(texture);
  13707. attachments.push(attachment);
  13708. gl.activeTexture(gl["TEXTURE" + i]);
  13709. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13710. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13711. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13712. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13714. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13715. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13716. if (generateMipMaps) {
  13717. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13718. }
  13719. // Unbind
  13720. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13721. texture._framebuffer = framebuffer;
  13722. texture._depthStencilBuffer = depthStencilBuffer;
  13723. texture.baseWidth = width;
  13724. texture.baseHeight = height;
  13725. texture.width = width;
  13726. texture.height = height;
  13727. texture.isReady = true;
  13728. texture.samples = 1;
  13729. texture.generateMipMaps = generateMipMaps;
  13730. texture.samplingMode = samplingMode;
  13731. texture.type = type;
  13732. texture._generateDepthBuffer = generateDepthBuffer;
  13733. texture._generateStencilBuffer = generateStencilBuffer;
  13734. texture._attachments = attachments;
  13735. this._internalTexturesCache.push(texture);
  13736. }
  13737. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13738. // Depth texture
  13739. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13740. gl.activeTexture(gl.TEXTURE0);
  13741. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13742. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13743. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13744. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13745. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13746. 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);
  13747. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13748. depthTexture._framebuffer = framebuffer;
  13749. depthTexture.baseWidth = width;
  13750. depthTexture.baseHeight = height;
  13751. depthTexture.width = width;
  13752. depthTexture.height = height;
  13753. depthTexture.isReady = true;
  13754. depthTexture.samples = 1;
  13755. depthTexture.generateMipMaps = generateMipMaps;
  13756. depthTexture.samplingMode = gl.NEAREST;
  13757. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13758. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13759. textures.push(depthTexture);
  13760. this._internalTexturesCache.push(depthTexture);
  13761. }
  13762. gl.drawBuffers(attachments);
  13763. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13764. this.bindUnboundFramebuffer(null);
  13765. this.resetTextureCache();
  13766. return textures;
  13767. };
  13768. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13769. if (samples === void 0) { samples = 1; }
  13770. var depthStencilBuffer = null;
  13771. var gl = this._gl;
  13772. // Create the depth/stencil buffer
  13773. if (generateStencilBuffer) {
  13774. depthStencilBuffer = gl.createRenderbuffer();
  13775. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13776. if (samples > 1) {
  13777. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13778. }
  13779. else {
  13780. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13781. }
  13782. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13783. }
  13784. else if (generateDepthBuffer) {
  13785. depthStencilBuffer = gl.createRenderbuffer();
  13786. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13787. if (samples > 1) {
  13788. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13789. }
  13790. else {
  13791. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13792. }
  13793. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13794. }
  13795. return depthStencilBuffer;
  13796. };
  13797. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13798. if (this.webGLVersion < 2 || !texture) {
  13799. return 1;
  13800. }
  13801. if (texture.samples === samples) {
  13802. return samples;
  13803. }
  13804. var gl = this._gl;
  13805. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13806. // Dispose previous render buffers
  13807. if (texture._depthStencilBuffer) {
  13808. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13809. texture._depthStencilBuffer = null;
  13810. }
  13811. if (texture._MSAAFramebuffer) {
  13812. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13813. texture._MSAAFramebuffer = null;
  13814. }
  13815. if (texture._MSAARenderBuffer) {
  13816. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13817. texture._MSAARenderBuffer = null;
  13818. }
  13819. if (samples > 1) {
  13820. var framebuffer = gl.createFramebuffer();
  13821. if (!framebuffer) {
  13822. throw new Error("Unable to create multi sampled framebuffer");
  13823. }
  13824. texture._MSAAFramebuffer = framebuffer;
  13825. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13826. var colorRenderbuffer = gl.createRenderbuffer();
  13827. if (!colorRenderbuffer) {
  13828. throw new Error("Unable to create multi sampled framebuffer");
  13829. }
  13830. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13831. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13832. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13833. texture._MSAARenderBuffer = colorRenderbuffer;
  13834. }
  13835. else {
  13836. this.bindUnboundFramebuffer(texture._framebuffer);
  13837. }
  13838. texture.samples = samples;
  13839. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13840. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13841. this.bindUnboundFramebuffer(null);
  13842. return samples;
  13843. };
  13844. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13845. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13846. return 1;
  13847. }
  13848. if (textures[0].samples === samples) {
  13849. return samples;
  13850. }
  13851. var gl = this._gl;
  13852. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13853. // Dispose previous render buffers
  13854. if (textures[0]._depthStencilBuffer) {
  13855. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13856. textures[0]._depthStencilBuffer = null;
  13857. }
  13858. if (textures[0]._MSAAFramebuffer) {
  13859. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13860. textures[0]._MSAAFramebuffer = null;
  13861. }
  13862. for (var i = 0; i < textures.length; i++) {
  13863. if (textures[i]._MSAARenderBuffer) {
  13864. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13865. textures[i]._MSAARenderBuffer = null;
  13866. }
  13867. }
  13868. if (samples > 1) {
  13869. var framebuffer = gl.createFramebuffer();
  13870. if (!framebuffer) {
  13871. throw new Error("Unable to create multi sampled framebuffer");
  13872. }
  13873. this.bindUnboundFramebuffer(framebuffer);
  13874. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13875. var attachments = [];
  13876. for (var i = 0; i < textures.length; i++) {
  13877. var texture = textures[i];
  13878. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13879. var colorRenderbuffer = gl.createRenderbuffer();
  13880. if (!colorRenderbuffer) {
  13881. throw new Error("Unable to create multi sampled framebuffer");
  13882. }
  13883. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13884. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13885. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13886. texture._MSAAFramebuffer = framebuffer;
  13887. texture._MSAARenderBuffer = colorRenderbuffer;
  13888. texture.samples = samples;
  13889. texture._depthStencilBuffer = depthStencilBuffer;
  13890. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13891. attachments.push(attachment);
  13892. }
  13893. gl.drawBuffers(attachments);
  13894. }
  13895. else {
  13896. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13897. }
  13898. this.bindUnboundFramebuffer(null);
  13899. return samples;
  13900. };
  13901. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13902. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13903. };
  13904. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13905. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13906. };
  13907. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13908. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13909. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13910. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13911. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13912. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13913. }
  13914. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13915. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13916. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13917. }
  13918. var gl = this._gl;
  13919. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13920. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13921. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13922. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13923. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13924. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13925. }
  13926. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13927. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13929. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13930. for (var face = 0; face < 6; face++) {
  13931. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13932. }
  13933. // Create the framebuffer
  13934. var framebuffer = gl.createFramebuffer();
  13935. this.bindUnboundFramebuffer(framebuffer);
  13936. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13937. // MipMaps
  13938. if (fullOptions.generateMipMaps) {
  13939. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13940. }
  13941. // Unbind
  13942. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13943. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13944. this.bindUnboundFramebuffer(null);
  13945. texture._framebuffer = framebuffer;
  13946. texture.width = size;
  13947. texture.height = size;
  13948. texture.isReady = true;
  13949. texture.isCube = true;
  13950. texture.samples = 1;
  13951. texture.generateMipMaps = fullOptions.generateMipMaps;
  13952. texture.samplingMode = fullOptions.samplingMode;
  13953. texture.type = fullOptions.type;
  13954. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13955. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13956. this._internalTexturesCache.push(texture);
  13957. return texture;
  13958. };
  13959. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13960. var _this = this;
  13961. if (onLoad === void 0) { onLoad = null; }
  13962. if (onError === void 0) { onError = null; }
  13963. if (forcedExtension === void 0) { forcedExtension = null; }
  13964. var callback = function (loadData) {
  13965. if (!loadData) {
  13966. if (onLoad) {
  13967. onLoad(null);
  13968. }
  13969. return;
  13970. }
  13971. var texture = loadData.texture;
  13972. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13973. texture._lodGenerationScale = scale;
  13974. texture._lodGenerationOffset = offset;
  13975. if (_this._caps.textureLOD) {
  13976. // Do not add extra process if texture lod is supported.
  13977. if (onLoad) {
  13978. onLoad(texture);
  13979. }
  13980. return;
  13981. }
  13982. var mipSlices = 3;
  13983. var gl = _this._gl;
  13984. var width = loadData.width;
  13985. if (!width) {
  13986. return;
  13987. }
  13988. var textures = [];
  13989. for (var i = 0; i < mipSlices; i++) {
  13990. //compute LOD from even spacing in smoothness (matching shader calculation)
  13991. var smoothness = i / (mipSlices - 1);
  13992. var roughness = 1 - smoothness;
  13993. var minLODIndex = offset; // roughness = 0
  13994. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13995. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13996. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13997. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13998. glTextureFromLod.isCube = true;
  13999. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14000. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14002. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14004. if (loadData.isDDS) {
  14005. var info = loadData.info;
  14006. var data = loadData.data;
  14007. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14008. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14009. }
  14010. else {
  14011. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14012. }
  14013. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14014. // Wrap in a base texture for easy binding.
  14015. var lodTexture = new BABYLON.BaseTexture(scene);
  14016. lodTexture.isCube = true;
  14017. lodTexture._texture = glTextureFromLod;
  14018. glTextureFromLod.isReady = true;
  14019. textures.push(lodTexture);
  14020. }
  14021. texture._lodTextureHigh = textures[2];
  14022. texture._lodTextureMid = textures[1];
  14023. texture._lodTextureLow = textures[0];
  14024. if (onLoad) {
  14025. onLoad(texture);
  14026. }
  14027. };
  14028. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14029. };
  14030. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14031. var _this = this;
  14032. if (onLoad === void 0) { onLoad = null; }
  14033. if (onError === void 0) { onError = null; }
  14034. if (forcedExtension === void 0) { forcedExtension = null; }
  14035. var gl = this._gl;
  14036. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14037. texture.isCube = true;
  14038. texture.url = rootUrl;
  14039. texture.generateMipMaps = !noMipmap;
  14040. if (!this._doNotHandleContextLost) {
  14041. texture._extension = forcedExtension;
  14042. texture._files = files;
  14043. }
  14044. var isKTX = false;
  14045. var isDDS = false;
  14046. var lastDot = rootUrl.lastIndexOf('.');
  14047. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14048. if (this._textureFormatInUse) {
  14049. extension = this._textureFormatInUse;
  14050. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14051. isKTX = true;
  14052. }
  14053. else {
  14054. isDDS = (extension === ".dds");
  14055. }
  14056. var onerror = function (request, exception) {
  14057. if (onError && request) {
  14058. onError(request.status + " " + request.statusText, exception);
  14059. }
  14060. };
  14061. if (isKTX) {
  14062. this._loadFile(rootUrl, function (data) {
  14063. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14064. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14065. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14066. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14067. ktx.uploadLevels(_this._gl, !noMipmap);
  14068. _this.setCubeMapTextureParams(gl, loadMipmap);
  14069. texture.width = ktx.pixelWidth;
  14070. texture.height = ktx.pixelHeight;
  14071. texture.isReady = true;
  14072. }, undefined, undefined, true, onerror);
  14073. }
  14074. else if (isDDS) {
  14075. if (files && files.length === 6) {
  14076. this._cascadeLoadFiles(scene, function (imgs) {
  14077. var info;
  14078. var loadMipmap = false;
  14079. var width = 0;
  14080. for (var index = 0; index < imgs.length; index++) {
  14081. var data = imgs[index];
  14082. info = BABYLON.DDSTools.GetDDSInfo(data);
  14083. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14084. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14085. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14086. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14087. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14088. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14089. }
  14090. texture.width = info.width;
  14091. texture.height = info.height;
  14092. texture.type = info.textureType;
  14093. width = info.width;
  14094. }
  14095. _this.setCubeMapTextureParams(gl, loadMipmap);
  14096. texture.isReady = true;
  14097. if (onLoad) {
  14098. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14099. }
  14100. }, files, onError);
  14101. }
  14102. else {
  14103. this._loadFile(rootUrl, function (data) {
  14104. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14105. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14106. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14107. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14108. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14109. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14110. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14111. }
  14112. _this.setCubeMapTextureParams(gl, loadMipmap);
  14113. texture.width = info.width;
  14114. texture.height = info.height;
  14115. texture.isReady = true;
  14116. texture.type = info.textureType;
  14117. if (onLoad) {
  14118. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14119. }
  14120. }, undefined, undefined, true, onerror);
  14121. }
  14122. }
  14123. else {
  14124. if (!files) {
  14125. throw new Error("Cannot load cubemap because files were not defined");
  14126. }
  14127. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14128. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14129. var height = width;
  14130. _this._prepareWorkingCanvas();
  14131. if (!_this._workingCanvas || !_this._workingContext) {
  14132. return;
  14133. }
  14134. _this._workingCanvas.width = width;
  14135. _this._workingCanvas.height = height;
  14136. var faces = [
  14137. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14138. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14139. ];
  14140. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14141. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14142. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14143. for (var index = 0; index < faces.length; index++) {
  14144. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14145. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14146. }
  14147. if (!noMipmap) {
  14148. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14149. }
  14150. _this.setCubeMapTextureParams(gl, !noMipmap);
  14151. texture.width = width;
  14152. texture.height = height;
  14153. texture.isReady = true;
  14154. if (format) {
  14155. texture.format = format;
  14156. }
  14157. texture.onLoadedObservable.notifyObservers(texture);
  14158. texture.onLoadedObservable.clear();
  14159. if (onLoad) {
  14160. onLoad();
  14161. }
  14162. }, files, onError);
  14163. }
  14164. this._internalTexturesCache.push(texture);
  14165. return texture;
  14166. };
  14167. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14168. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14169. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14170. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14171. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14172. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14173. // this.resetTextureCache();
  14174. };
  14175. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14176. if (compression === void 0) { compression = null; }
  14177. if (level === void 0) { level = 0; }
  14178. texture._bufferViewArray = data;
  14179. texture.format = format;
  14180. texture.type = type;
  14181. texture.invertY = invertY;
  14182. texture._compression = compression;
  14183. var gl = this._gl;
  14184. var textureType = this._getWebGLTextureType(type);
  14185. var internalFormat = this._getInternalFormat(format);
  14186. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14187. var needConversion = false;
  14188. if (internalFormat === gl.RGB) {
  14189. internalFormat = gl.RGBA;
  14190. needConversion = true;
  14191. }
  14192. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14193. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14194. if (texture.width % 4 !== 0) {
  14195. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14196. }
  14197. // Data are known to be in +X +Y +Z -X -Y -Z
  14198. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14199. var faceData = data[faceIndex];
  14200. if (compression) {
  14201. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14202. }
  14203. else {
  14204. if (needConversion) {
  14205. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14206. }
  14207. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14208. }
  14209. }
  14210. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14211. if (isPot && texture.generateMipMaps && level === 0) {
  14212. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14213. }
  14214. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14215. // this.resetTextureCache();
  14216. texture.isReady = true;
  14217. };
  14218. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14219. if (compression === void 0) { compression = null; }
  14220. var gl = this._gl;
  14221. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14222. texture.isCube = true;
  14223. texture.generateMipMaps = generateMipMaps;
  14224. texture.format = format;
  14225. texture.type = type;
  14226. if (!this._doNotHandleContextLost) {
  14227. texture._bufferViewArray = data;
  14228. }
  14229. var textureType = this._getWebGLTextureType(type);
  14230. var internalFormat = this._getInternalFormat(format);
  14231. if (internalFormat === gl.RGB) {
  14232. internalFormat = gl.RGBA;
  14233. }
  14234. var width = size;
  14235. var height = width;
  14236. texture.width = width;
  14237. texture.height = height;
  14238. // Double check on POT to generate Mips.
  14239. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14240. if (!isPot) {
  14241. generateMipMaps = false;
  14242. }
  14243. // Upload data if needed. The texture won't be ready until then.
  14244. if (data) {
  14245. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14246. }
  14247. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14248. // Filters
  14249. if (data && generateMipMaps) {
  14250. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14251. }
  14252. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14253. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14254. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14255. }
  14256. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14257. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14258. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14259. }
  14260. else {
  14261. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14262. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14263. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14264. }
  14265. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14266. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14267. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14268. return texture;
  14269. };
  14270. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14271. var _this = this;
  14272. if (onLoad === void 0) { onLoad = null; }
  14273. if (onError === void 0) { onError = null; }
  14274. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14275. if (invertY === void 0) { invertY = false; }
  14276. var gl = this._gl;
  14277. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14278. scene._addPendingData(texture);
  14279. texture.url = url;
  14280. this._internalTexturesCache.push(texture);
  14281. var onerror = function (request, exception) {
  14282. scene._removePendingData(texture);
  14283. if (onError && request) {
  14284. onError(request.status + " " + request.statusText, exception);
  14285. }
  14286. };
  14287. var internalCallback = function (data) {
  14288. var width = texture.width;
  14289. var faceDataArrays = callback(data);
  14290. if (!faceDataArrays) {
  14291. return;
  14292. }
  14293. if (mipmmapGenerator) {
  14294. var textureType = _this._getWebGLTextureType(type);
  14295. var internalFormat = _this._getInternalFormat(format);
  14296. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14297. var needConversion = false;
  14298. if (internalFormat === gl.RGB) {
  14299. internalFormat = gl.RGBA;
  14300. needConversion = true;
  14301. }
  14302. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14303. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14304. var mipData = mipmmapGenerator(faceDataArrays);
  14305. for (var level = 0; level < mipData.length; level++) {
  14306. var mipSize = width >> level;
  14307. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14308. var mipFaceData = mipData[level][faceIndex];
  14309. if (needConversion) {
  14310. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14311. }
  14312. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14313. }
  14314. }
  14315. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14316. }
  14317. else {
  14318. texture.generateMipMaps = !noMipmap;
  14319. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14320. }
  14321. texture.isReady = true;
  14322. // this.resetTextureCache();
  14323. scene._removePendingData(texture);
  14324. if (onLoad) {
  14325. onLoad();
  14326. }
  14327. };
  14328. this._loadFile(url, function (data) {
  14329. internalCallback(data);
  14330. }, undefined, scene.database, true, onerror);
  14331. return texture;
  14332. };
  14333. ;
  14334. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14335. if (compression === void 0) { compression = null; }
  14336. var internalFormat = this._getInternalFormat(format);
  14337. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14338. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14339. if (!this._doNotHandleContextLost) {
  14340. texture._bufferView = data;
  14341. texture.format = format;
  14342. texture.invertY = invertY;
  14343. texture._compression = compression;
  14344. }
  14345. if (texture.width % 4 !== 0) {
  14346. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14347. }
  14348. if (compression && data) {
  14349. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14350. }
  14351. else {
  14352. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14353. }
  14354. if (texture.generateMipMaps) {
  14355. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14356. }
  14357. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14358. // this.resetTextureCache();
  14359. texture.isReady = true;
  14360. };
  14361. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14362. if (compression === void 0) { compression = null; }
  14363. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14364. texture.baseWidth = width;
  14365. texture.baseHeight = height;
  14366. texture.baseDepth = depth;
  14367. texture.width = width;
  14368. texture.height = height;
  14369. texture.depth = depth;
  14370. texture.format = format;
  14371. texture.generateMipMaps = generateMipMaps;
  14372. texture.samplingMode = samplingMode;
  14373. texture.is3D = true;
  14374. if (!this._doNotHandleContextLost) {
  14375. texture._bufferView = data;
  14376. }
  14377. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14378. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14379. // Filters
  14380. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14381. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14382. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14383. if (generateMipMaps) {
  14384. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14385. }
  14386. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14387. this._internalTexturesCache.push(texture);
  14388. return texture;
  14389. };
  14390. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14391. var gl = this._gl;
  14392. if (!gl) {
  14393. return;
  14394. }
  14395. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14396. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14397. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14398. if (!noMipmap && !isCompressed) {
  14399. gl.generateMipmap(gl.TEXTURE_2D);
  14400. }
  14401. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14402. // this.resetTextureCache();
  14403. if (scene) {
  14404. scene._removePendingData(texture);
  14405. }
  14406. texture.onLoadedObservable.notifyObservers(texture);
  14407. texture.onLoadedObservable.clear();
  14408. };
  14409. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14410. var _this = this;
  14411. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14412. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14413. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14414. var gl = this._gl;
  14415. if (!gl) {
  14416. return;
  14417. }
  14418. if (!texture._webGLTexture) {
  14419. // this.resetTextureCache();
  14420. if (scene) {
  14421. scene._removePendingData(texture);
  14422. }
  14423. return;
  14424. }
  14425. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14426. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14427. texture.baseWidth = width;
  14428. texture.baseHeight = height;
  14429. texture.width = potWidth;
  14430. texture.height = potHeight;
  14431. texture.isReady = true;
  14432. if (processFunction(potWidth, potHeight, function () {
  14433. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14434. })) {
  14435. // Returning as texture needs extra async steps
  14436. return;
  14437. }
  14438. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14439. };
  14440. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14441. // Create new RGBA data container.
  14442. var rgbaData;
  14443. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14444. rgbaData = new Float32Array(width * height * 4);
  14445. }
  14446. else {
  14447. rgbaData = new Uint32Array(width * height * 4);
  14448. }
  14449. // Convert each pixel.
  14450. for (var x = 0; x < width; x++) {
  14451. for (var y = 0; y < height; y++) {
  14452. var index = (y * width + x) * 3;
  14453. var newIndex = (y * width + x) * 4;
  14454. // Map Old Value to new value.
  14455. rgbaData[newIndex + 0] = rgbData[index + 0];
  14456. rgbaData[newIndex + 1] = rgbData[index + 1];
  14457. rgbaData[newIndex + 2] = rgbData[index + 2];
  14458. // Add fully opaque alpha channel.
  14459. rgbaData[newIndex + 3] = 1;
  14460. }
  14461. }
  14462. return rgbaData;
  14463. };
  14464. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14465. var gl = this._gl;
  14466. if (texture._framebuffer) {
  14467. gl.deleteFramebuffer(texture._framebuffer);
  14468. texture._framebuffer = null;
  14469. }
  14470. if (texture._depthStencilBuffer) {
  14471. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14472. texture._depthStencilBuffer = null;
  14473. }
  14474. if (texture._MSAAFramebuffer) {
  14475. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14476. texture._MSAAFramebuffer = null;
  14477. }
  14478. if (texture._MSAARenderBuffer) {
  14479. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14480. texture._MSAARenderBuffer = null;
  14481. }
  14482. };
  14483. Engine.prototype._releaseTexture = function (texture) {
  14484. var gl = this._gl;
  14485. this._releaseFramebufferObjects(texture);
  14486. gl.deleteTexture(texture._webGLTexture);
  14487. // Unbind channels
  14488. this.unbindAllTextures();
  14489. var index = this._internalTexturesCache.indexOf(texture);
  14490. if (index !== -1) {
  14491. this._internalTexturesCache.splice(index, 1);
  14492. }
  14493. // Integrated fixed lod samplers.
  14494. if (texture._lodTextureHigh) {
  14495. texture._lodTextureHigh.dispose();
  14496. }
  14497. if (texture._lodTextureMid) {
  14498. texture._lodTextureMid.dispose();
  14499. }
  14500. if (texture._lodTextureLow) {
  14501. texture._lodTextureLow.dispose();
  14502. }
  14503. // Set output texture of post process to null if the texture has been released/disposed
  14504. this.scenes.forEach(function (scene) {
  14505. scene.postProcesses.forEach(function (postProcess) {
  14506. if (postProcess._outputTexture == texture) {
  14507. postProcess._outputTexture = null;
  14508. }
  14509. });
  14510. scene.cameras.forEach(function (camera) {
  14511. camera._postProcesses.forEach(function (postProcess) {
  14512. if (postProcess) {
  14513. if (postProcess._outputTexture == texture) {
  14514. postProcess._outputTexture = null;
  14515. }
  14516. }
  14517. });
  14518. });
  14519. });
  14520. };
  14521. Engine.prototype.setProgram = function (program) {
  14522. if (this._currentProgram !== program) {
  14523. this._gl.useProgram(program);
  14524. this._currentProgram = program;
  14525. }
  14526. };
  14527. Engine.prototype.bindSamplers = function (effect) {
  14528. this.setProgram(effect.getProgram());
  14529. var samplers = effect.getSamplers();
  14530. for (var index = 0; index < samplers.length; index++) {
  14531. var uniform = effect.getUniform(samplers[index]);
  14532. if (uniform) {
  14533. this._boundUniforms[index] = uniform;
  14534. }
  14535. }
  14536. this._currentEffect = null;
  14537. };
  14538. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14539. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14540. return;
  14541. }
  14542. // Remove
  14543. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14544. // Bind last to it
  14545. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14546. // Bind to dummy
  14547. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14548. };
  14549. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14550. if (!internalTexture) {
  14551. return -1;
  14552. }
  14553. internalTexture._initialSlot = channel;
  14554. if (this.disableTextureBindingOptimization) {
  14555. if (channel !== internalTexture._designatedSlot) {
  14556. this._textureCollisions.addCount(1, false);
  14557. }
  14558. }
  14559. else {
  14560. if (channel !== internalTexture._designatedSlot) {
  14561. if (internalTexture._designatedSlot > -1) {
  14562. return internalTexture._designatedSlot;
  14563. }
  14564. else {
  14565. // No slot for this texture, let's pick a new one (if we find a free slot)
  14566. if (this._nextFreeTextureSlots.length) {
  14567. return this._nextFreeTextureSlots[0];
  14568. }
  14569. // We need to recycle the oldest bound texture, sorry.
  14570. this._textureCollisions.addCount(1, false);
  14571. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14572. }
  14573. }
  14574. }
  14575. return channel;
  14576. };
  14577. Engine.prototype._linkTrackers = function (previous, next) {
  14578. previous.next = next;
  14579. next.previous = previous;
  14580. };
  14581. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14582. var currentSlot = internalTexture._designatedSlot;
  14583. if (currentSlot === -1) {
  14584. return -1;
  14585. }
  14586. internalTexture._designatedSlot = -1;
  14587. if (this.disableTextureBindingOptimization) {
  14588. return -1;
  14589. }
  14590. // Remove from bound list
  14591. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14592. // Free the slot
  14593. this._boundTexturesCache[currentSlot] = null;
  14594. this._nextFreeTextureSlots.push(currentSlot);
  14595. return currentSlot;
  14596. };
  14597. Engine.prototype._activateCurrentTexture = function () {
  14598. if (this._currentTextureChannel !== this._activeChannel) {
  14599. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14600. this._currentTextureChannel = this._activeChannel;
  14601. }
  14602. };
  14603. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14604. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14605. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14606. this._activeChannel = texture._designatedSlot;
  14607. }
  14608. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14609. var isTextureForRendering = texture && texture._initialSlot > -1;
  14610. if (currentTextureBound !== texture) {
  14611. if (currentTextureBound) {
  14612. this._removeDesignatedSlot(currentTextureBound);
  14613. }
  14614. this._activateCurrentTexture();
  14615. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14616. this._boundTexturesCache[this._activeChannel] = texture;
  14617. if (texture) {
  14618. if (!this.disableTextureBindingOptimization) {
  14619. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14620. if (slotIndex > -1) {
  14621. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14622. }
  14623. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14624. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14625. }
  14626. texture._designatedSlot = this._activeChannel;
  14627. }
  14628. }
  14629. else if (forTextureDataUpdate) {
  14630. this._activateCurrentTexture();
  14631. }
  14632. if (isTextureForRendering && !forTextureDataUpdate) {
  14633. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14634. }
  14635. };
  14636. Engine.prototype._bindTexture = function (channel, texture) {
  14637. if (channel < 0) {
  14638. return;
  14639. }
  14640. if (texture) {
  14641. channel = this._getCorrectTextureChannel(channel, texture);
  14642. }
  14643. this._activeChannel = channel;
  14644. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14645. };
  14646. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14647. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14648. };
  14649. /**
  14650. * Binds the output of the passed in post process to the texture channel specified
  14651. * @param channel The channel the texture should be bound to
  14652. * @param postProcess The post process which's output should be bound
  14653. */
  14654. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14655. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14656. };
  14657. Engine.prototype.unbindAllTextures = function () {
  14658. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14659. this._activeChannel = channel;
  14660. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14661. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14662. if (this.webGLVersion > 1) {
  14663. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14664. }
  14665. }
  14666. };
  14667. /**
  14668. * Sets a texture to the according uniform.
  14669. * @param channel The texture channel
  14670. * @param uniform The uniform to set
  14671. * @param texture The texture to apply
  14672. */
  14673. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14674. if (channel < 0) {
  14675. return;
  14676. }
  14677. if (uniform) {
  14678. this._boundUniforms[channel] = uniform;
  14679. }
  14680. this._setTexture(channel, texture);
  14681. };
  14682. /**
  14683. * Sets a depth stencil texture from a render target to the according uniform.
  14684. * @param channel The texture channel
  14685. * @param uniform The uniform to set
  14686. * @param texture The render target texture containing the depth stencil texture to apply
  14687. */
  14688. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14689. if (channel < 0) {
  14690. return;
  14691. }
  14692. if (uniform) {
  14693. this._boundUniforms[channel] = uniform;
  14694. }
  14695. if (!texture || !texture.depthStencilTexture) {
  14696. this._setTexture(channel, null);
  14697. }
  14698. else {
  14699. this._setTexture(channel, texture, false, true);
  14700. }
  14701. };
  14702. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14703. var uniform = this._boundUniforms[sourceSlot];
  14704. if (uniform._currentState === destination) {
  14705. return;
  14706. }
  14707. this._gl.uniform1i(uniform, destination);
  14708. uniform._currentState = destination;
  14709. };
  14710. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14711. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14712. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14713. // Not ready?
  14714. if (!texture) {
  14715. if (this._boundTexturesCache[channel] != null) {
  14716. this._activeChannel = channel;
  14717. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14718. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14719. if (this.webGLVersion > 1) {
  14720. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14721. }
  14722. }
  14723. return false;
  14724. }
  14725. // Video
  14726. if (texture.video) {
  14727. this._activeChannel = channel;
  14728. texture.update();
  14729. }
  14730. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14731. texture.delayLoad();
  14732. return false;
  14733. }
  14734. var internalTexture;
  14735. if (depthStencilTexture) {
  14736. internalTexture = texture.depthStencilTexture;
  14737. }
  14738. else if (texture.isReady()) {
  14739. internalTexture = texture.getInternalTexture();
  14740. }
  14741. else if (texture.isCube) {
  14742. internalTexture = this.emptyCubeTexture;
  14743. }
  14744. else if (texture.is3D) {
  14745. internalTexture = this.emptyTexture3D;
  14746. }
  14747. else {
  14748. internalTexture = this.emptyTexture;
  14749. }
  14750. if (!isPartOfTextureArray) {
  14751. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14752. }
  14753. if (this._boundTexturesCache[channel] === internalTexture) {
  14754. this._moveBoundTextureOnTop(internalTexture);
  14755. if (!isPartOfTextureArray) {
  14756. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14757. }
  14758. return false;
  14759. }
  14760. this._activeChannel = channel;
  14761. if (internalTexture && internalTexture.is3D) {
  14762. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14763. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14764. internalTexture._cachedWrapU = texture.wrapU;
  14765. switch (texture.wrapU) {
  14766. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14767. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14768. break;
  14769. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14770. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14771. break;
  14772. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14773. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14774. break;
  14775. }
  14776. }
  14777. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14778. internalTexture._cachedWrapV = texture.wrapV;
  14779. switch (texture.wrapV) {
  14780. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14781. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14782. break;
  14783. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14784. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14785. break;
  14786. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14787. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14788. break;
  14789. }
  14790. }
  14791. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14792. internalTexture._cachedWrapR = texture.wrapR;
  14793. switch (texture.wrapR) {
  14794. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14795. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14796. break;
  14797. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14798. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14799. break;
  14800. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14801. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14802. break;
  14803. }
  14804. }
  14805. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14806. }
  14807. else if (internalTexture && internalTexture.isCube) {
  14808. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14809. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14810. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14811. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14812. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14813. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14814. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14815. }
  14816. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14817. }
  14818. else {
  14819. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14820. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14821. internalTexture._cachedWrapU = texture.wrapU;
  14822. switch (texture.wrapU) {
  14823. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14824. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14825. break;
  14826. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14827. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14828. break;
  14829. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14830. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14831. break;
  14832. }
  14833. }
  14834. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14835. internalTexture._cachedWrapV = texture.wrapV;
  14836. switch (texture.wrapV) {
  14837. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14838. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14839. break;
  14840. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14841. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14842. break;
  14843. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14844. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14845. break;
  14846. }
  14847. }
  14848. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14849. }
  14850. return true;
  14851. };
  14852. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14853. if (channel < 0 || !uniform) {
  14854. return;
  14855. }
  14856. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14857. this._textureUnits = new Int32Array(textures.length);
  14858. }
  14859. for (var i = 0; i < textures.length; i++) {
  14860. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14861. }
  14862. this._gl.uniform1iv(uniform, this._textureUnits);
  14863. for (var index = 0; index < textures.length; index++) {
  14864. this._setTexture(this._textureUnits[index], textures[index], true);
  14865. }
  14866. };
  14867. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14868. var internalTexture = texture.getInternalTexture();
  14869. if (!internalTexture) {
  14870. return;
  14871. }
  14872. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14873. var value = texture.anisotropicFilteringLevel;
  14874. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14875. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14876. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14877. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14878. }
  14879. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14880. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14881. internalTexture._cachedAnisotropicFilteringLevel = value;
  14882. }
  14883. };
  14884. Engine.prototype.readPixels = function (x, y, width, height) {
  14885. var data = new Uint8Array(height * width * 4);
  14886. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14887. return data;
  14888. };
  14889. /**
  14890. * Add an externaly attached data from its key.
  14891. * This method call will fail and return false, if such key already exists.
  14892. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14893. * @param key the unique key that identifies the data
  14894. * @param data the data object to associate to the key for this Engine instance
  14895. * @return true if no such key were already present and the data was added successfully, false otherwise
  14896. */
  14897. Engine.prototype.addExternalData = function (key, data) {
  14898. if (!this._externalData) {
  14899. this._externalData = new BABYLON.StringDictionary();
  14900. }
  14901. return this._externalData.add(key, data);
  14902. };
  14903. /**
  14904. * Get an externaly attached data from its key
  14905. * @param key the unique key that identifies the data
  14906. * @return the associated data, if present (can be null), or undefined if not present
  14907. */
  14908. Engine.prototype.getExternalData = function (key) {
  14909. if (!this._externalData) {
  14910. this._externalData = new BABYLON.StringDictionary();
  14911. }
  14912. return this._externalData.get(key);
  14913. };
  14914. /**
  14915. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14916. * @param key the unique key that identifies the data
  14917. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14918. * @return the associated data, can be null if the factory returned null.
  14919. */
  14920. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14921. if (!this._externalData) {
  14922. this._externalData = new BABYLON.StringDictionary();
  14923. }
  14924. return this._externalData.getOrAddWithFactory(key, factory);
  14925. };
  14926. /**
  14927. * Remove an externaly attached data from the Engine instance
  14928. * @param key the unique key that identifies the data
  14929. * @return true if the data was successfully removed, false if it doesn't exist
  14930. */
  14931. Engine.prototype.removeExternalData = function (key) {
  14932. if (!this._externalData) {
  14933. this._externalData = new BABYLON.StringDictionary();
  14934. }
  14935. return this._externalData.remove(key);
  14936. };
  14937. Engine.prototype.unbindAllAttributes = function () {
  14938. if (this._mustWipeVertexAttributes) {
  14939. this._mustWipeVertexAttributes = false;
  14940. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14941. this._gl.disableVertexAttribArray(i);
  14942. this._vertexAttribArraysEnabled[i] = false;
  14943. this._currentBufferPointers[i].active = false;
  14944. }
  14945. return;
  14946. }
  14947. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14948. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14949. continue;
  14950. }
  14951. this._gl.disableVertexAttribArray(i);
  14952. this._vertexAttribArraysEnabled[i] = false;
  14953. this._currentBufferPointers[i].active = false;
  14954. }
  14955. };
  14956. Engine.prototype.releaseEffects = function () {
  14957. for (var name in this._compiledEffects) {
  14958. this._deleteProgram(this._compiledEffects[name]._program);
  14959. }
  14960. this._compiledEffects = {};
  14961. };
  14962. // Dispose
  14963. Engine.prototype.dispose = function () {
  14964. this.hideLoadingUI();
  14965. this.stopRenderLoop();
  14966. // Release postProcesses
  14967. while (this.postProcesses.length) {
  14968. this.postProcesses[0].dispose();
  14969. }
  14970. // Empty texture
  14971. if (this._emptyTexture) {
  14972. this._releaseTexture(this._emptyTexture);
  14973. this._emptyTexture = null;
  14974. }
  14975. if (this._emptyCubeTexture) {
  14976. this._releaseTexture(this._emptyCubeTexture);
  14977. this._emptyCubeTexture = null;
  14978. }
  14979. // Rescale PP
  14980. if (this._rescalePostProcess) {
  14981. this._rescalePostProcess.dispose();
  14982. }
  14983. // Release scenes
  14984. while (this.scenes.length) {
  14985. this.scenes[0].dispose();
  14986. }
  14987. // Release audio engine
  14988. if (Engine.audioEngine) {
  14989. Engine.audioEngine.dispose();
  14990. }
  14991. // Release effects
  14992. this.releaseEffects();
  14993. // Unbind
  14994. this.unbindAllAttributes();
  14995. this._boundUniforms = [];
  14996. if (this._dummyFramebuffer) {
  14997. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14998. }
  14999. //WebVR
  15000. this.disableVR();
  15001. // Events
  15002. if (BABYLON.Tools.IsWindowObjectExist()) {
  15003. window.removeEventListener("blur", this._onBlur);
  15004. window.removeEventListener("focus", this._onFocus);
  15005. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15006. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15007. if (this._renderingCanvas) {
  15008. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15009. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15010. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15011. if (!this._doNotHandleContextLost) {
  15012. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15013. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15014. }
  15015. }
  15016. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15017. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15018. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15019. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15020. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15021. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15022. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15023. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15024. if (this._onVrDisplayConnect) {
  15025. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15026. if (this._onVrDisplayDisconnect) {
  15027. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15028. }
  15029. if (this._onVrDisplayPresentChange) {
  15030. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15031. }
  15032. this._onVrDisplayConnect = null;
  15033. this._onVrDisplayDisconnect = null;
  15034. }
  15035. }
  15036. // Remove from Instances
  15037. var index = Engine.Instances.indexOf(this);
  15038. if (index >= 0) {
  15039. Engine.Instances.splice(index, 1);
  15040. }
  15041. this._workingCanvas = null;
  15042. this._workingContext = null;
  15043. this._currentBufferPointers = [];
  15044. this._renderingCanvas = null;
  15045. this._currentProgram = null;
  15046. this._bindedRenderFunction = null;
  15047. this.onResizeObservable.clear();
  15048. this.onCanvasBlurObservable.clear();
  15049. this.onCanvasFocusObservable.clear();
  15050. this.onCanvasPointerOutObservable.clear();
  15051. this.onBeginFrameObservable.clear();
  15052. this.onEndFrameObservable.clear();
  15053. BABYLON.Effect.ResetCache();
  15054. // Abort active requests
  15055. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15056. var request = _a[_i];
  15057. request.abort();
  15058. }
  15059. };
  15060. // Loading screen
  15061. Engine.prototype.displayLoadingUI = function () {
  15062. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15063. return;
  15064. }
  15065. var loadingScreen = this.loadingScreen;
  15066. if (loadingScreen) {
  15067. loadingScreen.displayLoadingUI();
  15068. }
  15069. };
  15070. Engine.prototype.hideLoadingUI = function () {
  15071. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15072. return;
  15073. }
  15074. var loadingScreen = this.loadingScreen;
  15075. if (loadingScreen) {
  15076. loadingScreen.hideLoadingUI();
  15077. }
  15078. };
  15079. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15080. get: function () {
  15081. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15082. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15083. return this._loadingScreen;
  15084. },
  15085. set: function (loadingScreen) {
  15086. this._loadingScreen = loadingScreen;
  15087. },
  15088. enumerable: true,
  15089. configurable: true
  15090. });
  15091. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15092. set: function (text) {
  15093. this.loadingScreen.loadingUIText = text;
  15094. },
  15095. enumerable: true,
  15096. configurable: true
  15097. });
  15098. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15099. set: function (color) {
  15100. this.loadingScreen.loadingUIBackgroundColor = color;
  15101. },
  15102. enumerable: true,
  15103. configurable: true
  15104. });
  15105. Engine.prototype.attachContextLostEvent = function (callback) {
  15106. if (this._renderingCanvas) {
  15107. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15108. }
  15109. };
  15110. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15111. if (this._renderingCanvas) {
  15112. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15113. }
  15114. };
  15115. Engine.prototype.getVertexShaderSource = function (program) {
  15116. var shaders = this._gl.getAttachedShaders(program);
  15117. if (!shaders) {
  15118. return null;
  15119. }
  15120. return this._gl.getShaderSource(shaders[0]);
  15121. };
  15122. Engine.prototype.getFragmentShaderSource = function (program) {
  15123. var shaders = this._gl.getAttachedShaders(program);
  15124. if (!shaders) {
  15125. return null;
  15126. }
  15127. return this._gl.getShaderSource(shaders[1]);
  15128. };
  15129. Engine.prototype.getError = function () {
  15130. return this._gl.getError();
  15131. };
  15132. // FPS
  15133. Engine.prototype.getFps = function () {
  15134. return this._fps;
  15135. };
  15136. Engine.prototype.getDeltaTime = function () {
  15137. return this._deltaTime;
  15138. };
  15139. Engine.prototype._measureFps = function () {
  15140. this._performanceMonitor.sampleFrame();
  15141. this._fps = this._performanceMonitor.averageFPS;
  15142. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15143. };
  15144. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15145. if (faceIndex === void 0) { faceIndex = -1; }
  15146. var gl = this._gl;
  15147. if (!this._dummyFramebuffer) {
  15148. var dummy = gl.createFramebuffer();
  15149. if (!dummy) {
  15150. throw new Error("Unable to create dummy framebuffer");
  15151. }
  15152. this._dummyFramebuffer = dummy;
  15153. }
  15154. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15155. if (faceIndex > -1) {
  15156. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15157. }
  15158. else {
  15159. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15160. }
  15161. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15162. var buffer;
  15163. switch (readType) {
  15164. case gl.UNSIGNED_BYTE:
  15165. buffer = new Uint8Array(4 * width * height);
  15166. readType = gl.UNSIGNED_BYTE;
  15167. break;
  15168. default:
  15169. buffer = new Float32Array(4 * width * height);
  15170. readType = gl.FLOAT;
  15171. break;
  15172. }
  15173. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15174. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15175. return buffer;
  15176. };
  15177. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15178. if (this._webGLVersion > 1) {
  15179. return this._caps.colorBufferFloat;
  15180. }
  15181. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15182. };
  15183. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15184. if (this._webGLVersion > 1) {
  15185. return this._caps.colorBufferFloat;
  15186. }
  15187. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15188. };
  15189. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15190. Engine.prototype._canRenderToFramebuffer = function (type) {
  15191. var gl = this._gl;
  15192. //clear existing errors
  15193. while (gl.getError() !== gl.NO_ERROR) { }
  15194. var successful = true;
  15195. var texture = gl.createTexture();
  15196. gl.bindTexture(gl.TEXTURE_2D, texture);
  15197. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15198. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15200. var fb = gl.createFramebuffer();
  15201. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15202. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15203. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15204. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15205. successful = successful && (gl.getError() === gl.NO_ERROR);
  15206. //try render by clearing frame buffer's color buffer
  15207. if (successful) {
  15208. gl.clear(gl.COLOR_BUFFER_BIT);
  15209. successful = successful && (gl.getError() === gl.NO_ERROR);
  15210. }
  15211. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15212. if (successful) {
  15213. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15214. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15215. var readFormat = gl.RGBA;
  15216. var readType = gl.UNSIGNED_BYTE;
  15217. var buffer = new Uint8Array(4);
  15218. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15219. successful = successful && (gl.getError() === gl.NO_ERROR);
  15220. }
  15221. //clean up
  15222. gl.deleteTexture(texture);
  15223. gl.deleteFramebuffer(fb);
  15224. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15225. //clear accumulated errors
  15226. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15227. return successful;
  15228. };
  15229. Engine.prototype._getWebGLTextureType = function (type) {
  15230. if (type === Engine.TEXTURETYPE_FLOAT) {
  15231. return this._gl.FLOAT;
  15232. }
  15233. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15234. // Add Half Float Constant.
  15235. return this._gl.HALF_FLOAT_OES;
  15236. }
  15237. return this._gl.UNSIGNED_BYTE;
  15238. };
  15239. ;
  15240. Engine.prototype._getInternalFormat = function (format) {
  15241. var internalFormat = this._gl.RGBA;
  15242. switch (format) {
  15243. case Engine.TEXTUREFORMAT_ALPHA:
  15244. internalFormat = this._gl.ALPHA;
  15245. break;
  15246. case Engine.TEXTUREFORMAT_LUMINANCE:
  15247. internalFormat = this._gl.LUMINANCE;
  15248. break;
  15249. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15250. internalFormat = this._gl.LUMINANCE_ALPHA;
  15251. break;
  15252. case Engine.TEXTUREFORMAT_RGB:
  15253. case Engine.TEXTUREFORMAT_RGB32F:
  15254. internalFormat = this._gl.RGB;
  15255. break;
  15256. case Engine.TEXTUREFORMAT_RGBA:
  15257. case Engine.TEXTUREFORMAT_RGBA32F:
  15258. internalFormat = this._gl.RGBA;
  15259. break;
  15260. case Engine.TEXTUREFORMAT_R32F:
  15261. internalFormat = this._gl.RED;
  15262. break;
  15263. case Engine.TEXTUREFORMAT_RG32F:
  15264. internalFormat = this._gl.RG;
  15265. break;
  15266. }
  15267. return internalFormat;
  15268. };
  15269. /** @ignore */
  15270. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15271. if (this._webGLVersion === 1) {
  15272. if (format) {
  15273. switch (format) {
  15274. case Engine.TEXTUREFORMAT_LUMINANCE:
  15275. return this._gl.LUMINANCE;
  15276. }
  15277. }
  15278. return this._gl.RGBA;
  15279. }
  15280. if (type === Engine.TEXTURETYPE_FLOAT) {
  15281. if (format) {
  15282. switch (format) {
  15283. case Engine.TEXTUREFORMAT_R32F:
  15284. return this._gl.R32F;
  15285. case Engine.TEXTUREFORMAT_RG32F:
  15286. return this._gl.RG32F;
  15287. case Engine.TEXTUREFORMAT_RGB32F:
  15288. return this._gl.RGB32F;
  15289. }
  15290. }
  15291. return this._gl.RGBA32F;
  15292. }
  15293. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15294. return this._gl.RGBA16F;
  15295. }
  15296. if (format) {
  15297. switch (format) {
  15298. case Engine.TEXTUREFORMAT_LUMINANCE:
  15299. return this._gl.LUMINANCE;
  15300. }
  15301. }
  15302. return this._gl.RGBA;
  15303. };
  15304. ;
  15305. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15306. if (type === Engine.TEXTURETYPE_FLOAT) {
  15307. return this._gl.RGBA32F;
  15308. }
  15309. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15310. return this._gl.RGBA16F;
  15311. }
  15312. return this._gl.RGBA8;
  15313. };
  15314. ;
  15315. Engine.prototype.createQuery = function () {
  15316. return this._gl.createQuery();
  15317. };
  15318. Engine.prototype.deleteQuery = function (query) {
  15319. this._gl.deleteQuery(query);
  15320. return this;
  15321. };
  15322. Engine.prototype.isQueryResultAvailable = function (query) {
  15323. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15324. };
  15325. Engine.prototype.getQueryResult = function (query) {
  15326. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15327. };
  15328. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15329. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15330. this._gl.beginQuery(glAlgorithm, query);
  15331. return this;
  15332. };
  15333. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15334. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15335. this._gl.endQuery(glAlgorithm);
  15336. return this;
  15337. };
  15338. /* Time queries */
  15339. Engine.prototype._createTimeQuery = function () {
  15340. var timerQuery = this._caps.timerQuery;
  15341. if (timerQuery.createQueryEXT) {
  15342. return timerQuery.createQueryEXT();
  15343. }
  15344. return this.createQuery();
  15345. };
  15346. Engine.prototype._deleteTimeQuery = function (query) {
  15347. var timerQuery = this._caps.timerQuery;
  15348. if (timerQuery.deleteQueryEXT) {
  15349. timerQuery.deleteQueryEXT(query);
  15350. return;
  15351. }
  15352. this.deleteQuery(query);
  15353. };
  15354. Engine.prototype._getTimeQueryResult = function (query) {
  15355. var timerQuery = this._caps.timerQuery;
  15356. if (timerQuery.getQueryObjectEXT) {
  15357. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15358. }
  15359. return this.getQueryResult(query);
  15360. };
  15361. Engine.prototype._getTimeQueryAvailability = function (query) {
  15362. var timerQuery = this._caps.timerQuery;
  15363. if (timerQuery.getQueryObjectEXT) {
  15364. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15365. }
  15366. return this.isQueryResultAvailable(query);
  15367. };
  15368. Engine.prototype.startTimeQuery = function () {
  15369. var timerQuery = this._caps.timerQuery;
  15370. if (!timerQuery) {
  15371. return null;
  15372. }
  15373. var token = new BABYLON._TimeToken();
  15374. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15375. if (this._caps.canUseTimestampForTimerQuery) {
  15376. token._startTimeQuery = this._createTimeQuery();
  15377. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15378. }
  15379. else {
  15380. if (this._currentNonTimestampToken) {
  15381. return this._currentNonTimestampToken;
  15382. }
  15383. token._timeElapsedQuery = this._createTimeQuery();
  15384. if (timerQuery.beginQueryEXT) {
  15385. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15386. }
  15387. else {
  15388. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15389. }
  15390. this._currentNonTimestampToken = token;
  15391. }
  15392. return token;
  15393. };
  15394. Engine.prototype.endTimeQuery = function (token) {
  15395. var timerQuery = this._caps.timerQuery;
  15396. if (!timerQuery || !token) {
  15397. return -1;
  15398. }
  15399. if (this._caps.canUseTimestampForTimerQuery) {
  15400. if (!token._startTimeQuery) {
  15401. return -1;
  15402. }
  15403. if (!token._endTimeQuery) {
  15404. token._endTimeQuery = this._createTimeQuery();
  15405. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15406. }
  15407. }
  15408. else if (!token._timeElapsedQueryEnded) {
  15409. if (!token._timeElapsedQuery) {
  15410. return -1;
  15411. }
  15412. if (timerQuery.endQueryEXT) {
  15413. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15414. }
  15415. else {
  15416. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15417. }
  15418. token._timeElapsedQueryEnded = true;
  15419. }
  15420. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15421. var available = false;
  15422. if (token._endTimeQuery) {
  15423. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15424. }
  15425. else if (token._timeElapsedQuery) {
  15426. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15427. }
  15428. if (available && !disjoint) {
  15429. var result = 0;
  15430. if (this._caps.canUseTimestampForTimerQuery) {
  15431. if (!token._startTimeQuery || !token._endTimeQuery) {
  15432. return -1;
  15433. }
  15434. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15435. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15436. result = timeEnd - timeStart;
  15437. this._deleteTimeQuery(token._startTimeQuery);
  15438. this._deleteTimeQuery(token._endTimeQuery);
  15439. token._startTimeQuery = null;
  15440. token._endTimeQuery = null;
  15441. }
  15442. else {
  15443. if (!token._timeElapsedQuery) {
  15444. return -1;
  15445. }
  15446. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15447. this._deleteTimeQuery(token._timeElapsedQuery);
  15448. token._timeElapsedQuery = null;
  15449. token._timeElapsedQueryEnded = false;
  15450. this._currentNonTimestampToken = null;
  15451. }
  15452. return result;
  15453. }
  15454. return -1;
  15455. };
  15456. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15457. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15458. };
  15459. // Transform feedback
  15460. Engine.prototype.createTransformFeedback = function () {
  15461. return this._gl.createTransformFeedback();
  15462. };
  15463. Engine.prototype.deleteTransformFeedback = function (value) {
  15464. this._gl.deleteTransformFeedback(value);
  15465. };
  15466. Engine.prototype.bindTransformFeedback = function (value) {
  15467. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15468. };
  15469. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15470. if (usePoints === void 0) { usePoints = true; }
  15471. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15472. };
  15473. Engine.prototype.endTransformFeedback = function () {
  15474. this._gl.endTransformFeedback();
  15475. };
  15476. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15477. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15478. };
  15479. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15480. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15481. };
  15482. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15483. var _this = this;
  15484. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15485. this._activeRequests.push(request);
  15486. request.onCompleteObservable.add(function (request) {
  15487. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15488. });
  15489. return request;
  15490. };
  15491. /** @ignore */
  15492. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15493. var _this = this;
  15494. return new Promise(function (resolve, reject) {
  15495. _this._loadFile(url, function (data) {
  15496. resolve(data);
  15497. }, undefined, database, useArrayBuffer, function (request, exception) {
  15498. reject(exception);
  15499. });
  15500. });
  15501. };
  15502. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15503. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15504. var onload = function (data) {
  15505. loadedFiles[index] = data;
  15506. loadedFiles._internalCount++;
  15507. if (loadedFiles._internalCount === 6) {
  15508. onfinish(loadedFiles);
  15509. }
  15510. };
  15511. var onerror = function (request, exception) {
  15512. if (onErrorCallBack && request) {
  15513. onErrorCallBack(request.status + " " + request.statusText, exception);
  15514. }
  15515. };
  15516. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15517. };
  15518. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15519. if (onError === void 0) { onError = null; }
  15520. var loadedFiles = [];
  15521. loadedFiles._internalCount = 0;
  15522. for (var index = 0; index < 6; index++) {
  15523. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15524. }
  15525. };
  15526. // Statics
  15527. Engine.isSupported = function () {
  15528. try {
  15529. var tempcanvas = document.createElement("canvas");
  15530. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15531. return gl != null && !!window.WebGLRenderingContext;
  15532. }
  15533. catch (e) {
  15534. return false;
  15535. }
  15536. };
  15537. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15538. Engine.ExceptionList = [
  15539. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15540. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15541. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15542. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15543. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15544. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15545. ];
  15546. Engine.Instances = new Array();
  15547. // Const statics
  15548. Engine._ALPHA_DISABLE = 0;
  15549. Engine._ALPHA_ADD = 1;
  15550. Engine._ALPHA_COMBINE = 2;
  15551. Engine._ALPHA_SUBTRACT = 3;
  15552. Engine._ALPHA_MULTIPLY = 4;
  15553. Engine._ALPHA_MAXIMIZED = 5;
  15554. Engine._ALPHA_ONEONE = 6;
  15555. Engine._ALPHA_PREMULTIPLIED = 7;
  15556. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15557. Engine._ALPHA_INTERPOLATE = 9;
  15558. Engine._ALPHA_SCREENMODE = 10;
  15559. Engine._DELAYLOADSTATE_NONE = 0;
  15560. Engine._DELAYLOADSTATE_LOADED = 1;
  15561. Engine._DELAYLOADSTATE_LOADING = 2;
  15562. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15563. Engine._TEXTUREFORMAT_ALPHA = 0;
  15564. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15565. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15566. Engine._TEXTUREFORMAT_RGB = 4;
  15567. Engine._TEXTUREFORMAT_RGBA = 5;
  15568. Engine._TEXTUREFORMAT_R32F = 6;
  15569. Engine._TEXTUREFORMAT_RG32F = 7;
  15570. Engine._TEXTUREFORMAT_RGB32F = 8;
  15571. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15572. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15573. Engine._TEXTURETYPE_FLOAT = 1;
  15574. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15575. // Depht or Stencil test Constants.
  15576. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15577. 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.
  15578. 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.
  15579. 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.
  15580. 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.
  15581. 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.
  15582. 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.
  15583. 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.
  15584. // Stencil Actions Constants.
  15585. Engine._KEEP = 0x1E00;
  15586. Engine._REPLACE = 0x1E01;
  15587. Engine._INCR = 0x1E02;
  15588. Engine._DECR = 0x1E03;
  15589. Engine._INVERT = 0x150A;
  15590. Engine._INCR_WRAP = 0x8507;
  15591. Engine._DECR_WRAP = 0x8508;
  15592. // Texture rescaling mode
  15593. Engine._SCALEMODE_FLOOR = 1;
  15594. Engine._SCALEMODE_NEAREST = 2;
  15595. Engine._SCALEMODE_CEILING = 3;
  15596. // Updatable statics so stick with vars here
  15597. Engine.CollisionsEpsilon = 0.001;
  15598. Engine.CodeRepository = "src/";
  15599. Engine.ShadersRepository = "src/Shaders/";
  15600. return Engine;
  15601. }());
  15602. BABYLON.Engine = Engine;
  15603. })(BABYLON || (BABYLON = {}));
  15604. //# sourceMappingURL=babylon.engine.js.map
  15605. "use strict";
  15606. var BABYLON;
  15607. (function (BABYLON) {
  15608. /**
  15609. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15610. */
  15611. var Node = /** @class */ (function () {
  15612. /**
  15613. * Creates a new Node
  15614. * @param {string} name - the name and id to be given to this node
  15615. * @param {BABYLON.Scene} the scene this node will be added to
  15616. */
  15617. function Node(name, scene) {
  15618. if (scene === void 0) { scene = null; }
  15619. /**
  15620. * Gets or sets a string used to store user defined state for the node
  15621. */
  15622. this.state = "";
  15623. /**
  15624. * Gets or sets an object used to store user defined information for the node
  15625. */
  15626. this.metadata = null;
  15627. /**
  15628. * Gets or sets a boolean used to define if the node must be serialized
  15629. */
  15630. this.doNotSerialize = false;
  15631. /** @ignore */
  15632. this._isDisposed = false;
  15633. /**
  15634. * Gets a list of {BABYLON.Animation} associated with the node
  15635. */
  15636. this.animations = new Array();
  15637. this._ranges = {};
  15638. this._isEnabled = true;
  15639. this._isReady = true;
  15640. /** @ignore */
  15641. this._currentRenderId = -1;
  15642. this._parentRenderId = -1;
  15643. this._childRenderId = -1;
  15644. this._animationPropertiesOverride = null;
  15645. /**
  15646. * An event triggered when the mesh is disposed
  15647. * @type {BABYLON.Observable}
  15648. */
  15649. this.onDisposeObservable = new BABYLON.Observable();
  15650. // Behaviors
  15651. this._behaviors = new Array();
  15652. this.name = name;
  15653. this.id = name;
  15654. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15655. this.uniqueId = this._scene.getUniqueId();
  15656. this._initCache();
  15657. }
  15658. /**
  15659. * Gets a boolean indicating if the node has been disposed
  15660. * @returns true if the node was disposed
  15661. */
  15662. Node.prototype.isDisposed = function () {
  15663. return this._isDisposed;
  15664. };
  15665. Object.defineProperty(Node.prototype, "parent", {
  15666. get: function () {
  15667. return this._parentNode;
  15668. },
  15669. /**
  15670. * Gets or sets the parent of the node
  15671. */
  15672. set: function (parent) {
  15673. if (this._parentNode === parent) {
  15674. return;
  15675. }
  15676. // Remove self from list of children of parent
  15677. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15678. var index = this._parentNode._children.indexOf(this);
  15679. if (index !== -1) {
  15680. this._parentNode._children.splice(index, 1);
  15681. }
  15682. }
  15683. // Store new parent
  15684. this._parentNode = parent;
  15685. // Add as child to new parent
  15686. if (this._parentNode) {
  15687. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15688. this._parentNode._children = new Array();
  15689. }
  15690. this._parentNode._children.push(this);
  15691. }
  15692. },
  15693. enumerable: true,
  15694. configurable: true
  15695. });
  15696. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15697. /**
  15698. * Gets or sets the animation properties override
  15699. */
  15700. get: function () {
  15701. return this._animationPropertiesOverride;
  15702. },
  15703. set: function (value) {
  15704. this._animationPropertiesOverride = value;
  15705. },
  15706. enumerable: true,
  15707. configurable: true
  15708. });
  15709. /**
  15710. * Gets a string idenfifying the name of the class
  15711. * @returns "Node" string
  15712. */
  15713. Node.prototype.getClassName = function () {
  15714. return "Node";
  15715. };
  15716. Object.defineProperty(Node.prototype, "onDispose", {
  15717. /**
  15718. * Sets a callback that will be raised when the node will be disposed
  15719. */
  15720. set: function (callback) {
  15721. if (this._onDisposeObserver) {
  15722. this.onDisposeObservable.remove(this._onDisposeObserver);
  15723. }
  15724. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15725. },
  15726. enumerable: true,
  15727. configurable: true
  15728. });
  15729. /**
  15730. * Gets the scene of the node
  15731. * @returns a {BABYLON.Scene}
  15732. */
  15733. Node.prototype.getScene = function () {
  15734. return this._scene;
  15735. };
  15736. /**
  15737. * Gets the engine of the node
  15738. * @returns a {BABYLON.Engine}
  15739. */
  15740. Node.prototype.getEngine = function () {
  15741. return this._scene.getEngine();
  15742. };
  15743. /**
  15744. * Attach a behavior to the node
  15745. * @see http://doc.babylonjs.com/features/behaviour
  15746. * @param behavior defines the behavior to attach
  15747. * @returns the current Node
  15748. */
  15749. Node.prototype.addBehavior = function (behavior) {
  15750. var _this = this;
  15751. var index = this._behaviors.indexOf(behavior);
  15752. if (index !== -1) {
  15753. return this;
  15754. }
  15755. behavior.init();
  15756. if (this._scene.isLoading) {
  15757. // We defer the attach when the scene will be loaded
  15758. var observer = this._scene.onDataLoadedObservable.add(function () {
  15759. behavior.attach(_this);
  15760. setTimeout(function () {
  15761. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15762. _this._scene.onDataLoadedObservable.remove(observer);
  15763. }, 0);
  15764. });
  15765. }
  15766. else {
  15767. behavior.attach(this);
  15768. }
  15769. this._behaviors.push(behavior);
  15770. return this;
  15771. };
  15772. /**
  15773. * Remove an attached behavior
  15774. * @see http://doc.babylonjs.com/features/behaviour
  15775. * @param behavior defines the behavior to attach
  15776. * @returns the current Node
  15777. */
  15778. Node.prototype.removeBehavior = function (behavior) {
  15779. var index = this._behaviors.indexOf(behavior);
  15780. if (index === -1) {
  15781. return this;
  15782. }
  15783. this._behaviors[index].detach();
  15784. this._behaviors.splice(index, 1);
  15785. return this;
  15786. };
  15787. Object.defineProperty(Node.prototype, "behaviors", {
  15788. /**
  15789. * Gets the list of attached behaviors
  15790. * @see http://doc.babylonjs.com/features/behaviour
  15791. */
  15792. get: function () {
  15793. return this._behaviors;
  15794. },
  15795. enumerable: true,
  15796. configurable: true
  15797. });
  15798. /**
  15799. * Gets an attached behavior by name
  15800. * @param name defines the name of the behavior to look for
  15801. * @see http://doc.babylonjs.com/features/behaviour
  15802. * @returns null if behavior was not found else the requested behavior
  15803. */
  15804. Node.prototype.getBehaviorByName = function (name) {
  15805. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15806. var behavior = _a[_i];
  15807. if (behavior.name === name) {
  15808. return behavior;
  15809. }
  15810. }
  15811. return null;
  15812. };
  15813. /**
  15814. * Returns the world matrix of the node
  15815. * @returns a matrix containing the node's world matrix
  15816. */
  15817. Node.prototype.getWorldMatrix = function () {
  15818. return BABYLON.Matrix.Identity();
  15819. };
  15820. // override it in derived class if you add new variables to the cache
  15821. // and call the parent class method
  15822. /** @ignore */
  15823. Node.prototype._initCache = function () {
  15824. this._cache = {};
  15825. this._cache.parent = undefined;
  15826. };
  15827. /** @ignore */
  15828. Node.prototype.updateCache = function (force) {
  15829. if (!force && this.isSynchronized())
  15830. return;
  15831. this._cache.parent = this.parent;
  15832. this._updateCache();
  15833. };
  15834. // override it in derived class if you add new variables to the cache
  15835. // and call the parent class method if !ignoreParentClass
  15836. /** @ignore */
  15837. Node.prototype._updateCache = function (ignoreParentClass) {
  15838. };
  15839. // override it in derived class if you add new variables to the cache
  15840. /** @ignore */
  15841. Node.prototype._isSynchronized = function () {
  15842. return true;
  15843. };
  15844. /** @ignore */
  15845. Node.prototype._markSyncedWithParent = function () {
  15846. if (this.parent) {
  15847. this._parentRenderId = this.parent._childRenderId;
  15848. }
  15849. };
  15850. /** @ignore */
  15851. Node.prototype.isSynchronizedWithParent = function () {
  15852. if (!this.parent) {
  15853. return true;
  15854. }
  15855. if (this._parentRenderId !== this.parent._childRenderId) {
  15856. return false;
  15857. }
  15858. return this.parent.isSynchronized();
  15859. };
  15860. /** @ignore */
  15861. Node.prototype.isSynchronized = function (updateCache) {
  15862. var check = this.hasNewParent();
  15863. check = check || !this.isSynchronizedWithParent();
  15864. check = check || !this._isSynchronized();
  15865. if (updateCache)
  15866. this.updateCache(true);
  15867. return !check;
  15868. };
  15869. /** @ignore */
  15870. Node.prototype.hasNewParent = function (update) {
  15871. if (this._cache.parent === this.parent)
  15872. return false;
  15873. if (update)
  15874. this._cache.parent = this.parent;
  15875. return true;
  15876. };
  15877. /**
  15878. * Is this node ready to be used/rendered
  15879. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15880. * @return true if the node is ready
  15881. */
  15882. Node.prototype.isReady = function (completeCheck) {
  15883. if (completeCheck === void 0) { completeCheck = false; }
  15884. return this._isReady;
  15885. };
  15886. /**
  15887. * Is this node enabled?
  15888. * 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
  15889. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15890. * @return whether this node (and its parent) is enabled
  15891. * @see setEnabled
  15892. */
  15893. Node.prototype.isEnabled = function (checkAncestors) {
  15894. if (checkAncestors === void 0) { checkAncestors = true; }
  15895. if (checkAncestors === false) {
  15896. return this._isEnabled;
  15897. }
  15898. if (this._isEnabled === false) {
  15899. return false;
  15900. }
  15901. if (this.parent !== undefined && this.parent !== null) {
  15902. return this.parent.isEnabled(checkAncestors);
  15903. }
  15904. return true;
  15905. };
  15906. /**
  15907. * Set the enabled state of this node
  15908. * @param value defines the new enabled state
  15909. * @see isEnabled
  15910. */
  15911. Node.prototype.setEnabled = function (value) {
  15912. this._isEnabled = value;
  15913. };
  15914. /**
  15915. * Is this node a descendant of the given node?
  15916. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15917. * @param ancestor defines the parent node to inspect
  15918. * @see parent
  15919. * @returns a boolean indicating if this node is a descendant of the given node
  15920. */
  15921. Node.prototype.isDescendantOf = function (ancestor) {
  15922. if (this.parent) {
  15923. if (this.parent === ancestor) {
  15924. return true;
  15925. }
  15926. return this.parent.isDescendantOf(ancestor);
  15927. }
  15928. return false;
  15929. };
  15930. /** @ignore */
  15931. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15932. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15933. if (!this._children) {
  15934. return;
  15935. }
  15936. for (var index = 0; index < this._children.length; index++) {
  15937. var item = this._children[index];
  15938. if (!predicate || predicate(item)) {
  15939. results.push(item);
  15940. }
  15941. if (!directDescendantsOnly) {
  15942. item._getDescendants(results, false, predicate);
  15943. }
  15944. }
  15945. };
  15946. /**
  15947. * Will return all nodes that have this node as ascendant
  15948. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15949. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15950. * @return all children nodes of all types
  15951. */
  15952. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15953. var results = new Array();
  15954. this._getDescendants(results, directDescendantsOnly, predicate);
  15955. return results;
  15956. };
  15957. /**
  15958. * Get all child-meshes of this node
  15959. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15960. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15961. * @returns an array of {BABYLON.AbstractMesh}
  15962. */
  15963. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15964. var results = [];
  15965. this._getDescendants(results, directDescendantsOnly, function (node) {
  15966. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15967. });
  15968. return results;
  15969. };
  15970. /**
  15971. * Get all child-transformNodes of this node
  15972. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15973. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15974. * @returns an array of {BABYLON.TransformNode}
  15975. */
  15976. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15977. var results = [];
  15978. this._getDescendants(results, directDescendantsOnly, function (node) {
  15979. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15980. });
  15981. return results;
  15982. };
  15983. /**
  15984. * Get all direct children of this node
  15985. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15986. * @returns an array of {BABYLON.Node}
  15987. */
  15988. Node.prototype.getChildren = function (predicate) {
  15989. return this.getDescendants(true, predicate);
  15990. };
  15991. /** @ignore */
  15992. Node.prototype._setReady = function (state) {
  15993. if (state === this._isReady) {
  15994. return;
  15995. }
  15996. if (!state) {
  15997. this._isReady = false;
  15998. return;
  15999. }
  16000. if (this.onReady) {
  16001. this.onReady(this);
  16002. }
  16003. this._isReady = true;
  16004. };
  16005. /**
  16006. * Get an animation by name
  16007. * @param name defines the name of the animation to look for
  16008. * @returns null if not found else the requested animation
  16009. */
  16010. Node.prototype.getAnimationByName = function (name) {
  16011. for (var i = 0; i < this.animations.length; i++) {
  16012. var animation = this.animations[i];
  16013. if (animation.name === name) {
  16014. return animation;
  16015. }
  16016. }
  16017. return null;
  16018. };
  16019. /**
  16020. * Creates an animation range for this node
  16021. * @param name defines the name of the range
  16022. * @param from defines the starting key
  16023. * @param to defines the end key
  16024. */
  16025. Node.prototype.createAnimationRange = function (name, from, to) {
  16026. // check name not already in use
  16027. if (!this._ranges[name]) {
  16028. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16029. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16030. if (this.animations[i]) {
  16031. this.animations[i].createRange(name, from, to);
  16032. }
  16033. }
  16034. }
  16035. };
  16036. /**
  16037. * Delete a specific animation range
  16038. * @param name defines the name of the range to delete
  16039. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16040. */
  16041. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16042. if (deleteFrames === void 0) { deleteFrames = true; }
  16043. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16044. if (this.animations[i]) {
  16045. this.animations[i].deleteRange(name, deleteFrames);
  16046. }
  16047. }
  16048. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16049. };
  16050. /**
  16051. * Get an animation range by name
  16052. * @param name defines the name of the animation range to look for
  16053. * @returns null if not found else the requested animation range
  16054. */
  16055. Node.prototype.getAnimationRange = function (name) {
  16056. return this._ranges[name];
  16057. };
  16058. /**
  16059. * Will start the animation sequence
  16060. * @param name defines the range frames for animation sequence
  16061. * @param loop defines if the animation should loop (false by default)
  16062. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16063. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16064. * @returns the object created for this animation. If range does not exist, it will return null
  16065. */
  16066. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16067. var range = this.getAnimationRange(name);
  16068. if (!range) {
  16069. return null;
  16070. }
  16071. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16072. };
  16073. /**
  16074. * Serialize animation ranges into a JSON compatible object
  16075. * @returns serialization object
  16076. */
  16077. Node.prototype.serializeAnimationRanges = function () {
  16078. var serializationRanges = [];
  16079. for (var name in this._ranges) {
  16080. var localRange = this._ranges[name];
  16081. if (!localRange) {
  16082. continue;
  16083. }
  16084. var range = {};
  16085. range.name = name;
  16086. range.from = localRange.from;
  16087. range.to = localRange.to;
  16088. serializationRanges.push(range);
  16089. }
  16090. return serializationRanges;
  16091. };
  16092. /**
  16093. * Computes the world matrix of the node
  16094. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16095. * @returns the world matrix
  16096. */
  16097. Node.prototype.computeWorldMatrix = function (force) {
  16098. return BABYLON.Matrix.Identity();
  16099. };
  16100. /**
  16101. * Releases resources associated with this node.
  16102. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16103. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16104. */
  16105. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16106. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16107. if (!doNotRecurse) {
  16108. var nodes = this.getDescendants(true);
  16109. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16110. var node = nodes_1[_i];
  16111. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16112. }
  16113. }
  16114. else {
  16115. var transformNodes = this.getChildTransformNodes(true);
  16116. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16117. var transformNode = transformNodes_1[_a];
  16118. transformNode.parent = null;
  16119. transformNode.computeWorldMatrix(true);
  16120. }
  16121. }
  16122. this.parent = null;
  16123. // Callback
  16124. this.onDisposeObservable.notifyObservers(this);
  16125. this.onDisposeObservable.clear();
  16126. // Behaviors
  16127. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16128. var behavior = _c[_b];
  16129. behavior.detach();
  16130. }
  16131. this._behaviors = [];
  16132. this._isDisposed = true;
  16133. };
  16134. /**
  16135. * Parse animation range data from a serialization object and store them into a given node
  16136. * @param node defines where to store the animation ranges
  16137. * @param parsedNode defines the serialization object to read data from
  16138. * @param scene defines the hosting scene
  16139. */
  16140. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16141. if (parsedNode.ranges) {
  16142. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16143. var data = parsedNode.ranges[index];
  16144. node.createAnimationRange(data.name, data.from, data.to);
  16145. }
  16146. }
  16147. };
  16148. __decorate([
  16149. BABYLON.serialize()
  16150. ], Node.prototype, "name", void 0);
  16151. __decorate([
  16152. BABYLON.serialize()
  16153. ], Node.prototype, "id", void 0);
  16154. __decorate([
  16155. BABYLON.serialize()
  16156. ], Node.prototype, "uniqueId", void 0);
  16157. __decorate([
  16158. BABYLON.serialize()
  16159. ], Node.prototype, "state", void 0);
  16160. __decorate([
  16161. BABYLON.serialize()
  16162. ], Node.prototype, "metadata", void 0);
  16163. return Node;
  16164. }());
  16165. BABYLON.Node = Node;
  16166. })(BABYLON || (BABYLON = {}));
  16167. //# sourceMappingURL=babylon.node.js.map
  16168. "use strict";
  16169. var BABYLON;
  16170. (function (BABYLON) {
  16171. var BoundingSphere = /** @class */ (function () {
  16172. function BoundingSphere(minimum, maximum) {
  16173. this.minimum = minimum;
  16174. this.maximum = maximum;
  16175. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16176. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16177. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16178. this.radius = distance * 0.5;
  16179. this.centerWorld = BABYLON.Vector3.Zero();
  16180. this._update(BABYLON.Matrix.Identity());
  16181. }
  16182. // Methods
  16183. BoundingSphere.prototype._update = function (world) {
  16184. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16185. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16186. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16187. };
  16188. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16189. for (var i = 0; i < 6; i++) {
  16190. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16191. return false;
  16192. }
  16193. return true;
  16194. };
  16195. BoundingSphere.prototype.intersectsPoint = function (point) {
  16196. var x = this.centerWorld.x - point.x;
  16197. var y = this.centerWorld.y - point.y;
  16198. var z = this.centerWorld.z - point.z;
  16199. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16200. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16201. return false;
  16202. return true;
  16203. };
  16204. // Statics
  16205. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16206. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16207. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16208. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16209. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16210. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16211. return false;
  16212. return true;
  16213. };
  16214. return BoundingSphere;
  16215. }());
  16216. BABYLON.BoundingSphere = BoundingSphere;
  16217. })(BABYLON || (BABYLON = {}));
  16218. //# sourceMappingURL=babylon.boundingSphere.js.map
  16219. "use strict";
  16220. var BABYLON;
  16221. (function (BABYLON) {
  16222. var BoundingBox = /** @class */ (function () {
  16223. function BoundingBox(minimum, maximum) {
  16224. this.minimum = minimum;
  16225. this.maximum = maximum;
  16226. this.vectors = new Array();
  16227. this.vectorsWorld = new Array();
  16228. // Bounding vectors
  16229. this.vectors.push(this.minimum.clone());
  16230. this.vectors.push(this.maximum.clone());
  16231. this.vectors.push(this.minimum.clone());
  16232. this.vectors[2].x = this.maximum.x;
  16233. this.vectors.push(this.minimum.clone());
  16234. this.vectors[3].y = this.maximum.y;
  16235. this.vectors.push(this.minimum.clone());
  16236. this.vectors[4].z = this.maximum.z;
  16237. this.vectors.push(this.maximum.clone());
  16238. this.vectors[5].z = this.minimum.z;
  16239. this.vectors.push(this.maximum.clone());
  16240. this.vectors[6].x = this.minimum.x;
  16241. this.vectors.push(this.maximum.clone());
  16242. this.vectors[7].y = this.minimum.y;
  16243. // OBB
  16244. this.center = this.maximum.add(this.minimum).scale(0.5);
  16245. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16246. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16247. // World
  16248. for (var index = 0; index < this.vectors.length; index++) {
  16249. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16250. }
  16251. this.minimumWorld = BABYLON.Vector3.Zero();
  16252. this.maximumWorld = BABYLON.Vector3.Zero();
  16253. this.centerWorld = BABYLON.Vector3.Zero();
  16254. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16255. this._update(BABYLON.Matrix.Identity());
  16256. }
  16257. // Methods
  16258. BoundingBox.prototype.getWorldMatrix = function () {
  16259. return this._worldMatrix;
  16260. };
  16261. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16262. this._worldMatrix.copyFrom(matrix);
  16263. return this;
  16264. };
  16265. BoundingBox.prototype._update = function (world) {
  16266. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16267. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16268. for (var index = 0; index < this.vectors.length; index++) {
  16269. var v = this.vectorsWorld[index];
  16270. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16271. if (v.x < this.minimumWorld.x)
  16272. this.minimumWorld.x = v.x;
  16273. if (v.y < this.minimumWorld.y)
  16274. this.minimumWorld.y = v.y;
  16275. if (v.z < this.minimumWorld.z)
  16276. this.minimumWorld.z = v.z;
  16277. if (v.x > this.maximumWorld.x)
  16278. this.maximumWorld.x = v.x;
  16279. if (v.y > this.maximumWorld.y)
  16280. this.maximumWorld.y = v.y;
  16281. if (v.z > this.maximumWorld.z)
  16282. this.maximumWorld.z = v.z;
  16283. }
  16284. // Extend
  16285. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16286. this.extendSizeWorld.scaleInPlace(0.5);
  16287. // OBB
  16288. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16289. this.centerWorld.scaleInPlace(0.5);
  16290. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16291. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16292. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16293. this._worldMatrix = world;
  16294. };
  16295. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16296. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16297. };
  16298. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16299. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16300. };
  16301. BoundingBox.prototype.intersectsPoint = function (point) {
  16302. var delta = -BABYLON.Epsilon;
  16303. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16304. return false;
  16305. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16306. return false;
  16307. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16308. return false;
  16309. return true;
  16310. };
  16311. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16312. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16313. };
  16314. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16315. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16316. return false;
  16317. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16318. return false;
  16319. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16320. return false;
  16321. return true;
  16322. };
  16323. // Statics
  16324. BoundingBox.Intersects = function (box0, box1) {
  16325. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16326. return false;
  16327. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16328. return false;
  16329. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16330. return false;
  16331. return true;
  16332. };
  16333. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16334. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16335. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16336. return (num <= (sphereRadius * sphereRadius));
  16337. };
  16338. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16339. for (var p = 0; p < 6; p++) {
  16340. for (var i = 0; i < 8; i++) {
  16341. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16342. return false;
  16343. }
  16344. }
  16345. }
  16346. return true;
  16347. };
  16348. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16349. for (var p = 0; p < 6; p++) {
  16350. var inCount = 8;
  16351. for (var i = 0; i < 8; i++) {
  16352. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16353. --inCount;
  16354. }
  16355. else {
  16356. break;
  16357. }
  16358. }
  16359. if (inCount === 0)
  16360. return false;
  16361. }
  16362. return true;
  16363. };
  16364. return BoundingBox;
  16365. }());
  16366. BABYLON.BoundingBox = BoundingBox;
  16367. })(BABYLON || (BABYLON = {}));
  16368. //# sourceMappingURL=babylon.boundingBox.js.map
  16369. "use strict";
  16370. var BABYLON;
  16371. (function (BABYLON) {
  16372. var computeBoxExtents = function (axis, box) {
  16373. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16374. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16375. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16376. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16377. var r = r0 + r1 + r2;
  16378. return {
  16379. min: p - r,
  16380. max: p + r
  16381. };
  16382. };
  16383. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16384. var axisOverlap = function (axis, box0, box1) {
  16385. var result0 = computeBoxExtents(axis, box0);
  16386. var result1 = computeBoxExtents(axis, box1);
  16387. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16388. };
  16389. var BoundingInfo = /** @class */ (function () {
  16390. function BoundingInfo(minimum, maximum) {
  16391. this.minimum = minimum;
  16392. this.maximum = maximum;
  16393. this._isLocked = false;
  16394. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16395. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16396. }
  16397. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16398. get: function () {
  16399. return this._isLocked;
  16400. },
  16401. set: function (value) {
  16402. this._isLocked = value;
  16403. },
  16404. enumerable: true,
  16405. configurable: true
  16406. });
  16407. // Methods
  16408. BoundingInfo.prototype.update = function (world) {
  16409. if (this._isLocked) {
  16410. return;
  16411. }
  16412. this.boundingBox._update(world);
  16413. this.boundingSphere._update(world);
  16414. };
  16415. /**
  16416. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16417. * @param center New center of the bounding info
  16418. * @param extend New extend of the bounding info
  16419. */
  16420. BoundingInfo.prototype.centerOn = function (center, extend) {
  16421. this.minimum = center.subtract(extend);
  16422. this.maximum = center.add(extend);
  16423. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16424. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16425. return this;
  16426. };
  16427. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16428. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16429. return false;
  16430. return this.boundingBox.isInFrustum(frustumPlanes);
  16431. };
  16432. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16433. /**
  16434. * Gets the world distance between the min and max points of the bounding box
  16435. */
  16436. get: function () {
  16437. var boundingBox = this.boundingBox;
  16438. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16439. return size.length();
  16440. },
  16441. enumerable: true,
  16442. configurable: true
  16443. });
  16444. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16445. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16446. };
  16447. BoundingInfo.prototype._checkCollision = function (collider) {
  16448. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16449. };
  16450. BoundingInfo.prototype.intersectsPoint = function (point) {
  16451. if (!this.boundingSphere.centerWorld) {
  16452. return false;
  16453. }
  16454. if (!this.boundingSphere.intersectsPoint(point)) {
  16455. return false;
  16456. }
  16457. if (!this.boundingBox.intersectsPoint(point)) {
  16458. return false;
  16459. }
  16460. return true;
  16461. };
  16462. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16463. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16464. return false;
  16465. }
  16466. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16467. return false;
  16468. }
  16469. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16470. return false;
  16471. }
  16472. if (!precise) {
  16473. return true;
  16474. }
  16475. var box0 = this.boundingBox;
  16476. var box1 = boundingInfo.boundingBox;
  16477. if (!axisOverlap(box0.directions[0], box0, box1))
  16478. return false;
  16479. if (!axisOverlap(box0.directions[1], box0, box1))
  16480. return false;
  16481. if (!axisOverlap(box0.directions[2], box0, box1))
  16482. return false;
  16483. if (!axisOverlap(box1.directions[0], box0, box1))
  16484. return false;
  16485. if (!axisOverlap(box1.directions[1], box0, box1))
  16486. return false;
  16487. if (!axisOverlap(box1.directions[2], box0, box1))
  16488. return false;
  16489. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16490. return false;
  16491. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16492. return false;
  16493. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16494. return false;
  16495. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16496. return false;
  16497. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16498. return false;
  16499. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16500. return false;
  16501. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16502. return false;
  16503. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16504. return false;
  16505. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16506. return false;
  16507. return true;
  16508. };
  16509. return BoundingInfo;
  16510. }());
  16511. BABYLON.BoundingInfo = BoundingInfo;
  16512. })(BABYLON || (BABYLON = {}));
  16513. //# sourceMappingURL=babylon.boundingInfo.js.map
  16514. "use strict";
  16515. var BABYLON;
  16516. (function (BABYLON) {
  16517. var TransformNode = /** @class */ (function (_super) {
  16518. __extends(TransformNode, _super);
  16519. function TransformNode(name, scene, isPure) {
  16520. if (scene === void 0) { scene = null; }
  16521. if (isPure === void 0) { isPure = true; }
  16522. var _this = _super.call(this, name, scene) || this;
  16523. _this._forward = new BABYLON.Vector3(0, 0, 1);
  16524. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  16525. _this._up = new BABYLON.Vector3(0, 1, 0);
  16526. _this._right = new BABYLON.Vector3(1, 0, 0);
  16527. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  16528. // Properties
  16529. _this._rotation = BABYLON.Vector3.Zero();
  16530. _this._scaling = BABYLON.Vector3.One();
  16531. _this._isDirty = false;
  16532. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  16533. _this.scalingDeterminant = 1;
  16534. _this.infiniteDistance = false;
  16535. _this.position = BABYLON.Vector3.Zero();
  16536. _this._localWorld = BABYLON.Matrix.Zero();
  16537. _this._worldMatrix = BABYLON.Matrix.Zero();
  16538. _this._worldMatrixDeterminant = 0;
  16539. _this._absolutePosition = BABYLON.Vector3.Zero();
  16540. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16541. _this._postMultiplyPivotMatrix = false;
  16542. _this._isWorldMatrixFrozen = false;
  16543. /**
  16544. * An event triggered after the world matrix is updated
  16545. * @type {BABYLON.Observable}
  16546. */
  16547. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16548. _this._nonUniformScaling = false;
  16549. if (isPure) {
  16550. _this.getScene().addTransformNode(_this);
  16551. }
  16552. return _this;
  16553. }
  16554. /**
  16555. * Gets a string idenfifying the name of the class
  16556. * @returns "TransformNode" string
  16557. */
  16558. TransformNode.prototype.getClassName = function () {
  16559. return "TransformNode";
  16560. };
  16561. Object.defineProperty(TransformNode.prototype, "rotation", {
  16562. /**
  16563. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16564. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16565. * Default : (0.0, 0.0, 0.0)
  16566. */
  16567. get: function () {
  16568. return this._rotation;
  16569. },
  16570. set: function (newRotation) {
  16571. this._rotation = newRotation;
  16572. },
  16573. enumerable: true,
  16574. configurable: true
  16575. });
  16576. Object.defineProperty(TransformNode.prototype, "scaling", {
  16577. /**
  16578. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16579. * Default : (1.0, 1.0, 1.0)
  16580. */
  16581. get: function () {
  16582. return this._scaling;
  16583. },
  16584. /**
  16585. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16586. * Default : (1.0, 1.0, 1.0)
  16587. */
  16588. set: function (newScaling) {
  16589. this._scaling = newScaling;
  16590. },
  16591. enumerable: true,
  16592. configurable: true
  16593. });
  16594. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16595. /**
  16596. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16597. * It's null by default.
  16598. * 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)
  16599. */
  16600. get: function () {
  16601. return this._rotationQuaternion;
  16602. },
  16603. set: function (quaternion) {
  16604. this._rotationQuaternion = quaternion;
  16605. //reset the rotation vector.
  16606. if (quaternion && this.rotation.length()) {
  16607. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16608. }
  16609. },
  16610. enumerable: true,
  16611. configurable: true
  16612. });
  16613. Object.defineProperty(TransformNode.prototype, "forward", {
  16614. /**
  16615. * The forward direction of that transform in world space.
  16616. */
  16617. get: function () {
  16618. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  16619. },
  16620. enumerable: true,
  16621. configurable: true
  16622. });
  16623. Object.defineProperty(TransformNode.prototype, "up", {
  16624. /**
  16625. * The up direction of that transform in world space.
  16626. */
  16627. get: function () {
  16628. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  16629. },
  16630. enumerable: true,
  16631. configurable: true
  16632. });
  16633. Object.defineProperty(TransformNode.prototype, "right", {
  16634. /**
  16635. * The right direction of that transform in world space.
  16636. */
  16637. get: function () {
  16638. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  16639. },
  16640. enumerable: true,
  16641. configurable: true
  16642. });
  16643. /**
  16644. * Returns the latest update of the World matrix
  16645. * Returns a Matrix.
  16646. */
  16647. TransformNode.prototype.getWorldMatrix = function () {
  16648. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16649. this.computeWorldMatrix();
  16650. }
  16651. return this._worldMatrix;
  16652. };
  16653. /**
  16654. * Returns the latest update of the World matrix determinant.
  16655. */
  16656. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16657. return this._worldMatrixDeterminant;
  16658. };
  16659. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16660. /**
  16661. * Returns directly the latest state of the mesh World matrix.
  16662. * A Matrix is returned.
  16663. */
  16664. get: function () {
  16665. return this._worldMatrix;
  16666. },
  16667. enumerable: true,
  16668. configurable: true
  16669. });
  16670. /**
  16671. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16672. * Returns the TransformNode.
  16673. */
  16674. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16675. this._poseMatrix.copyFrom(matrix);
  16676. return this;
  16677. };
  16678. /**
  16679. * Returns the mesh Pose matrix.
  16680. * Returned object : Matrix
  16681. */
  16682. TransformNode.prototype.getPoseMatrix = function () {
  16683. return this._poseMatrix;
  16684. };
  16685. TransformNode.prototype._isSynchronized = function () {
  16686. if (this._isDirty) {
  16687. return false;
  16688. }
  16689. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  16690. return false;
  16691. if (this._cache.pivotMatrixUpdated) {
  16692. return false;
  16693. }
  16694. if (this.infiniteDistance) {
  16695. return false;
  16696. }
  16697. if (!this._cache.position.equals(this.position))
  16698. return false;
  16699. if (this.rotationQuaternion) {
  16700. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16701. return false;
  16702. }
  16703. if (!this._cache.rotation.equals(this.rotation))
  16704. return false;
  16705. if (!this._cache.scaling.equals(this.scaling))
  16706. return false;
  16707. return true;
  16708. };
  16709. TransformNode.prototype._initCache = function () {
  16710. _super.prototype._initCache.call(this);
  16711. this._cache.localMatrixUpdated = false;
  16712. this._cache.position = BABYLON.Vector3.Zero();
  16713. this._cache.scaling = BABYLON.Vector3.Zero();
  16714. this._cache.rotation = BABYLON.Vector3.Zero();
  16715. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16716. this._cache.billboardMode = -1;
  16717. };
  16718. TransformNode.prototype.markAsDirty = function (property) {
  16719. if (property === "rotation") {
  16720. this.rotationQuaternion = null;
  16721. }
  16722. this._currentRenderId = Number.MAX_VALUE;
  16723. this._isDirty = true;
  16724. return this;
  16725. };
  16726. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16727. /**
  16728. * Returns the current mesh absolute position.
  16729. * Retuns a Vector3.
  16730. */
  16731. get: function () {
  16732. return this._absolutePosition;
  16733. },
  16734. enumerable: true,
  16735. configurable: true
  16736. });
  16737. /**
  16738. * Sets a new matrix to apply before all other transformation
  16739. * @param matrix defines the transform matrix
  16740. * @returns the current TransformNode
  16741. */
  16742. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16743. return this.setPivotMatrix(matrix, false);
  16744. };
  16745. /**
  16746. * Sets a new pivot matrix to the current node
  16747. * @param matrix defines the new pivot matrix to use
  16748. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  16749. * @returns the current TransformNode
  16750. */
  16751. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16752. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16753. this._pivotMatrix = matrix.clone();
  16754. this._cache.pivotMatrixUpdated = true;
  16755. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16756. if (this._postMultiplyPivotMatrix) {
  16757. if (!this._pivotMatrixInverse) {
  16758. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16759. }
  16760. else {
  16761. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16762. }
  16763. }
  16764. return this;
  16765. };
  16766. /**
  16767. * Returns the mesh pivot matrix.
  16768. * Default : Identity.
  16769. * A Matrix is returned.
  16770. */
  16771. TransformNode.prototype.getPivotMatrix = function () {
  16772. return this._pivotMatrix;
  16773. };
  16774. /**
  16775. * Prevents the World matrix to be computed any longer.
  16776. * Returns the TransformNode.
  16777. */
  16778. TransformNode.prototype.freezeWorldMatrix = function () {
  16779. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16780. this.computeWorldMatrix(true);
  16781. this._isWorldMatrixFrozen = true;
  16782. return this;
  16783. };
  16784. /**
  16785. * Allows back the World matrix computation.
  16786. * Returns the TransformNode.
  16787. */
  16788. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16789. this._isWorldMatrixFrozen = false;
  16790. this.computeWorldMatrix(true);
  16791. return this;
  16792. };
  16793. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16794. /**
  16795. * True if the World matrix has been frozen.
  16796. * Returns a boolean.
  16797. */
  16798. get: function () {
  16799. return this._isWorldMatrixFrozen;
  16800. },
  16801. enumerable: true,
  16802. configurable: true
  16803. });
  16804. /**
  16805. * Retuns the mesh absolute position in the World.
  16806. * Returns a Vector3.
  16807. */
  16808. TransformNode.prototype.getAbsolutePosition = function () {
  16809. this.computeWorldMatrix();
  16810. return this._absolutePosition;
  16811. };
  16812. /**
  16813. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16814. * Returns the TransformNode.
  16815. */
  16816. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16817. if (!absolutePosition) {
  16818. return this;
  16819. }
  16820. var absolutePositionX;
  16821. var absolutePositionY;
  16822. var absolutePositionZ;
  16823. if (absolutePosition.x === undefined) {
  16824. if (arguments.length < 3) {
  16825. return this;
  16826. }
  16827. absolutePositionX = arguments[0];
  16828. absolutePositionY = arguments[1];
  16829. absolutePositionZ = arguments[2];
  16830. }
  16831. else {
  16832. absolutePositionX = absolutePosition.x;
  16833. absolutePositionY = absolutePosition.y;
  16834. absolutePositionZ = absolutePosition.z;
  16835. }
  16836. if (this.parent) {
  16837. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16838. invertParentWorldMatrix.invert();
  16839. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16840. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16841. }
  16842. else {
  16843. this.position.x = absolutePositionX;
  16844. this.position.y = absolutePositionY;
  16845. this.position.z = absolutePositionZ;
  16846. }
  16847. return this;
  16848. };
  16849. /**
  16850. * Sets the mesh position in its local space.
  16851. * Returns the TransformNode.
  16852. */
  16853. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16854. this.computeWorldMatrix();
  16855. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16856. return this;
  16857. };
  16858. /**
  16859. * Returns the mesh position in the local space from the current World matrix values.
  16860. * Returns a new Vector3.
  16861. */
  16862. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16863. this.computeWorldMatrix();
  16864. var invLocalWorldMatrix = this._localWorld.clone();
  16865. invLocalWorldMatrix.invert();
  16866. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16867. };
  16868. /**
  16869. * Translates the mesh along the passed Vector3 in its local space.
  16870. * Returns the TransformNode.
  16871. */
  16872. TransformNode.prototype.locallyTranslate = function (vector3) {
  16873. this.computeWorldMatrix(true);
  16874. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16875. return this;
  16876. };
  16877. /**
  16878. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16879. * @param targetPoint the position (must be in same space as current mesh) to look at
  16880. * @param yawCor optional yaw (y-axis) correction in radians
  16881. * @param pitchCor optional pitch (x-axis) correction in radians
  16882. * @param rollCor optional roll (z-axis) correction in radians
  16883. * @param space the choosen space of the target
  16884. * @returns the TransformNode.
  16885. */
  16886. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16887. if (yawCor === void 0) { yawCor = 0; }
  16888. if (pitchCor === void 0) { pitchCor = 0; }
  16889. if (rollCor === void 0) { rollCor = 0; }
  16890. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16891. var dv = TransformNode._lookAtVectorCache;
  16892. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16893. targetPoint.subtractToRef(pos, dv);
  16894. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16895. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16896. var pitch = Math.atan2(dv.y, len);
  16897. if (this.rotationQuaternion) {
  16898. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16899. }
  16900. else {
  16901. this.rotation.x = pitch + pitchCor;
  16902. this.rotation.y = yaw + yawCor;
  16903. this.rotation.z = rollCor;
  16904. }
  16905. return this;
  16906. };
  16907. /**
  16908. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16909. * This Vector3 is expressed in the World space.
  16910. */
  16911. TransformNode.prototype.getDirection = function (localAxis) {
  16912. var result = BABYLON.Vector3.Zero();
  16913. this.getDirectionToRef(localAxis, result);
  16914. return result;
  16915. };
  16916. /**
  16917. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16918. * localAxis is expressed in the mesh local space.
  16919. * result is computed in the Wordl space from the mesh World matrix.
  16920. * Returns the TransformNode.
  16921. */
  16922. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16923. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16924. return this;
  16925. };
  16926. /**
  16927. * Sets a new pivot point to the current node
  16928. * @param point defines the new pivot point to use
  16929. * @param space defines if the point is in world or local space (local by default)
  16930. * @returns the current TransformNode
  16931. */
  16932. TransformNode.prototype.setPivotPoint = function (point, space) {
  16933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16934. if (this.getScene().getRenderId() == 0) {
  16935. this.computeWorldMatrix(true);
  16936. }
  16937. var wm = this.getWorldMatrix();
  16938. if (space == BABYLON.Space.WORLD) {
  16939. var tmat = BABYLON.Tmp.Matrix[0];
  16940. wm.invertToRef(tmat);
  16941. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16942. }
  16943. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16944. };
  16945. /**
  16946. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16947. */
  16948. TransformNode.prototype.getPivotPoint = function () {
  16949. var point = BABYLON.Vector3.Zero();
  16950. this.getPivotPointToRef(point);
  16951. return point;
  16952. };
  16953. /**
  16954. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16955. * Returns the TransformNode.
  16956. */
  16957. TransformNode.prototype.getPivotPointToRef = function (result) {
  16958. result.x = -this._pivotMatrix.m[12];
  16959. result.y = -this._pivotMatrix.m[13];
  16960. result.z = -this._pivotMatrix.m[14];
  16961. return this;
  16962. };
  16963. /**
  16964. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16965. */
  16966. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16967. var point = BABYLON.Vector3.Zero();
  16968. this.getAbsolutePivotPointToRef(point);
  16969. return point;
  16970. };
  16971. /**
  16972. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16973. * Returns the TransformNode.
  16974. */
  16975. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16976. result.x = this._pivotMatrix.m[12];
  16977. result.y = this._pivotMatrix.m[13];
  16978. result.z = this._pivotMatrix.m[14];
  16979. this.getPivotPointToRef(result);
  16980. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16981. return this;
  16982. };
  16983. /**
  16984. * Defines the passed node as the parent of the current node.
  16985. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16986. * Returns the TransformNode.
  16987. */
  16988. TransformNode.prototype.setParent = function (node) {
  16989. if (node === null) {
  16990. var rotation = BABYLON.Tmp.Quaternion[0];
  16991. var position = BABYLON.Tmp.Vector3[0];
  16992. var scale = BABYLON.Tmp.Vector3[1];
  16993. if (this.parent && this.parent.computeWorldMatrix) {
  16994. this.parent.computeWorldMatrix(true);
  16995. }
  16996. this.computeWorldMatrix(true);
  16997. this.getWorldMatrix().decompose(scale, rotation, position);
  16998. if (this.rotationQuaternion) {
  16999. this.rotationQuaternion.copyFrom(rotation);
  17000. }
  17001. else {
  17002. rotation.toEulerAnglesToRef(this.rotation);
  17003. }
  17004. this.scaling.x = scale.x;
  17005. this.scaling.y = scale.y;
  17006. this.scaling.z = scale.z;
  17007. this.position.x = position.x;
  17008. this.position.y = position.y;
  17009. this.position.z = position.z;
  17010. }
  17011. else {
  17012. var rotation = BABYLON.Tmp.Quaternion[0];
  17013. var position = BABYLON.Tmp.Vector3[0];
  17014. var scale = BABYLON.Tmp.Vector3[1];
  17015. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17016. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17017. this.computeWorldMatrix(true);
  17018. node.computeWorldMatrix(true);
  17019. node.getWorldMatrix().invertToRef(invParentMatrix);
  17020. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17021. diffMatrix.decompose(scale, rotation, position);
  17022. if (this.rotationQuaternion) {
  17023. this.rotationQuaternion.copyFrom(rotation);
  17024. }
  17025. else {
  17026. rotation.toEulerAnglesToRef(this.rotation);
  17027. }
  17028. this.position.x = position.x;
  17029. this.position.y = position.y;
  17030. this.position.z = position.z;
  17031. this.scaling.x = scale.x;
  17032. this.scaling.y = scale.y;
  17033. this.scaling.z = scale.z;
  17034. }
  17035. this.parent = node;
  17036. return this;
  17037. };
  17038. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17039. get: function () {
  17040. return this._nonUniformScaling;
  17041. },
  17042. enumerable: true,
  17043. configurable: true
  17044. });
  17045. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17046. if (this._nonUniformScaling === value) {
  17047. return false;
  17048. }
  17049. this._nonUniformScaling = true;
  17050. return true;
  17051. };
  17052. /**
  17053. * Attach the current TransformNode to another TransformNode associated with a bone
  17054. * @param bone Bone affecting the TransformNode
  17055. * @param affectedTransformNode TransformNode associated with the bone
  17056. */
  17057. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17058. this._transformToBoneReferal = affectedTransformNode;
  17059. this.parent = bone;
  17060. if (bone.getWorldMatrix().determinant() < 0) {
  17061. this.scalingDeterminant *= -1;
  17062. }
  17063. return this;
  17064. };
  17065. TransformNode.prototype.detachFromBone = function () {
  17066. if (!this.parent) {
  17067. return this;
  17068. }
  17069. if (this.parent.getWorldMatrix().determinant() < 0) {
  17070. this.scalingDeterminant *= -1;
  17071. }
  17072. this._transformToBoneReferal = null;
  17073. this.parent = null;
  17074. return this;
  17075. };
  17076. /**
  17077. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17078. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17079. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17080. * The passed axis is also normalized.
  17081. * Returns the TransformNode.
  17082. */
  17083. TransformNode.prototype.rotate = function (axis, amount, space) {
  17084. axis.normalize();
  17085. if (!this.rotationQuaternion) {
  17086. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17087. this.rotation = BABYLON.Vector3.Zero();
  17088. }
  17089. var rotationQuaternion;
  17090. if (!space || space === BABYLON.Space.LOCAL) {
  17091. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17092. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17093. }
  17094. else {
  17095. if (this.parent) {
  17096. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17097. invertParentWorldMatrix.invert();
  17098. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17099. }
  17100. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17101. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17102. }
  17103. return this;
  17104. };
  17105. /**
  17106. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17107. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17108. * The passed axis is also normalized.
  17109. * Returns the TransformNode.
  17110. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17111. */
  17112. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17113. axis.normalize();
  17114. if (!this.rotationQuaternion) {
  17115. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17116. this.rotation.copyFromFloats(0, 0, 0);
  17117. }
  17118. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17119. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17120. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17121. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17122. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17123. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17124. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17125. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17126. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17127. return this;
  17128. };
  17129. /**
  17130. * Translates the mesh along the axis vector for the passed distance in the given space.
  17131. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17132. * Returns the TransformNode.
  17133. */
  17134. TransformNode.prototype.translate = function (axis, distance, space) {
  17135. var displacementVector = axis.scale(distance);
  17136. if (!space || space === BABYLON.Space.LOCAL) {
  17137. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17138. this.setPositionWithLocalVector(tempV3);
  17139. }
  17140. else {
  17141. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17142. }
  17143. return this;
  17144. };
  17145. /**
  17146. * Adds a rotation step to the mesh current rotation.
  17147. * x, y, z are Euler angles expressed in radians.
  17148. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17149. * This means this rotation is made in the mesh local space only.
  17150. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17151. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17152. * ```javascript
  17153. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17154. * ```
  17155. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17156. * 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.
  17157. * Returns the TransformNode.
  17158. */
  17159. TransformNode.prototype.addRotation = function (x, y, z) {
  17160. var rotationQuaternion;
  17161. if (this.rotationQuaternion) {
  17162. rotationQuaternion = this.rotationQuaternion;
  17163. }
  17164. else {
  17165. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17166. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17167. }
  17168. var accumulation = BABYLON.Tmp.Quaternion[0];
  17169. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17170. rotationQuaternion.multiplyInPlace(accumulation);
  17171. if (!this.rotationQuaternion) {
  17172. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17173. }
  17174. return this;
  17175. };
  17176. /**
  17177. * Computes the mesh World matrix and returns it.
  17178. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17179. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17180. * If the parameter `force`is set to `true`, the actual computation is done.
  17181. * Returns the mesh World Matrix.
  17182. */
  17183. TransformNode.prototype.computeWorldMatrix = function (force) {
  17184. if (this._isWorldMatrixFrozen) {
  17185. return this._worldMatrix;
  17186. }
  17187. if (!force && this.isSynchronized(true)) {
  17188. this._currentRenderId = this.getScene().getRenderId();
  17189. return this._worldMatrix;
  17190. }
  17191. this._cache.position.copyFrom(this.position);
  17192. this._cache.scaling.copyFrom(this.scaling);
  17193. this._cache.pivotMatrixUpdated = false;
  17194. this._cache.billboardMode = this.billboardMode;
  17195. this._currentRenderId = this.getScene().getRenderId();
  17196. this._childRenderId = this.getScene().getRenderId();
  17197. this._isDirty = false;
  17198. // Scaling
  17199. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17200. // Rotation
  17201. //rotate, if quaternion is set and rotation was used
  17202. if (this.rotationQuaternion) {
  17203. var len = this.rotation.length();
  17204. if (len) {
  17205. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17206. this.rotation.copyFromFloats(0, 0, 0);
  17207. }
  17208. }
  17209. if (this.rotationQuaternion) {
  17210. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17211. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17212. }
  17213. else {
  17214. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17215. this._cache.rotation.copyFrom(this.rotation);
  17216. }
  17217. // Translation
  17218. var camera = this.getScene().activeCamera;
  17219. if (this.infiniteDistance && !this.parent && camera) {
  17220. var cameraWorldMatrix = camera.getWorldMatrix();
  17221. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17222. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17223. }
  17224. else {
  17225. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17226. }
  17227. // Composing transformations
  17228. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17229. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17230. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17231. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  17232. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  17233. // Need to decompose each rotation here
  17234. var currentPosition = BABYLON.Tmp.Vector3[3];
  17235. if (this.parent && this.parent.getWorldMatrix) {
  17236. if (this._transformToBoneReferal) {
  17237. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17238. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17239. }
  17240. else {
  17241. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17242. }
  17243. }
  17244. else {
  17245. currentPosition.copyFrom(this.position);
  17246. }
  17247. currentPosition.subtractInPlace(camera.globalPosition);
  17248. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17249. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  17250. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17251. }
  17252. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  17253. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17254. }
  17255. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  17256. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17257. }
  17258. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17259. }
  17260. else {
  17261. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17262. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17263. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17264. }
  17265. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17266. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17267. }
  17268. // Local world
  17269. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17270. // Parent
  17271. if (this.parent && this.parent.getWorldMatrix) {
  17272. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  17273. if (this._transformToBoneReferal) {
  17274. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17275. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17276. }
  17277. else {
  17278. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17279. }
  17280. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17281. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17282. this._worldMatrix.copyFrom(this._localWorld);
  17283. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17284. }
  17285. else {
  17286. if (this._transformToBoneReferal) {
  17287. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17288. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17289. }
  17290. else {
  17291. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17292. }
  17293. }
  17294. this._markSyncedWithParent();
  17295. }
  17296. else {
  17297. this._worldMatrix.copyFrom(this._localWorld);
  17298. }
  17299. // Post multiply inverse of pivotMatrix
  17300. if (this._postMultiplyPivotMatrix) {
  17301. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17302. }
  17303. // Normal matrix
  17304. if (this.scaling.isNonUniform) {
  17305. this._updateNonUniformScalingState(true);
  17306. }
  17307. else if (this.parent && this.parent._nonUniformScaling) {
  17308. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17309. }
  17310. else {
  17311. this._updateNonUniformScalingState(false);
  17312. }
  17313. this._afterComputeWorldMatrix();
  17314. // Absolute position
  17315. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17316. // Callbacks
  17317. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17318. if (!this._poseMatrix) {
  17319. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17320. }
  17321. // Cache the determinant
  17322. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17323. return this._worldMatrix;
  17324. };
  17325. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17326. };
  17327. /**
  17328. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17329. * @param func: callback function to add
  17330. *
  17331. * Returns the TransformNode.
  17332. */
  17333. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17334. this.onAfterWorldMatrixUpdateObservable.add(func);
  17335. return this;
  17336. };
  17337. /**
  17338. * Removes a registered callback function.
  17339. * Returns the TransformNode.
  17340. */
  17341. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17342. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17343. return this;
  17344. };
  17345. /**
  17346. * Clone the current transform node
  17347. * Returns the new transform node
  17348. * @param name Name of the new clone
  17349. * @param newParent New parent for the clone
  17350. * @param doNotCloneChildren Do not clone children hierarchy
  17351. */
  17352. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17353. var _this = this;
  17354. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17355. result.name = name;
  17356. result.id = name;
  17357. if (newParent) {
  17358. result.parent = newParent;
  17359. }
  17360. if (!doNotCloneChildren) {
  17361. // Children
  17362. var directDescendants = this.getDescendants(true);
  17363. for (var index = 0; index < directDescendants.length; index++) {
  17364. var child = directDescendants[index];
  17365. if (child.clone) {
  17366. child.clone(name + "." + child.name, result);
  17367. }
  17368. }
  17369. }
  17370. return result;
  17371. };
  17372. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17373. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17374. serializationObject.type = this.getClassName();
  17375. // Parent
  17376. if (this.parent) {
  17377. serializationObject.parentId = this.parent.id;
  17378. }
  17379. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17380. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17381. }
  17382. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17383. serializationObject.isEnabled = this.isEnabled();
  17384. // Parent
  17385. if (this.parent) {
  17386. serializationObject.parentId = this.parent.id;
  17387. }
  17388. return serializationObject;
  17389. };
  17390. // Statics
  17391. /**
  17392. * Returns a new TransformNode object parsed from the source provided.
  17393. * The parameter `parsedMesh` is the source.
  17394. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17395. */
  17396. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17397. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17398. if (BABYLON.Tags) {
  17399. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17400. }
  17401. if (parsedTransformNode.localMatrix) {
  17402. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17403. }
  17404. else if (parsedTransformNode.pivotMatrix) {
  17405. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17406. }
  17407. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17408. // Parent
  17409. if (parsedTransformNode.parentId) {
  17410. transformNode._waitingParentId = parsedTransformNode.parentId;
  17411. }
  17412. return transformNode;
  17413. };
  17414. /**
  17415. * Releases resources associated with this transform node.
  17416. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17417. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17418. */
  17419. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17420. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17421. // Animations
  17422. this.getScene().stopAnimation(this);
  17423. // Remove from scene
  17424. this.getScene().removeTransformNode(this);
  17425. this.onAfterWorldMatrixUpdateObservable.clear();
  17426. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17427. };
  17428. // Statics
  17429. TransformNode.BILLBOARDMODE_NONE = 0;
  17430. TransformNode.BILLBOARDMODE_X = 1;
  17431. TransformNode.BILLBOARDMODE_Y = 2;
  17432. TransformNode.BILLBOARDMODE_Z = 4;
  17433. TransformNode.BILLBOARDMODE_ALL = 7;
  17434. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17435. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17436. __decorate([
  17437. BABYLON.serializeAsVector3()
  17438. ], TransformNode.prototype, "_rotation", void 0);
  17439. __decorate([
  17440. BABYLON.serializeAsQuaternion()
  17441. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17442. __decorate([
  17443. BABYLON.serializeAsVector3()
  17444. ], TransformNode.prototype, "_scaling", void 0);
  17445. __decorate([
  17446. BABYLON.serialize()
  17447. ], TransformNode.prototype, "billboardMode", void 0);
  17448. __decorate([
  17449. BABYLON.serialize()
  17450. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17451. __decorate([
  17452. BABYLON.serialize()
  17453. ], TransformNode.prototype, "infiniteDistance", void 0);
  17454. __decorate([
  17455. BABYLON.serializeAsVector3()
  17456. ], TransformNode.prototype, "position", void 0);
  17457. return TransformNode;
  17458. }(BABYLON.Node));
  17459. BABYLON.TransformNode = TransformNode;
  17460. })(BABYLON || (BABYLON = {}));
  17461. //# sourceMappingURL=babylon.transformNode.js.map
  17462. "use strict";
  17463. var BABYLON;
  17464. (function (BABYLON) {
  17465. var AbstractMesh = /** @class */ (function (_super) {
  17466. __extends(AbstractMesh, _super);
  17467. // Constructor
  17468. function AbstractMesh(name, scene) {
  17469. if (scene === void 0) { scene = null; }
  17470. var _this = _super.call(this, name, scene, false) || this;
  17471. _this._facetNb = 0; // facet number
  17472. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17473. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17474. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17475. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17476. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17477. _this._subDiv = {
  17478. max: 1,
  17479. X: 1,
  17480. Y: 1,
  17481. Z: 1
  17482. };
  17483. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17484. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17485. // Events
  17486. /**
  17487. * An event triggered when this mesh collides with another one
  17488. * @type {BABYLON.Observable}
  17489. */
  17490. _this.onCollideObservable = new BABYLON.Observable();
  17491. /**
  17492. * An event triggered when the collision's position changes
  17493. * @type {BABYLON.Observable}
  17494. */
  17495. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17496. /**
  17497. * An event triggered when material is changed
  17498. * @type {BABYLON.Observable}
  17499. */
  17500. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17501. // Properties
  17502. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17503. /**
  17504. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17505. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17506. * or
  17507. * 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.
  17508. * for more info check WebGl documentations
  17509. */
  17510. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17511. /**
  17512. * 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:
  17513. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17514. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17515. * 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.
  17516. */
  17517. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17518. /**
  17519. * 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.
  17520. * The default value is -1 which means don't break the query and wait till the result.
  17521. */
  17522. _this.occlusionRetryCount = -1;
  17523. _this._occlusionInternalRetryCounter = 0;
  17524. _this._isOccluded = false;
  17525. _this._isOcclusionQueryInProgress = false;
  17526. _this._visibility = 1.0;
  17527. _this.alphaIndex = Number.MAX_VALUE;
  17528. _this.isVisible = true;
  17529. _this.isPickable = true;
  17530. _this.showBoundingBox = false;
  17531. _this.showSubMeshesBoundingBox = false;
  17532. _this.isBlocker = false;
  17533. _this.enablePointerMoveEvents = false;
  17534. _this.renderingGroupId = 0;
  17535. _this._receiveShadows = false;
  17536. _this.renderOutline = false;
  17537. _this.outlineColor = BABYLON.Color3.Red();
  17538. _this.outlineWidth = 0.02;
  17539. _this.renderOverlay = false;
  17540. _this.overlayColor = BABYLON.Color3.Red();
  17541. _this.overlayAlpha = 0.5;
  17542. _this._hasVertexAlpha = false;
  17543. _this._useVertexColors = true;
  17544. _this._computeBonesUsingShaders = true;
  17545. _this._numBoneInfluencers = 4;
  17546. _this._applyFog = true;
  17547. _this.useOctreeForRenderingSelection = true;
  17548. _this.useOctreeForPicking = true;
  17549. _this.useOctreeForCollisions = true;
  17550. _this._layerMask = 0x0FFFFFFF;
  17551. /**
  17552. * True if the mesh must be rendered in any case.
  17553. */
  17554. _this.alwaysSelectAsActiveMesh = false;
  17555. /**
  17556. * This scene's action manager
  17557. * @type {BABYLON.ActionManager}
  17558. */
  17559. _this.actionManager = null;
  17560. // Physics
  17561. _this.physicsImpostor = null;
  17562. // Collisions
  17563. _this._checkCollisions = false;
  17564. _this._collisionMask = -1;
  17565. _this._collisionGroup = -1;
  17566. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17567. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17568. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17569. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17570. // Edges
  17571. _this.edgesWidth = 1;
  17572. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17573. // Cache
  17574. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17575. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17576. _this._renderId = 0;
  17577. _this._intersectionsInProgress = new Array();
  17578. _this._unIndexed = false;
  17579. _this._lightSources = new Array();
  17580. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17581. if (collidedMesh === void 0) { collidedMesh = null; }
  17582. //TODO move this to the collision coordinator!
  17583. if (_this.getScene().workerCollisions)
  17584. newPosition.multiplyInPlace(_this._collider._radius);
  17585. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17586. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17587. _this.position.addInPlace(_this._diffPositionForCollisions);
  17588. }
  17589. if (collidedMesh) {
  17590. _this.onCollideObservable.notifyObservers(collidedMesh);
  17591. }
  17592. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17593. };
  17594. _this.getScene().addMesh(_this);
  17595. _this._resyncLightSources();
  17596. return _this;
  17597. }
  17598. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17599. get: function () {
  17600. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17601. },
  17602. enumerable: true,
  17603. configurable: true
  17604. });
  17605. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17606. get: function () {
  17607. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17608. },
  17609. enumerable: true,
  17610. configurable: true
  17611. });
  17612. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17613. get: function () {
  17614. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17615. },
  17616. enumerable: true,
  17617. configurable: true
  17618. });
  17619. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17620. get: function () {
  17621. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17622. },
  17623. enumerable: true,
  17624. configurable: true
  17625. });
  17626. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17627. get: function () {
  17628. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17634. /**
  17635. * Read-only : the number of facets in the mesh
  17636. */
  17637. get: function () {
  17638. return this._facetNb;
  17639. },
  17640. enumerable: true,
  17641. configurable: true
  17642. });
  17643. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17644. /**
  17645. * The number (integer) of subdivisions per axis in the partioning space
  17646. */
  17647. get: function () {
  17648. return this._partitioningSubdivisions;
  17649. },
  17650. set: function (nb) {
  17651. this._partitioningSubdivisions = nb;
  17652. },
  17653. enumerable: true,
  17654. configurable: true
  17655. });
  17656. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17657. /**
  17658. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17659. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17660. */
  17661. get: function () {
  17662. return this._partitioningBBoxRatio;
  17663. },
  17664. set: function (ratio) {
  17665. this._partitioningBBoxRatio = ratio;
  17666. },
  17667. enumerable: true,
  17668. configurable: true
  17669. });
  17670. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17671. /**
  17672. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17673. * Works only for updatable meshes.
  17674. * Doesn't work with multi-materials.
  17675. */
  17676. get: function () {
  17677. return this._facetDepthSort;
  17678. },
  17679. set: function (sort) {
  17680. this._facetDepthSort = sort;
  17681. },
  17682. enumerable: true,
  17683. configurable: true
  17684. });
  17685. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17686. /**
  17687. * The location (Vector3) where the facet depth sort must be computed from.
  17688. * By default, the active camera position.
  17689. * Used only when facet depth sort is enabled.
  17690. */
  17691. get: function () {
  17692. return this._facetDepthSortFrom;
  17693. },
  17694. set: function (location) {
  17695. this._facetDepthSortFrom = location;
  17696. },
  17697. enumerable: true,
  17698. configurable: true
  17699. });
  17700. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17701. /**
  17702. * Read-only boolean : is the feature facetData enabled ?
  17703. */
  17704. get: function () {
  17705. return this._facetDataEnabled;
  17706. },
  17707. enumerable: true,
  17708. configurable: true
  17709. });
  17710. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17711. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17712. return false;
  17713. }
  17714. this._markSubMeshesAsMiscDirty();
  17715. return true;
  17716. };
  17717. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17718. set: function (callback) {
  17719. if (this._onCollideObserver) {
  17720. this.onCollideObservable.remove(this._onCollideObserver);
  17721. }
  17722. this._onCollideObserver = this.onCollideObservable.add(callback);
  17723. },
  17724. enumerable: true,
  17725. configurable: true
  17726. });
  17727. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17728. set: function (callback) {
  17729. if (this._onCollisionPositionChangeObserver) {
  17730. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17731. }
  17732. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17733. },
  17734. enumerable: true,
  17735. configurable: true
  17736. });
  17737. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17738. /**
  17739. * 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.
  17740. */
  17741. get: function () {
  17742. return this._isOccluded;
  17743. },
  17744. set: function (value) {
  17745. this._isOccluded = value;
  17746. },
  17747. enumerable: true,
  17748. configurable: true
  17749. });
  17750. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17751. /**
  17752. * Flag to check the progress status of the query
  17753. */
  17754. get: function () {
  17755. return this._isOcclusionQueryInProgress;
  17756. },
  17757. enumerable: true,
  17758. configurable: true
  17759. });
  17760. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17761. /**
  17762. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17763. */
  17764. get: function () {
  17765. return this._visibility;
  17766. },
  17767. /**
  17768. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17769. */
  17770. set: function (value) {
  17771. if (this._visibility === value) {
  17772. return;
  17773. }
  17774. this._visibility = value;
  17775. this._markSubMeshesAsMiscDirty();
  17776. },
  17777. enumerable: true,
  17778. configurable: true
  17779. });
  17780. Object.defineProperty(AbstractMesh.prototype, "material", {
  17781. get: function () {
  17782. return this._material;
  17783. },
  17784. set: function (value) {
  17785. if (this._material === value) {
  17786. return;
  17787. }
  17788. this._material = value;
  17789. if (this.onMaterialChangedObservable.hasObservers) {
  17790. this.onMaterialChangedObservable.notifyObservers(this);
  17791. }
  17792. if (!this.subMeshes) {
  17793. return;
  17794. }
  17795. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17796. var subMesh = _a[_i];
  17797. subMesh.setEffect(null);
  17798. }
  17799. },
  17800. enumerable: true,
  17801. configurable: true
  17802. });
  17803. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17804. get: function () {
  17805. return this._receiveShadows;
  17806. },
  17807. set: function (value) {
  17808. if (this._receiveShadows === value) {
  17809. return;
  17810. }
  17811. this._receiveShadows = value;
  17812. this._markSubMeshesAsLightDirty();
  17813. },
  17814. enumerable: true,
  17815. configurable: true
  17816. });
  17817. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17818. get: function () {
  17819. return this._hasVertexAlpha;
  17820. },
  17821. set: function (value) {
  17822. if (this._hasVertexAlpha === value) {
  17823. return;
  17824. }
  17825. this._hasVertexAlpha = value;
  17826. this._markSubMeshesAsAttributesDirty();
  17827. this._markSubMeshesAsMiscDirty();
  17828. },
  17829. enumerable: true,
  17830. configurable: true
  17831. });
  17832. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17833. get: function () {
  17834. return this._useVertexColors;
  17835. },
  17836. set: function (value) {
  17837. if (this._useVertexColors === value) {
  17838. return;
  17839. }
  17840. this._useVertexColors = value;
  17841. this._markSubMeshesAsAttributesDirty();
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17847. get: function () {
  17848. return this._computeBonesUsingShaders;
  17849. },
  17850. set: function (value) {
  17851. if (this._computeBonesUsingShaders === value) {
  17852. return;
  17853. }
  17854. this._computeBonesUsingShaders = value;
  17855. this._markSubMeshesAsAttributesDirty();
  17856. },
  17857. enumerable: true,
  17858. configurable: true
  17859. });
  17860. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17861. get: function () {
  17862. return this._numBoneInfluencers;
  17863. },
  17864. set: function (value) {
  17865. if (this._numBoneInfluencers === value) {
  17866. return;
  17867. }
  17868. this._numBoneInfluencers = value;
  17869. this._markSubMeshesAsAttributesDirty();
  17870. },
  17871. enumerable: true,
  17872. configurable: true
  17873. });
  17874. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17875. get: function () {
  17876. return this._applyFog;
  17877. },
  17878. set: function (value) {
  17879. if (this._applyFog === value) {
  17880. return;
  17881. }
  17882. this._applyFog = value;
  17883. this._markSubMeshesAsMiscDirty();
  17884. },
  17885. enumerable: true,
  17886. configurable: true
  17887. });
  17888. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17889. get: function () {
  17890. return this._layerMask;
  17891. },
  17892. set: function (value) {
  17893. if (value === this._layerMask) {
  17894. return;
  17895. }
  17896. this._layerMask = value;
  17897. this._resyncLightSources();
  17898. },
  17899. enumerable: true,
  17900. configurable: true
  17901. });
  17902. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17903. get: function () {
  17904. return this._collisionMask;
  17905. },
  17906. set: function (mask) {
  17907. this._collisionMask = !isNaN(mask) ? mask : -1;
  17908. },
  17909. enumerable: true,
  17910. configurable: true
  17911. });
  17912. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17913. get: function () {
  17914. return this._collisionGroup;
  17915. },
  17916. set: function (mask) {
  17917. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17918. },
  17919. enumerable: true,
  17920. configurable: true
  17921. });
  17922. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17923. get: function () {
  17924. return null;
  17925. },
  17926. enumerable: true,
  17927. configurable: true
  17928. });
  17929. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17930. get: function () {
  17931. return this._skeleton;
  17932. },
  17933. set: function (value) {
  17934. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17935. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17936. }
  17937. if (value && value.needInitialSkinMatrix) {
  17938. value._registerMeshWithPoseMatrix(this);
  17939. }
  17940. this._skeleton = value;
  17941. if (!this._skeleton) {
  17942. this._bonesTransformMatrices = null;
  17943. }
  17944. this._markSubMeshesAsAttributesDirty();
  17945. },
  17946. enumerable: true,
  17947. configurable: true
  17948. });
  17949. /**
  17950. * Returns the string "AbstractMesh"
  17951. */
  17952. AbstractMesh.prototype.getClassName = function () {
  17953. return "AbstractMesh";
  17954. };
  17955. /**
  17956. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17957. */
  17958. AbstractMesh.prototype.toString = function (fullDetails) {
  17959. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17960. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17961. if (this._skeleton) {
  17962. ret += ", skeleton: " + this._skeleton.name;
  17963. }
  17964. if (fullDetails) {
  17965. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17966. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17967. }
  17968. return ret;
  17969. };
  17970. AbstractMesh.prototype._rebuild = function () {
  17971. if (this._occlusionQuery) {
  17972. this._occlusionQuery = null;
  17973. }
  17974. if (this._edgesRenderer) {
  17975. this._edgesRenderer._rebuild();
  17976. }
  17977. if (!this.subMeshes) {
  17978. return;
  17979. }
  17980. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17981. var subMesh = _a[_i];
  17982. subMesh._rebuild();
  17983. }
  17984. };
  17985. AbstractMesh.prototype._resyncLightSources = function () {
  17986. this._lightSources.length = 0;
  17987. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17988. var light = _a[_i];
  17989. if (!light.isEnabled()) {
  17990. continue;
  17991. }
  17992. if (light.canAffectMesh(this)) {
  17993. this._lightSources.push(light);
  17994. }
  17995. }
  17996. this._markSubMeshesAsLightDirty();
  17997. };
  17998. AbstractMesh.prototype._resyncLighSource = function (light) {
  17999. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18000. var index = this._lightSources.indexOf(light);
  18001. if (index === -1) {
  18002. if (!isIn) {
  18003. return;
  18004. }
  18005. this._lightSources.push(light);
  18006. }
  18007. else {
  18008. if (isIn) {
  18009. return;
  18010. }
  18011. this._lightSources.splice(index, 1);
  18012. }
  18013. this._markSubMeshesAsLightDirty();
  18014. };
  18015. AbstractMesh.prototype._removeLightSource = function (light) {
  18016. var index = this._lightSources.indexOf(light);
  18017. if (index === -1) {
  18018. return;
  18019. }
  18020. this._lightSources.splice(index, 1);
  18021. this._markSubMeshesAsLightDirty();
  18022. };
  18023. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18024. if (!this.subMeshes) {
  18025. return;
  18026. }
  18027. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18028. var subMesh = _a[_i];
  18029. if (subMesh._materialDefines) {
  18030. func(subMesh._materialDefines);
  18031. }
  18032. }
  18033. };
  18034. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18035. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18036. };
  18037. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18038. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18039. };
  18040. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18041. if (!this.subMeshes) {
  18042. return;
  18043. }
  18044. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18045. var subMesh = _a[_i];
  18046. var material = subMesh.getMaterial();
  18047. if (material) {
  18048. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18049. }
  18050. }
  18051. };
  18052. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18053. /**
  18054. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18055. * Default : (1.0, 1.0, 1.0)
  18056. */
  18057. get: function () {
  18058. return this._scaling;
  18059. },
  18060. /**
  18061. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18062. * Default : (1.0, 1.0, 1.0)
  18063. */
  18064. set: function (newScaling) {
  18065. this._scaling = newScaling;
  18066. if (this.physicsImpostor) {
  18067. this.physicsImpostor.forceUpdate();
  18068. }
  18069. },
  18070. enumerable: true,
  18071. configurable: true
  18072. });
  18073. // Methods
  18074. /**
  18075. * Disables the mesh edger rendering mode.
  18076. * Returns the AbstractMesh.
  18077. */
  18078. AbstractMesh.prototype.disableEdgesRendering = function () {
  18079. if (this._edgesRenderer) {
  18080. this._edgesRenderer.dispose();
  18081. this._edgesRenderer = null;
  18082. }
  18083. return this;
  18084. };
  18085. /**
  18086. * Enables the edge rendering mode on the mesh.
  18087. * This mode makes the mesh edges visible.
  18088. * Returns the AbstractMesh.
  18089. */
  18090. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18091. if (epsilon === void 0) { epsilon = 0.95; }
  18092. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18093. this.disableEdgesRendering();
  18094. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18095. return this;
  18096. };
  18097. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18098. /**
  18099. * Returns true if the mesh is blocked. Used by the class Mesh.
  18100. * Returns the boolean `false` by default.
  18101. */
  18102. get: function () {
  18103. return false;
  18104. },
  18105. enumerable: true,
  18106. configurable: true
  18107. });
  18108. /**
  18109. * Returns the mesh itself by default, used by the class Mesh.
  18110. * Returned type : AbstractMesh
  18111. */
  18112. AbstractMesh.prototype.getLOD = function (camera) {
  18113. return this;
  18114. };
  18115. /**
  18116. * Returns 0 by default, used by the class Mesh.
  18117. * Returns an integer.
  18118. */
  18119. AbstractMesh.prototype.getTotalVertices = function () {
  18120. return 0;
  18121. };
  18122. /**
  18123. * Returns null by default, used by the class Mesh.
  18124. * Returned type : integer array
  18125. */
  18126. AbstractMesh.prototype.getIndices = function () {
  18127. return null;
  18128. };
  18129. /**
  18130. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18131. * Returned type : float array or Float32Array
  18132. */
  18133. AbstractMesh.prototype.getVerticesData = function (kind) {
  18134. return null;
  18135. };
  18136. /**
  18137. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18138. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18139. * The `data` are either a numeric array either a Float32Array.
  18140. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18141. * 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).
  18142. * Note that a new underlying VertexBuffer object is created each call.
  18143. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18144. *
  18145. * Possible `kind` values :
  18146. * - BABYLON.VertexBuffer.PositionKind
  18147. * - BABYLON.VertexBuffer.UVKind
  18148. * - BABYLON.VertexBuffer.UV2Kind
  18149. * - BABYLON.VertexBuffer.UV3Kind
  18150. * - BABYLON.VertexBuffer.UV4Kind
  18151. * - BABYLON.VertexBuffer.UV5Kind
  18152. * - BABYLON.VertexBuffer.UV6Kind
  18153. * - BABYLON.VertexBuffer.ColorKind
  18154. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18155. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18156. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18157. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18158. *
  18159. * Returns the Mesh.
  18160. */
  18161. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18162. return this;
  18163. };
  18164. /**
  18165. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18166. * If the mesh has no geometry, it is simply returned as it is.
  18167. * The `data` are either a numeric array either a Float32Array.
  18168. * No new underlying VertexBuffer object is created.
  18169. * 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.
  18170. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18171. *
  18172. * Possible `kind` values :
  18173. * - BABYLON.VertexBuffer.PositionKind
  18174. * - BABYLON.VertexBuffer.UVKind
  18175. * - BABYLON.VertexBuffer.UV2Kind
  18176. * - BABYLON.VertexBuffer.UV3Kind
  18177. * - BABYLON.VertexBuffer.UV4Kind
  18178. * - BABYLON.VertexBuffer.UV5Kind
  18179. * - BABYLON.VertexBuffer.UV6Kind
  18180. * - BABYLON.VertexBuffer.ColorKind
  18181. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18182. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18183. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18184. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18185. *
  18186. * Returns the Mesh.
  18187. */
  18188. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18189. return this;
  18190. };
  18191. /**
  18192. * Sets the mesh indices.
  18193. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18194. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18195. * This method creates a new index buffer each call.
  18196. * Returns the Mesh.
  18197. */
  18198. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18199. return this;
  18200. };
  18201. /** Returns false by default, used by the class Mesh.
  18202. * Returns a boolean
  18203. */
  18204. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18205. return false;
  18206. };
  18207. /**
  18208. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18209. * Returns a BoundingInfo
  18210. */
  18211. AbstractMesh.prototype.getBoundingInfo = function () {
  18212. if (this._masterMesh) {
  18213. return this._masterMesh.getBoundingInfo();
  18214. }
  18215. if (!this._boundingInfo) {
  18216. // this._boundingInfo is being created here
  18217. this._updateBoundingInfo();
  18218. }
  18219. // cannot be null.
  18220. return this._boundingInfo;
  18221. };
  18222. /**
  18223. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18224. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18225. */
  18226. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18227. if (includeDescendants === void 0) { includeDescendants = true; }
  18228. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18229. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18230. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18231. if (maxDimension === 0) {
  18232. return this;
  18233. }
  18234. var scale = 1 / maxDimension;
  18235. this.scaling.scaleInPlace(scale);
  18236. return this;
  18237. };
  18238. /**
  18239. * Sets a mesh new object BoundingInfo.
  18240. * Returns the AbstractMesh.
  18241. */
  18242. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18243. this._boundingInfo = boundingInfo;
  18244. return this;
  18245. };
  18246. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18247. get: function () {
  18248. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18249. },
  18250. enumerable: true,
  18251. configurable: true
  18252. });
  18253. AbstractMesh.prototype._preActivate = function () {
  18254. };
  18255. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18256. };
  18257. AbstractMesh.prototype._activate = function (renderId) {
  18258. this._renderId = renderId;
  18259. };
  18260. /**
  18261. * Returns the latest update of the World matrix
  18262. * Returns a Matrix.
  18263. */
  18264. AbstractMesh.prototype.getWorldMatrix = function () {
  18265. if (this._masterMesh) {
  18266. return this._masterMesh.getWorldMatrix();
  18267. }
  18268. return _super.prototype.getWorldMatrix.call(this);
  18269. };
  18270. /**
  18271. * Returns the latest update of the World matrix determinant.
  18272. */
  18273. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18274. if (this._masterMesh) {
  18275. return this._masterMesh._getWorldMatrixDeterminant();
  18276. }
  18277. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18278. };
  18279. // ================================== Point of View Movement =================================
  18280. /**
  18281. * Perform relative position change from the point of view of behind the front of the mesh.
  18282. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18283. * Supports definition of mesh facing forward or backward.
  18284. * @param {number} amountRight
  18285. * @param {number} amountUp
  18286. * @param {number} amountForward
  18287. *
  18288. * Returns the AbstractMesh.
  18289. */
  18290. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18291. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18292. return this;
  18293. };
  18294. /**
  18295. * Calculate relative position change from the point of view of behind the front of the mesh.
  18296. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18297. * Supports definition of mesh facing forward or backward.
  18298. * @param {number} amountRight
  18299. * @param {number} amountUp
  18300. * @param {number} amountForward
  18301. *
  18302. * Returns a new Vector3.
  18303. */
  18304. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18305. var rotMatrix = new BABYLON.Matrix();
  18306. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18307. rotQuaternion.toRotationMatrix(rotMatrix);
  18308. var translationDelta = BABYLON.Vector3.Zero();
  18309. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18310. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18311. return translationDelta;
  18312. };
  18313. // ================================== Point of View Rotation =================================
  18314. /**
  18315. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18316. * Supports definition of mesh facing forward or backward.
  18317. * @param {number} flipBack
  18318. * @param {number} twirlClockwise
  18319. * @param {number} tiltRight
  18320. *
  18321. * Returns the AbstractMesh.
  18322. */
  18323. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18324. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18325. return this;
  18326. };
  18327. /**
  18328. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18329. * Supports definition of mesh facing forward or backward.
  18330. * @param {number} flipBack
  18331. * @param {number} twirlClockwise
  18332. * @param {number} tiltRight
  18333. *
  18334. * Returns a new Vector3.
  18335. */
  18336. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18337. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18338. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18339. };
  18340. /**
  18341. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18342. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18343. */
  18344. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18345. if (includeDescendants === void 0) { includeDescendants = true; }
  18346. this.computeWorldMatrix(true);
  18347. var min;
  18348. var max;
  18349. var boundingInfo = this.getBoundingInfo();
  18350. if (!this.subMeshes) {
  18351. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18352. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18353. }
  18354. else {
  18355. min = boundingInfo.boundingBox.minimumWorld;
  18356. max = boundingInfo.boundingBox.maximumWorld;
  18357. }
  18358. if (includeDescendants) {
  18359. var descendants = this.getDescendants(false);
  18360. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18361. var descendant = descendants_1[_i];
  18362. var childMesh = descendant;
  18363. childMesh.computeWorldMatrix(true);
  18364. //make sure we have the needed params to get mix and max
  18365. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18366. continue;
  18367. }
  18368. var childBoundingInfo = childMesh.getBoundingInfo();
  18369. var boundingBox = childBoundingInfo.boundingBox;
  18370. var minBox = boundingBox.minimumWorld;
  18371. var maxBox = boundingBox.maximumWorld;
  18372. BABYLON.Tools.CheckExtends(minBox, min, max);
  18373. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18374. }
  18375. }
  18376. return {
  18377. min: min,
  18378. max: max
  18379. };
  18380. };
  18381. /**
  18382. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18383. * Returns the AbstractMesh.
  18384. */
  18385. AbstractMesh.prototype._updateBoundingInfo = function () {
  18386. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18387. this._boundingInfo.update(this.worldMatrixFromCache);
  18388. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18389. return this;
  18390. };
  18391. /**
  18392. * Update a mesh's children BoundingInfo objects only.
  18393. * Returns the AbstractMesh.
  18394. */
  18395. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18396. if (!this.subMeshes) {
  18397. return this;
  18398. }
  18399. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18400. var subMesh = this.subMeshes[subIndex];
  18401. if (!subMesh.IsGlobal) {
  18402. subMesh.updateBoundingInfo(matrix);
  18403. }
  18404. }
  18405. return this;
  18406. };
  18407. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18408. // Bounding info
  18409. this._updateBoundingInfo();
  18410. };
  18411. /**
  18412. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18413. * A mesh is in the frustum if its bounding box intersects the frustum.
  18414. * Boolean returned.
  18415. */
  18416. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18417. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18418. };
  18419. /**
  18420. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18421. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18422. * Boolean returned.
  18423. */
  18424. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18425. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18426. ;
  18427. };
  18428. /**
  18429. * True if the mesh intersects another mesh or a SolidParticle object.
  18430. * 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)
  18431. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18432. * Returns a boolean.
  18433. */
  18434. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18435. if (precise === void 0) { precise = false; }
  18436. if (!this._boundingInfo || !mesh._boundingInfo) {
  18437. return false;
  18438. }
  18439. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18440. return true;
  18441. }
  18442. if (includeDescendants) {
  18443. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18444. var child = _a[_i];
  18445. if (child.intersectsMesh(mesh, precise, true)) {
  18446. return true;
  18447. }
  18448. }
  18449. }
  18450. return false;
  18451. };
  18452. /**
  18453. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18454. * Returns a boolean.
  18455. */
  18456. AbstractMesh.prototype.intersectsPoint = function (point) {
  18457. if (!this._boundingInfo) {
  18458. return false;
  18459. }
  18460. return this._boundingInfo.intersectsPoint(point);
  18461. };
  18462. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18463. return this.physicsImpostor;
  18464. };
  18465. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18466. if (camera === void 0) { camera = null; }
  18467. if (!camera) {
  18468. camera = this.getScene().activeCamera;
  18469. }
  18470. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18471. };
  18472. /**
  18473. * Returns the distance from the mesh to the active camera.
  18474. * Returns a float.
  18475. */
  18476. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18477. if (camera === void 0) { camera = null; }
  18478. if (!camera) {
  18479. camera = this.getScene().activeCamera;
  18480. }
  18481. return this.absolutePosition.subtract(camera.position).length();
  18482. };
  18483. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18484. if (!this.physicsImpostor) {
  18485. return this;
  18486. }
  18487. this.physicsImpostor.applyImpulse(force, contactPoint);
  18488. return this;
  18489. };
  18490. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18491. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18492. return this;
  18493. }
  18494. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18495. mainPivot: pivot1,
  18496. connectedPivot: pivot2,
  18497. nativeParams: options
  18498. });
  18499. return this;
  18500. };
  18501. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18502. // Collisions
  18503. /**
  18504. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18505. * Default `false`.
  18506. */
  18507. get: function () {
  18508. return this._checkCollisions;
  18509. },
  18510. set: function (collisionEnabled) {
  18511. this._checkCollisions = collisionEnabled;
  18512. if (this.getScene().workerCollisions) {
  18513. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18514. }
  18515. },
  18516. enumerable: true,
  18517. configurable: true
  18518. });
  18519. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18520. /**
  18521. * Gets Collider object used to compute collisions (not physics)
  18522. */
  18523. get: function () {
  18524. return this._collider;
  18525. },
  18526. enumerable: true,
  18527. configurable: true
  18528. });
  18529. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18530. var globalPosition = this.getAbsolutePosition();
  18531. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18532. if (!this._collider) {
  18533. this._collider = new BABYLON.Collider();
  18534. }
  18535. this._collider._radius = this.ellipsoid;
  18536. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18537. return this;
  18538. };
  18539. // Submeshes octree
  18540. /**
  18541. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18542. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18543. * Returns an Octree of submeshes.
  18544. */
  18545. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18546. if (maxCapacity === void 0) { maxCapacity = 64; }
  18547. if (maxDepth === void 0) { maxDepth = 2; }
  18548. if (!this._submeshesOctree) {
  18549. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18550. }
  18551. this.computeWorldMatrix(true);
  18552. var boundingInfo = this.getBoundingInfo();
  18553. // Update octree
  18554. var bbox = boundingInfo.boundingBox;
  18555. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18556. return this._submeshesOctree;
  18557. };
  18558. // Collisions
  18559. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18560. this._generatePointsArray();
  18561. if (!this._positions) {
  18562. return this;
  18563. }
  18564. // Transformation
  18565. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18566. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18567. subMesh._lastColliderWorldVertices = [];
  18568. subMesh._trianglePlanes = [];
  18569. var start = subMesh.verticesStart;
  18570. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18571. for (var i = start; i < end; i++) {
  18572. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18573. }
  18574. }
  18575. // Collide
  18576. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18577. if (collider.collisionFound) {
  18578. collider.collidedMesh = this;
  18579. }
  18580. return this;
  18581. };
  18582. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18583. var subMeshes;
  18584. var len;
  18585. // Octrees
  18586. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18587. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18588. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18589. len = intersections.length;
  18590. subMeshes = intersections.data;
  18591. }
  18592. else {
  18593. subMeshes = this.subMeshes;
  18594. len = subMeshes.length;
  18595. }
  18596. for (var index = 0; index < len; index++) {
  18597. var subMesh = subMeshes[index];
  18598. // Bounding test
  18599. if (len > 1 && !subMesh._checkCollision(collider))
  18600. continue;
  18601. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18602. }
  18603. return this;
  18604. };
  18605. AbstractMesh.prototype._checkCollision = function (collider) {
  18606. // Bounding box test
  18607. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18608. return this;
  18609. // Transformation matrix
  18610. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18611. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18612. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18613. return this;
  18614. };
  18615. // Picking
  18616. AbstractMesh.prototype._generatePointsArray = function () {
  18617. return false;
  18618. };
  18619. /**
  18620. * Checks if the passed Ray intersects with the mesh.
  18621. * Returns an object PickingInfo.
  18622. */
  18623. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18624. var pickingInfo = new BABYLON.PickingInfo();
  18625. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18626. return pickingInfo;
  18627. }
  18628. if (!this._generatePointsArray()) {
  18629. return pickingInfo;
  18630. }
  18631. var intersectInfo = null;
  18632. // Octrees
  18633. var subMeshes;
  18634. var len;
  18635. if (this._submeshesOctree && this.useOctreeForPicking) {
  18636. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18637. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18638. len = intersections.length;
  18639. subMeshes = intersections.data;
  18640. }
  18641. else {
  18642. subMeshes = this.subMeshes;
  18643. len = subMeshes.length;
  18644. }
  18645. for (var index = 0; index < len; index++) {
  18646. var subMesh = subMeshes[index];
  18647. // Bounding test
  18648. if (len > 1 && !subMesh.canIntersects(ray))
  18649. continue;
  18650. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18651. if (currentIntersectInfo) {
  18652. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18653. intersectInfo = currentIntersectInfo;
  18654. intersectInfo.subMeshId = index;
  18655. if (fastCheck) {
  18656. break;
  18657. }
  18658. }
  18659. }
  18660. }
  18661. if (intersectInfo) {
  18662. // Get picked point
  18663. var world = this.getWorldMatrix();
  18664. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18665. var direction = ray.direction.clone();
  18666. direction = direction.scale(intersectInfo.distance);
  18667. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18668. var pickedPoint = worldOrigin.add(worldDirection);
  18669. // Return result
  18670. pickingInfo.hit = true;
  18671. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18672. pickingInfo.pickedPoint = pickedPoint;
  18673. pickingInfo.pickedMesh = this;
  18674. pickingInfo.bu = intersectInfo.bu || 0;
  18675. pickingInfo.bv = intersectInfo.bv || 0;
  18676. pickingInfo.faceId = intersectInfo.faceId;
  18677. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18678. return pickingInfo;
  18679. }
  18680. return pickingInfo;
  18681. };
  18682. /**
  18683. * Clones the mesh, used by the class Mesh.
  18684. * Just returns `null` for an AbstractMesh.
  18685. */
  18686. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18687. return null;
  18688. };
  18689. /**
  18690. * Disposes all the mesh submeshes.
  18691. * Returns the AbstractMesh.
  18692. */
  18693. AbstractMesh.prototype.releaseSubMeshes = function () {
  18694. if (this.subMeshes) {
  18695. while (this.subMeshes.length) {
  18696. this.subMeshes[0].dispose();
  18697. }
  18698. }
  18699. else {
  18700. this.subMeshes = new Array();
  18701. }
  18702. return this;
  18703. };
  18704. /**
  18705. * Releases resources associated with this abstract mesh.
  18706. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18707. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18708. */
  18709. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18710. var _this = this;
  18711. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18712. var index;
  18713. // Smart Array Retainers.
  18714. this.getScene().freeActiveMeshes();
  18715. this.getScene().freeRenderingGroups();
  18716. // Action manager
  18717. if (this.actionManager !== undefined && this.actionManager !== null) {
  18718. this.actionManager.dispose();
  18719. this.actionManager = null;
  18720. }
  18721. // Skeleton
  18722. this._skeleton = null;
  18723. // Physics
  18724. if (this.physicsImpostor) {
  18725. this.physicsImpostor.dispose();
  18726. }
  18727. // Intersections in progress
  18728. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18729. var other = this._intersectionsInProgress[index];
  18730. var pos = other._intersectionsInProgress.indexOf(this);
  18731. other._intersectionsInProgress.splice(pos, 1);
  18732. }
  18733. this._intersectionsInProgress = [];
  18734. // Lights
  18735. var lights = this.getScene().lights;
  18736. lights.forEach(function (light) {
  18737. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18738. if (meshIndex !== -1) {
  18739. light.includedOnlyMeshes.splice(meshIndex, 1);
  18740. }
  18741. meshIndex = light.excludedMeshes.indexOf(_this);
  18742. if (meshIndex !== -1) {
  18743. light.excludedMeshes.splice(meshIndex, 1);
  18744. }
  18745. // Shadow generators
  18746. var generator = light.getShadowGenerator();
  18747. if (generator) {
  18748. var shadowMap = generator.getShadowMap();
  18749. if (shadowMap && shadowMap.renderList) {
  18750. meshIndex = shadowMap.renderList.indexOf(_this);
  18751. if (meshIndex !== -1) {
  18752. shadowMap.renderList.splice(meshIndex, 1);
  18753. }
  18754. }
  18755. }
  18756. });
  18757. // Edges
  18758. if (this._edgesRenderer) {
  18759. this._edgesRenderer.dispose();
  18760. this._edgesRenderer = null;
  18761. }
  18762. // SubMeshes
  18763. if (this.getClassName() !== "InstancedMesh") {
  18764. this.releaseSubMeshes();
  18765. }
  18766. // Octree
  18767. var sceneOctree = this.getScene().selectionOctree;
  18768. if (sceneOctree !== undefined && sceneOctree !== null) {
  18769. var index = sceneOctree.dynamicContent.indexOf(this);
  18770. if (index !== -1) {
  18771. sceneOctree.dynamicContent.splice(index, 1);
  18772. }
  18773. }
  18774. // Query
  18775. var engine = this.getScene().getEngine();
  18776. if (this._occlusionQuery) {
  18777. this._isOcclusionQueryInProgress = false;
  18778. engine.deleteQuery(this._occlusionQuery);
  18779. this._occlusionQuery = null;
  18780. }
  18781. // Engine
  18782. engine.wipeCaches();
  18783. // Remove from scene
  18784. this.getScene().removeMesh(this);
  18785. if (disposeMaterialAndTextures) {
  18786. if (this.material) {
  18787. this.material.dispose(false, true);
  18788. }
  18789. }
  18790. if (!doNotRecurse) {
  18791. // Particles
  18792. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18793. if (this.getScene().particleSystems[index].emitter === this) {
  18794. this.getScene().particleSystems[index].dispose();
  18795. index--;
  18796. }
  18797. }
  18798. }
  18799. // facet data
  18800. if (this._facetDataEnabled) {
  18801. this.disableFacetData();
  18802. }
  18803. this.onAfterWorldMatrixUpdateObservable.clear();
  18804. this.onCollideObservable.clear();
  18805. this.onCollisionPositionChangeObservable.clear();
  18806. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18807. };
  18808. /**
  18809. * Adds the passed mesh as a child to the current mesh.
  18810. * Returns the AbstractMesh.
  18811. */
  18812. AbstractMesh.prototype.addChild = function (mesh) {
  18813. mesh.setParent(this);
  18814. return this;
  18815. };
  18816. /**
  18817. * Removes the passed mesh from the current mesh children list.
  18818. * Returns the AbstractMesh.
  18819. */
  18820. AbstractMesh.prototype.removeChild = function (mesh) {
  18821. mesh.setParent(null);
  18822. return this;
  18823. };
  18824. // Facet data
  18825. /**
  18826. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18827. * Returns the AbstractMesh.
  18828. */
  18829. AbstractMesh.prototype._initFacetData = function () {
  18830. if (!this._facetNormals) {
  18831. this._facetNormals = new Array();
  18832. }
  18833. if (!this._facetPositions) {
  18834. this._facetPositions = new Array();
  18835. }
  18836. if (!this._facetPartitioning) {
  18837. this._facetPartitioning = new Array();
  18838. }
  18839. this._facetNb = (this.getIndices().length / 3) | 0;
  18840. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18841. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18842. for (var f = 0; f < this._facetNb; f++) {
  18843. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18844. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18845. }
  18846. this._facetDataEnabled = true;
  18847. return this;
  18848. };
  18849. /**
  18850. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18851. * This method can be called within the render loop.
  18852. * 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.
  18853. * Returns the AbstractMesh.
  18854. */
  18855. AbstractMesh.prototype.updateFacetData = function () {
  18856. if (!this._facetDataEnabled) {
  18857. this._initFacetData();
  18858. }
  18859. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18860. var indices = this.getIndices();
  18861. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18862. var bInfo = this.getBoundingInfo();
  18863. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18864. // init arrays, matrix and sort function on first call
  18865. this._facetDepthSortEnabled = true;
  18866. if (indices instanceof Uint16Array) {
  18867. this._depthSortedIndices = new Uint16Array(indices);
  18868. }
  18869. else if (indices instanceof Uint32Array) {
  18870. this._depthSortedIndices = new Uint32Array(indices);
  18871. }
  18872. else {
  18873. var needs32bits = false;
  18874. for (var i = 0; i < indices.length; i++) {
  18875. if (indices[i] > 65535) {
  18876. needs32bits = true;
  18877. break;
  18878. }
  18879. }
  18880. if (needs32bits) {
  18881. this._depthSortedIndices = new Uint32Array(indices);
  18882. }
  18883. else {
  18884. this._depthSortedIndices = new Uint16Array(indices);
  18885. }
  18886. }
  18887. this._facetDepthSortFunction = function (f1, f2) {
  18888. return (f2.sqDistance - f1.sqDistance);
  18889. };
  18890. if (!this._facetDepthSortFrom) {
  18891. var camera = this.getScene().activeCamera;
  18892. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18893. }
  18894. this._depthSortedFacets = [];
  18895. for (var f = 0; f < this._facetNb; f++) {
  18896. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18897. this._depthSortedFacets.push(depthSortedFacet);
  18898. }
  18899. this._invertedMatrix = BABYLON.Matrix.Identity();
  18900. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18901. }
  18902. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18903. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18904. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18905. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18906. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18907. this._subDiv.max = this._partitioningSubdivisions;
  18908. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18909. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18910. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18911. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18912. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18913. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18914. // set the parameters for ComputeNormals()
  18915. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18916. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18917. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18918. this._facetParameters.bInfo = bInfo;
  18919. this._facetParameters.bbSize = this._bbSize;
  18920. this._facetParameters.subDiv = this._subDiv;
  18921. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18922. this._facetParameters.depthSort = this._facetDepthSort;
  18923. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18924. this.computeWorldMatrix(true);
  18925. this._worldMatrix.invertToRef(this._invertedMatrix);
  18926. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18927. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18928. }
  18929. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18930. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18931. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18932. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18933. var l = (this._depthSortedIndices.length / 3) | 0;
  18934. for (var f = 0; f < l; f++) {
  18935. var sind = this._depthSortedFacets[f].ind;
  18936. this._depthSortedIndices[f * 3] = indices[sind];
  18937. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18938. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18939. }
  18940. this.updateIndices(this._depthSortedIndices);
  18941. }
  18942. return this;
  18943. };
  18944. /**
  18945. * Returns the facetLocalNormals array.
  18946. * The normals are expressed in the mesh local space.
  18947. */
  18948. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18949. if (!this._facetNormals) {
  18950. this.updateFacetData();
  18951. }
  18952. return this._facetNormals;
  18953. };
  18954. /**
  18955. * Returns the facetLocalPositions array.
  18956. * The facet positions are expressed in the mesh local space.
  18957. */
  18958. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18959. if (!this._facetPositions) {
  18960. this.updateFacetData();
  18961. }
  18962. return this._facetPositions;
  18963. };
  18964. /**
  18965. * Returns the facetLocalPartioning array.
  18966. */
  18967. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18968. if (!this._facetPartitioning) {
  18969. this.updateFacetData();
  18970. }
  18971. return this._facetPartitioning;
  18972. };
  18973. /**
  18974. * Returns the i-th facet position in the world system.
  18975. * This method allocates a new Vector3 per call.
  18976. */
  18977. AbstractMesh.prototype.getFacetPosition = function (i) {
  18978. var pos = BABYLON.Vector3.Zero();
  18979. this.getFacetPositionToRef(i, pos);
  18980. return pos;
  18981. };
  18982. /**
  18983. * Sets the reference Vector3 with the i-th facet position in the world system.
  18984. * Returns the AbstractMesh.
  18985. */
  18986. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18987. var localPos = (this.getFacetLocalPositions())[i];
  18988. var world = this.getWorldMatrix();
  18989. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18990. return this;
  18991. };
  18992. /**
  18993. * Returns the i-th facet normal in the world system.
  18994. * This method allocates a new Vector3 per call.
  18995. */
  18996. AbstractMesh.prototype.getFacetNormal = function (i) {
  18997. var norm = BABYLON.Vector3.Zero();
  18998. this.getFacetNormalToRef(i, norm);
  18999. return norm;
  19000. };
  19001. /**
  19002. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19003. * Returns the AbstractMesh.
  19004. */
  19005. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19006. var localNorm = (this.getFacetLocalNormals())[i];
  19007. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19008. return this;
  19009. };
  19010. /**
  19011. * 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).
  19012. */
  19013. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19014. var bInfo = this.getBoundingInfo();
  19015. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19016. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19017. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19018. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19019. return null;
  19020. }
  19021. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19022. };
  19023. /**
  19024. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19025. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19026. * 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.
  19027. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19028. * 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.
  19029. */
  19030. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19031. if (checkFace === void 0) { checkFace = false; }
  19032. if (facing === void 0) { facing = true; }
  19033. var world = this.getWorldMatrix();
  19034. var invMat = BABYLON.Tmp.Matrix[5];
  19035. world.invertToRef(invMat);
  19036. var invVect = BABYLON.Tmp.Vector3[8];
  19037. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19038. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19039. if (projected) {
  19040. // tranform the local computed projected vector to world coordinates
  19041. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19042. }
  19043. return closest;
  19044. };
  19045. /**
  19046. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19047. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19048. * 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.
  19049. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19050. * 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.
  19051. */
  19052. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19053. if (checkFace === void 0) { checkFace = false; }
  19054. if (facing === void 0) { facing = true; }
  19055. var closest = null;
  19056. var tmpx = 0.0;
  19057. var tmpy = 0.0;
  19058. var tmpz = 0.0;
  19059. var d = 0.0; // tmp dot facet normal * facet position
  19060. var t0 = 0.0;
  19061. var projx = 0.0;
  19062. var projy = 0.0;
  19063. var projz = 0.0;
  19064. // Get all the facets in the same partitioning block than (x, y, z)
  19065. var facetPositions = this.getFacetLocalPositions();
  19066. var facetNormals = this.getFacetLocalNormals();
  19067. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19068. if (!facetsInBlock) {
  19069. return null;
  19070. }
  19071. // Get the closest facet to (x, y, z)
  19072. var shortest = Number.MAX_VALUE; // init distance vars
  19073. var tmpDistance = shortest;
  19074. var fib; // current facet in the block
  19075. var norm; // current facet normal
  19076. var p0; // current facet barycenter position
  19077. // loop on all the facets in the current partitioning block
  19078. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19079. fib = facetsInBlock[idx];
  19080. norm = facetNormals[fib];
  19081. p0 = facetPositions[fib];
  19082. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19083. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19084. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19085. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19086. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19087. projx = x + norm.x * t0;
  19088. projy = y + norm.y * t0;
  19089. projz = z + norm.z * t0;
  19090. tmpx = projx - x;
  19091. tmpy = projy - y;
  19092. tmpz = projz - z;
  19093. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19094. if (tmpDistance < shortest) {
  19095. shortest = tmpDistance;
  19096. closest = fib;
  19097. if (projected) {
  19098. projected.x = projx;
  19099. projected.y = projy;
  19100. projected.z = projz;
  19101. }
  19102. }
  19103. }
  19104. }
  19105. return closest;
  19106. };
  19107. /**
  19108. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19109. */
  19110. AbstractMesh.prototype.getFacetDataParameters = function () {
  19111. return this._facetParameters;
  19112. };
  19113. /**
  19114. * Disables the feature FacetData and frees the related memory.
  19115. * Returns the AbstractMesh.
  19116. */
  19117. AbstractMesh.prototype.disableFacetData = function () {
  19118. if (this._facetDataEnabled) {
  19119. this._facetDataEnabled = false;
  19120. this._facetPositions = new Array();
  19121. this._facetNormals = new Array();
  19122. this._facetPartitioning = new Array();
  19123. this._facetParameters = null;
  19124. this._depthSortedIndices = new Uint32Array(0);
  19125. }
  19126. return this;
  19127. };
  19128. /**
  19129. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19130. * Returns the mesh.
  19131. */
  19132. AbstractMesh.prototype.updateIndices = function (indices) {
  19133. return this;
  19134. };
  19135. /**
  19136. * The mesh Geometry. Actually used by the Mesh object.
  19137. * Returns a blank geometry object.
  19138. */
  19139. /**
  19140. * Creates new normals data for the mesh.
  19141. * @param updatable.
  19142. */
  19143. AbstractMesh.prototype.createNormals = function (updatable) {
  19144. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19145. var indices = this.getIndices();
  19146. var normals;
  19147. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19148. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19149. }
  19150. else {
  19151. normals = [];
  19152. }
  19153. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19154. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19155. };
  19156. /**
  19157. * Align the mesh with a normal.
  19158. * Returns the mesh.
  19159. */
  19160. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19161. if (!upDirection) {
  19162. upDirection = BABYLON.Axis.Y;
  19163. }
  19164. var axisX = BABYLON.Tmp.Vector3[0];
  19165. var axisZ = BABYLON.Tmp.Vector3[1];
  19166. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19167. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19168. if (this.rotationQuaternion) {
  19169. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19170. }
  19171. else {
  19172. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19173. }
  19174. return this;
  19175. };
  19176. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19177. var engine = this.getEngine();
  19178. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19179. this._isOccluded = false;
  19180. return;
  19181. }
  19182. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19183. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19184. if (isOcclusionQueryAvailable) {
  19185. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19186. this._isOcclusionQueryInProgress = false;
  19187. this._occlusionInternalRetryCounter = 0;
  19188. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19189. }
  19190. else {
  19191. this._occlusionInternalRetryCounter++;
  19192. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19193. this._isOcclusionQueryInProgress = false;
  19194. this._occlusionInternalRetryCounter = 0;
  19195. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19196. // if strict continue the last state of the object.
  19197. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19198. }
  19199. else {
  19200. return;
  19201. }
  19202. }
  19203. }
  19204. var scene = this.getScene();
  19205. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19206. if (!this._occlusionQuery) {
  19207. this._occlusionQuery = engine.createQuery();
  19208. }
  19209. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19210. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19211. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19212. this._isOcclusionQueryInProgress = true;
  19213. };
  19214. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19215. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19216. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19217. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19218. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19219. return AbstractMesh;
  19220. }(BABYLON.TransformNode));
  19221. BABYLON.AbstractMesh = AbstractMesh;
  19222. })(BABYLON || (BABYLON = {}));
  19223. //# sourceMappingURL=babylon.abstractMesh.js.map
  19224. "use strict";
  19225. var BABYLON;
  19226. (function (BABYLON) {
  19227. /**
  19228. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19229. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19230. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  19231. */
  19232. var Light = /** @class */ (function (_super) {
  19233. __extends(Light, _super);
  19234. /**
  19235. * Creates a Light object in the scene.
  19236. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19237. * @param name The firendly name of the light
  19238. * @param scene The scene the light belongs too
  19239. */
  19240. function Light(name, scene) {
  19241. var _this = _super.call(this, name, scene) || this;
  19242. /**
  19243. * Diffuse gives the basic color to an object.
  19244. */
  19245. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19246. /**
  19247. * Specular produces a highlight color on an object.
  19248. * Note: This is note affecting PBR materials.
  19249. */
  19250. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19251. /**
  19252. * Strength of the light.
  19253. * Note: By default it is define in the framework own unit.
  19254. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19255. */
  19256. _this.intensity = 1.0;
  19257. /**
  19258. * Defines how far from the source the light is impacting in scene units.
  19259. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19260. */
  19261. _this.range = Number.MAX_VALUE;
  19262. /**
  19263. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19264. * of light.
  19265. */
  19266. _this._photometricScale = 1.0;
  19267. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19268. _this._radius = 0.00001;
  19269. /**
  19270. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19271. * exceeding the number allowed of the materials.
  19272. */
  19273. _this.renderPriority = 0;
  19274. /**
  19275. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19276. * the current shadow generator.
  19277. */
  19278. _this.shadowEnabled = true;
  19279. _this._excludeWithLayerMask = 0;
  19280. _this._includeOnlyWithLayerMask = 0;
  19281. _this._lightmapMode = 0;
  19282. /**
  19283. * @ignore Internal use only.
  19284. */
  19285. _this._excludedMeshesIds = new Array();
  19286. /**
  19287. * @ignore Internal use only.
  19288. */
  19289. _this._includedOnlyMeshesIds = new Array();
  19290. _this.getScene().addLight(_this);
  19291. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19292. _this._buildUniformLayout();
  19293. _this.includedOnlyMeshes = new Array();
  19294. _this.excludedMeshes = new Array();
  19295. _this._resyncMeshes();
  19296. return _this;
  19297. }
  19298. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19299. /**
  19300. * If every light affecting the material is in this lightmapMode,
  19301. * material.lightmapTexture adds or multiplies
  19302. * (depends on material.useLightmapAsShadowmap)
  19303. * after every other light calculations.
  19304. */
  19305. get: function () {
  19306. return Light._LIGHTMAP_DEFAULT;
  19307. },
  19308. enumerable: true,
  19309. configurable: true
  19310. });
  19311. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19312. /**
  19313. * material.lightmapTexture as only diffuse lighting from this light
  19314. * adds only specular lighting from this light
  19315. * adds dynamic shadows
  19316. */
  19317. get: function () {
  19318. return Light._LIGHTMAP_SPECULAR;
  19319. },
  19320. enumerable: true,
  19321. configurable: true
  19322. });
  19323. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19324. /**
  19325. * material.lightmapTexture as only lighting
  19326. * no light calculation from this light
  19327. * only adds dynamic shadows from this light
  19328. */
  19329. get: function () {
  19330. return Light._LIGHTMAP_SHADOWSONLY;
  19331. },
  19332. enumerable: true,
  19333. configurable: true
  19334. });
  19335. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19336. /**
  19337. * Each light type uses the default quantity according to its type:
  19338. * point/spot lights use luminous intensity
  19339. * directional lights use illuminance
  19340. */
  19341. get: function () {
  19342. return Light._INTENSITYMODE_AUTOMATIC;
  19343. },
  19344. enumerable: true,
  19345. configurable: true
  19346. });
  19347. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19348. /**
  19349. * lumen (lm)
  19350. */
  19351. get: function () {
  19352. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19353. },
  19354. enumerable: true,
  19355. configurable: true
  19356. });
  19357. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19358. /**
  19359. * candela (lm/sr)
  19360. */
  19361. get: function () {
  19362. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19363. },
  19364. enumerable: true,
  19365. configurable: true
  19366. });
  19367. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19368. /**
  19369. * lux (lm/m^2)
  19370. */
  19371. get: function () {
  19372. return Light._INTENSITYMODE_ILLUMINANCE;
  19373. },
  19374. enumerable: true,
  19375. configurable: true
  19376. });
  19377. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19378. /**
  19379. * nit (cd/m^2)
  19380. */
  19381. get: function () {
  19382. return Light._INTENSITYMODE_LUMINANCE;
  19383. },
  19384. enumerable: true,
  19385. configurable: true
  19386. });
  19387. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19388. /**
  19389. * Light type const id of the point light.
  19390. */
  19391. get: function () {
  19392. return Light._LIGHTTYPEID_POINTLIGHT;
  19393. },
  19394. enumerable: true,
  19395. configurable: true
  19396. });
  19397. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19398. /**
  19399. * Light type const id of the directional light.
  19400. */
  19401. get: function () {
  19402. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19403. },
  19404. enumerable: true,
  19405. configurable: true
  19406. });
  19407. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19408. /**
  19409. * Light type const id of the spot light.
  19410. */
  19411. get: function () {
  19412. return Light._LIGHTTYPEID_SPOTLIGHT;
  19413. },
  19414. enumerable: true,
  19415. configurable: true
  19416. });
  19417. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19418. /**
  19419. * Light type const id of the hemispheric light.
  19420. */
  19421. get: function () {
  19422. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19423. },
  19424. enumerable: true,
  19425. configurable: true
  19426. });
  19427. Object.defineProperty(Light.prototype, "intensityMode", {
  19428. /**
  19429. * Gets the photometric scale used to interpret the intensity.
  19430. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19431. */
  19432. get: function () {
  19433. return this._intensityMode;
  19434. },
  19435. /**
  19436. * Sets the photometric scale used to interpret the intensity.
  19437. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19438. */
  19439. set: function (value) {
  19440. this._intensityMode = value;
  19441. this._computePhotometricScale();
  19442. },
  19443. enumerable: true,
  19444. configurable: true
  19445. });
  19446. ;
  19447. ;
  19448. Object.defineProperty(Light.prototype, "radius", {
  19449. /**
  19450. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19451. */
  19452. get: function () {
  19453. return this._radius;
  19454. },
  19455. /**
  19456. * sets the light radius used by PBR Materials to simulate soft area lights.
  19457. */
  19458. set: function (value) {
  19459. this._radius = value;
  19460. this._computePhotometricScale();
  19461. },
  19462. enumerable: true,
  19463. configurable: true
  19464. });
  19465. ;
  19466. ;
  19467. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19468. /**
  19469. * Gets the only meshes impacted by this light.
  19470. */
  19471. get: function () {
  19472. return this._includedOnlyMeshes;
  19473. },
  19474. /**
  19475. * Sets the only meshes impacted by this light.
  19476. */
  19477. set: function (value) {
  19478. this._includedOnlyMeshes = value;
  19479. this._hookArrayForIncludedOnly(value);
  19480. },
  19481. enumerable: true,
  19482. configurable: true
  19483. });
  19484. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19485. /**
  19486. * Gets the meshes not impacted by this light.
  19487. */
  19488. get: function () {
  19489. return this._excludedMeshes;
  19490. },
  19491. /**
  19492. * Sets the meshes not impacted by this light.
  19493. */
  19494. set: function (value) {
  19495. this._excludedMeshes = value;
  19496. this._hookArrayForExcluded(value);
  19497. },
  19498. enumerable: true,
  19499. configurable: true
  19500. });
  19501. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19502. /**
  19503. * Gets the layer id use to find what meshes are not impacted by the light.
  19504. * Inactive if 0
  19505. */
  19506. get: function () {
  19507. return this._excludeWithLayerMask;
  19508. },
  19509. /**
  19510. * Sets the layer id use to find what meshes are not impacted by the light.
  19511. * Inactive if 0
  19512. */
  19513. set: function (value) {
  19514. this._excludeWithLayerMask = value;
  19515. this._resyncMeshes();
  19516. },
  19517. enumerable: true,
  19518. configurable: true
  19519. });
  19520. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19521. /**
  19522. * Gets the layer id use to find what meshes are impacted by the light.
  19523. * Inactive if 0
  19524. */
  19525. get: function () {
  19526. return this._includeOnlyWithLayerMask;
  19527. },
  19528. /**
  19529. * Sets the layer id use to find what meshes are impacted by the light.
  19530. * Inactive if 0
  19531. */
  19532. set: function (value) {
  19533. this._includeOnlyWithLayerMask = value;
  19534. this._resyncMeshes();
  19535. },
  19536. enumerable: true,
  19537. configurable: true
  19538. });
  19539. Object.defineProperty(Light.prototype, "lightmapMode", {
  19540. /**
  19541. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19542. */
  19543. get: function () {
  19544. return this._lightmapMode;
  19545. },
  19546. /**
  19547. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19548. */
  19549. set: function (value) {
  19550. if (this._lightmapMode === value) {
  19551. return;
  19552. }
  19553. this._lightmapMode = value;
  19554. this._markMeshesAsLightDirty();
  19555. },
  19556. enumerable: true,
  19557. configurable: true
  19558. });
  19559. /**
  19560. * Returns the string "Light".
  19561. * @returns the class name
  19562. */
  19563. Light.prototype.getClassName = function () {
  19564. return "Light";
  19565. };
  19566. /**
  19567. * Converts the light information to a readable string for debug purpose.
  19568. * @param fullDetails Supports for multiple levels of logging within scene loading
  19569. * @returns the human readable light info
  19570. */
  19571. Light.prototype.toString = function (fullDetails) {
  19572. var ret = "Name: " + this.name;
  19573. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19574. if (this.animations) {
  19575. for (var i = 0; i < this.animations.length; i++) {
  19576. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19577. }
  19578. }
  19579. if (fullDetails) {
  19580. }
  19581. return ret;
  19582. };
  19583. /**
  19584. * Set the enabled state of this node.
  19585. * @param value - the new enabled state
  19586. * @see isEnabled
  19587. */
  19588. Light.prototype.setEnabled = function (value) {
  19589. _super.prototype.setEnabled.call(this, value);
  19590. this._resyncMeshes();
  19591. };
  19592. /**
  19593. * Returns the Light associated shadow generator if any.
  19594. * @return the associated shadow generator.
  19595. */
  19596. Light.prototype.getShadowGenerator = function () {
  19597. return this._shadowGenerator;
  19598. };
  19599. /**
  19600. * Returns a Vector3, the absolute light position in the World.
  19601. * @returns the world space position of the light
  19602. */
  19603. Light.prototype.getAbsolutePosition = function () {
  19604. return BABYLON.Vector3.Zero();
  19605. };
  19606. /**
  19607. * Specifies if the light will affect the passed mesh.
  19608. * @param mesh The mesh to test against the light
  19609. * @return true the mesh is affected otherwise, false.
  19610. */
  19611. Light.prototype.canAffectMesh = function (mesh) {
  19612. if (!mesh) {
  19613. return true;
  19614. }
  19615. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19616. return false;
  19617. }
  19618. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19619. return false;
  19620. }
  19621. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19622. return false;
  19623. }
  19624. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19625. return false;
  19626. }
  19627. return true;
  19628. };
  19629. /**
  19630. * Computes and Returns the light World matrix.
  19631. * @returns the world matrix
  19632. */
  19633. Light.prototype.getWorldMatrix = function () {
  19634. this._currentRenderId = this.getScene().getRenderId();
  19635. var worldMatrix = this._getWorldMatrix();
  19636. if (this.parent && this.parent.getWorldMatrix) {
  19637. if (!this._parentedWorldMatrix) {
  19638. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19639. }
  19640. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19641. this._markSyncedWithParent();
  19642. return this._parentedWorldMatrix;
  19643. }
  19644. return worldMatrix;
  19645. };
  19646. /**
  19647. * Sort function to order lights for rendering.
  19648. * @param a First Light object to compare to second.
  19649. * @param b Second Light object to compare first.
  19650. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19651. */
  19652. Light.CompareLightsPriority = function (a, b) {
  19653. //shadow-casting lights have priority over non-shadow-casting lights
  19654. //the renderPrioirty is a secondary sort criterion
  19655. if (a.shadowEnabled !== b.shadowEnabled) {
  19656. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19657. }
  19658. return b.renderPriority - a.renderPriority;
  19659. };
  19660. /**
  19661. * Releases resources associated with this node.
  19662. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19663. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19664. */
  19665. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19666. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19667. if (this._shadowGenerator) {
  19668. this._shadowGenerator.dispose();
  19669. this._shadowGenerator = null;
  19670. }
  19671. // Animations
  19672. this.getScene().stopAnimation(this);
  19673. // Remove from meshes
  19674. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19675. var mesh = _a[_i];
  19676. mesh._removeLightSource(this);
  19677. }
  19678. this._uniformBuffer.dispose();
  19679. // Remove from scene
  19680. this.getScene().removeLight(this);
  19681. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19682. };
  19683. /**
  19684. * Returns the light type ID (integer).
  19685. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19686. */
  19687. Light.prototype.getTypeID = function () {
  19688. return 0;
  19689. };
  19690. /**
  19691. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19692. * @returns the scaled intensity in intensity mode unit
  19693. */
  19694. Light.prototype.getScaledIntensity = function () {
  19695. return this._photometricScale * this.intensity;
  19696. };
  19697. /**
  19698. * Returns a new Light object, named "name", from the current one.
  19699. * @param name The name of the cloned light
  19700. * @returns the new created light
  19701. */
  19702. Light.prototype.clone = function (name) {
  19703. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19704. if (!constructor) {
  19705. return null;
  19706. }
  19707. return BABYLON.SerializationHelper.Clone(constructor, this);
  19708. };
  19709. /**
  19710. * Serializes the current light into a Serialization object.
  19711. * @returns the serialized object.
  19712. */
  19713. Light.prototype.serialize = function () {
  19714. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19715. // Type
  19716. serializationObject.type = this.getTypeID();
  19717. // Parent
  19718. if (this.parent) {
  19719. serializationObject.parentId = this.parent.id;
  19720. }
  19721. // Inclusion / exclusions
  19722. if (this.excludedMeshes.length > 0) {
  19723. serializationObject.excludedMeshesIds = [];
  19724. this.excludedMeshes.forEach(function (mesh) {
  19725. serializationObject.excludedMeshesIds.push(mesh.id);
  19726. });
  19727. }
  19728. if (this.includedOnlyMeshes.length > 0) {
  19729. serializationObject.includedOnlyMeshesIds = [];
  19730. this.includedOnlyMeshes.forEach(function (mesh) {
  19731. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19732. });
  19733. }
  19734. // Animations
  19735. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19736. serializationObject.ranges = this.serializeAnimationRanges();
  19737. return serializationObject;
  19738. };
  19739. /**
  19740. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19741. * This new light is named "name" and added to the passed scene.
  19742. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19743. * @param name The friendly name of the light
  19744. * @param scene The scene the new light will belong to
  19745. * @returns the constructor function
  19746. */
  19747. Light.GetConstructorFromName = function (type, name, scene) {
  19748. switch (type) {
  19749. case 0:
  19750. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19751. case 1:
  19752. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19753. case 2:
  19754. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19755. case 3:
  19756. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19757. }
  19758. return null;
  19759. };
  19760. /**
  19761. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19762. * @param parsedLight The JSON representation of the light
  19763. * @param scene The scene to create the parsed light in
  19764. * @returns the created light after parsing
  19765. */
  19766. Light.Parse = function (parsedLight, scene) {
  19767. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19768. if (!constructor) {
  19769. return null;
  19770. }
  19771. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19772. // Inclusion / exclusions
  19773. if (parsedLight.excludedMeshesIds) {
  19774. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19775. }
  19776. if (parsedLight.includedOnlyMeshesIds) {
  19777. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19778. }
  19779. // Parent
  19780. if (parsedLight.parentId) {
  19781. light._waitingParentId = parsedLight.parentId;
  19782. }
  19783. // Animations
  19784. if (parsedLight.animations) {
  19785. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19786. var parsedAnimation = parsedLight.animations[animationIndex];
  19787. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19788. }
  19789. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19790. }
  19791. if (parsedLight.autoAnimate) {
  19792. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19793. }
  19794. return light;
  19795. };
  19796. Light.prototype._hookArrayForExcluded = function (array) {
  19797. var _this = this;
  19798. var oldPush = array.push;
  19799. array.push = function () {
  19800. var items = [];
  19801. for (var _i = 0; _i < arguments.length; _i++) {
  19802. items[_i] = arguments[_i];
  19803. }
  19804. var result = oldPush.apply(array, items);
  19805. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19806. var item = items_1[_a];
  19807. item._resyncLighSource(_this);
  19808. }
  19809. return result;
  19810. };
  19811. var oldSplice = array.splice;
  19812. array.splice = function (index, deleteCount) {
  19813. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19814. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19815. var item = deleted_1[_i];
  19816. item._resyncLighSource(_this);
  19817. }
  19818. return deleted;
  19819. };
  19820. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19821. var item = array_1[_i];
  19822. item._resyncLighSource(this);
  19823. }
  19824. };
  19825. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19826. var _this = this;
  19827. var oldPush = array.push;
  19828. array.push = function () {
  19829. var items = [];
  19830. for (var _i = 0; _i < arguments.length; _i++) {
  19831. items[_i] = arguments[_i];
  19832. }
  19833. var result = oldPush.apply(array, items);
  19834. _this._resyncMeshes();
  19835. return result;
  19836. };
  19837. var oldSplice = array.splice;
  19838. array.splice = function (index, deleteCount) {
  19839. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19840. _this._resyncMeshes();
  19841. return deleted;
  19842. };
  19843. this._resyncMeshes();
  19844. };
  19845. Light.prototype._resyncMeshes = function () {
  19846. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19847. var mesh = _a[_i];
  19848. mesh._resyncLighSource(this);
  19849. }
  19850. };
  19851. /**
  19852. * Forces the meshes to update their light related information in their rendering used effects
  19853. * @ignore Internal Use Only
  19854. */
  19855. Light.prototype._markMeshesAsLightDirty = function () {
  19856. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19857. var mesh = _a[_i];
  19858. if (mesh._lightSources.indexOf(this) !== -1) {
  19859. mesh._markSubMeshesAsLightDirty();
  19860. }
  19861. }
  19862. };
  19863. /**
  19864. * Recomputes the cached photometric scale if needed.
  19865. */
  19866. Light.prototype._computePhotometricScale = function () {
  19867. this._photometricScale = this._getPhotometricScale();
  19868. this.getScene().resetCachedMaterial();
  19869. };
  19870. /**
  19871. * Returns the Photometric Scale according to the light type and intensity mode.
  19872. */
  19873. Light.prototype._getPhotometricScale = function () {
  19874. var photometricScale = 0.0;
  19875. var lightTypeID = this.getTypeID();
  19876. //get photometric mode
  19877. var photometricMode = this.intensityMode;
  19878. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19879. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19880. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19881. }
  19882. else {
  19883. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19884. }
  19885. }
  19886. //compute photometric scale
  19887. switch (lightTypeID) {
  19888. case Light.LIGHTTYPEID_POINTLIGHT:
  19889. case Light.LIGHTTYPEID_SPOTLIGHT:
  19890. switch (photometricMode) {
  19891. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19892. photometricScale = 1.0 / (4.0 * Math.PI);
  19893. break;
  19894. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19895. photometricScale = 1.0;
  19896. break;
  19897. case Light.INTENSITYMODE_LUMINANCE:
  19898. photometricScale = this.radius * this.radius;
  19899. break;
  19900. }
  19901. break;
  19902. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19903. switch (photometricMode) {
  19904. case Light.INTENSITYMODE_ILLUMINANCE:
  19905. photometricScale = 1.0;
  19906. break;
  19907. case Light.INTENSITYMODE_LUMINANCE:
  19908. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19909. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19910. var apexAngleRadians = this.radius;
  19911. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19912. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19913. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19914. photometricScale = solidAngle;
  19915. break;
  19916. }
  19917. break;
  19918. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19919. // No fall off in hemisperic light.
  19920. photometricScale = 1.0;
  19921. break;
  19922. }
  19923. return photometricScale;
  19924. };
  19925. /**
  19926. * Reorder the light in the scene according to their defined priority.
  19927. * @ignore Internal Use Only
  19928. */
  19929. Light.prototype._reorderLightsInScene = function () {
  19930. var scene = this.getScene();
  19931. if (this._renderPriority != 0) {
  19932. scene.requireLightSorting = true;
  19933. }
  19934. this.getScene().sortLightsByPriority();
  19935. };
  19936. //lightmapMode Consts
  19937. Light._LIGHTMAP_DEFAULT = 0;
  19938. Light._LIGHTMAP_SPECULAR = 1;
  19939. Light._LIGHTMAP_SHADOWSONLY = 2;
  19940. // Intensity Mode Consts
  19941. Light._INTENSITYMODE_AUTOMATIC = 0;
  19942. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19943. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19944. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19945. Light._INTENSITYMODE_LUMINANCE = 4;
  19946. // Light types ids const.
  19947. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19948. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19949. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19950. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19951. __decorate([
  19952. BABYLON.serializeAsColor3()
  19953. ], Light.prototype, "diffuse", void 0);
  19954. __decorate([
  19955. BABYLON.serializeAsColor3()
  19956. ], Light.prototype, "specular", void 0);
  19957. __decorate([
  19958. BABYLON.serialize()
  19959. ], Light.prototype, "intensity", void 0);
  19960. __decorate([
  19961. BABYLON.serialize()
  19962. ], Light.prototype, "range", void 0);
  19963. __decorate([
  19964. BABYLON.serialize()
  19965. ], Light.prototype, "intensityMode", null);
  19966. __decorate([
  19967. BABYLON.serialize()
  19968. ], Light.prototype, "radius", null);
  19969. __decorate([
  19970. BABYLON.serialize()
  19971. ], Light.prototype, "_renderPriority", void 0);
  19972. __decorate([
  19973. BABYLON.expandToProperty("_reorderLightsInScene")
  19974. ], Light.prototype, "renderPriority", void 0);
  19975. __decorate([
  19976. BABYLON.serialize()
  19977. ], Light.prototype, "shadowEnabled", void 0);
  19978. __decorate([
  19979. BABYLON.serialize("excludeWithLayerMask")
  19980. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19981. __decorate([
  19982. BABYLON.serialize("includeOnlyWithLayerMask")
  19983. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19984. __decorate([
  19985. BABYLON.serialize("lightmapMode")
  19986. ], Light.prototype, "_lightmapMode", void 0);
  19987. return Light;
  19988. }(BABYLON.Node));
  19989. BABYLON.Light = Light;
  19990. })(BABYLON || (BABYLON = {}));
  19991. //# sourceMappingURL=babylon.light.js.map
  19992. "use strict";
  19993. var BABYLON;
  19994. (function (BABYLON) {
  19995. var Camera = /** @class */ (function (_super) {
  19996. __extends(Camera, _super);
  19997. function Camera(name, position, scene) {
  19998. var _this = _super.call(this, name, scene) || this;
  19999. /**
  20000. * The vector the camera should consider as up.
  20001. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20002. */
  20003. _this.upVector = BABYLON.Vector3.Up();
  20004. _this.orthoLeft = null;
  20005. _this.orthoRight = null;
  20006. _this.orthoBottom = null;
  20007. _this.orthoTop = null;
  20008. /**
  20009. * FOV is set in Radians. (default is 0.8)
  20010. */
  20011. _this.fov = 0.8;
  20012. _this.minZ = 1;
  20013. _this.maxZ = 10000.0;
  20014. _this.inertia = 0.9;
  20015. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20016. _this.isIntermediate = false;
  20017. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20018. /**
  20019. * Restricts the camera to viewing objects with the same layerMask.
  20020. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20021. */
  20022. _this.layerMask = 0x0FFFFFFF;
  20023. /**
  20024. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20025. */
  20026. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20027. // Camera rig members
  20028. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20029. _this._rigCameras = new Array();
  20030. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20031. _this._skipRendering = false;
  20032. _this.customRenderTargets = new Array();
  20033. // Observables
  20034. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20035. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20036. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20037. _this.onRestoreStateObservable = new BABYLON.Observable();
  20038. // Cache
  20039. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20040. _this._projectionMatrix = new BABYLON.Matrix();
  20041. _this._doNotComputeProjectionMatrix = false;
  20042. _this._postProcesses = new Array();
  20043. _this._transformMatrix = BABYLON.Matrix.Zero();
  20044. _this._activeMeshes = new BABYLON.SmartArray(256);
  20045. _this._globalPosition = BABYLON.Vector3.Zero();
  20046. _this._refreshFrustumPlanes = true;
  20047. _this.getScene().addCamera(_this);
  20048. if (!_this.getScene().activeCamera) {
  20049. _this.getScene().activeCamera = _this;
  20050. }
  20051. _this.position = position;
  20052. return _this;
  20053. }
  20054. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20055. get: function () {
  20056. return Camera._PERSPECTIVE_CAMERA;
  20057. },
  20058. enumerable: true,
  20059. configurable: true
  20060. });
  20061. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20062. get: function () {
  20063. return Camera._ORTHOGRAPHIC_CAMERA;
  20064. },
  20065. enumerable: true,
  20066. configurable: true
  20067. });
  20068. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20069. /**
  20070. * This is the default FOV mode for perspective cameras.
  20071. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20072. *
  20073. */
  20074. get: function () {
  20075. return Camera._FOVMODE_VERTICAL_FIXED;
  20076. },
  20077. enumerable: true,
  20078. configurable: true
  20079. });
  20080. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20081. /**
  20082. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20083. *
  20084. */
  20085. get: function () {
  20086. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20087. },
  20088. enumerable: true,
  20089. configurable: true
  20090. });
  20091. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20092. get: function () {
  20093. return Camera._RIG_MODE_NONE;
  20094. },
  20095. enumerable: true,
  20096. configurable: true
  20097. });
  20098. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20099. get: function () {
  20100. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20101. },
  20102. enumerable: true,
  20103. configurable: true
  20104. });
  20105. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20106. get: function () {
  20107. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20108. },
  20109. enumerable: true,
  20110. configurable: true
  20111. });
  20112. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20113. get: function () {
  20114. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20115. },
  20116. enumerable: true,
  20117. configurable: true
  20118. });
  20119. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20120. get: function () {
  20121. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20122. },
  20123. enumerable: true,
  20124. configurable: true
  20125. });
  20126. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20127. get: function () {
  20128. return Camera._RIG_MODE_VR;
  20129. },
  20130. enumerable: true,
  20131. configurable: true
  20132. });
  20133. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20134. get: function () {
  20135. return Camera._RIG_MODE_WEBVR;
  20136. },
  20137. enumerable: true,
  20138. configurable: true
  20139. });
  20140. /**
  20141. * Store current camera state (fov, position, etc..)
  20142. */
  20143. Camera.prototype.storeState = function () {
  20144. this._stateStored = true;
  20145. this._storedFov = this.fov;
  20146. return this;
  20147. };
  20148. /**
  20149. * Restores the camera state values if it has been stored. You must call storeState() first
  20150. */
  20151. Camera.prototype._restoreStateValues = function () {
  20152. if (!this._stateStored) {
  20153. return false;
  20154. }
  20155. this.fov = this._storedFov;
  20156. return true;
  20157. };
  20158. /**
  20159. * Restored camera state. You must call storeState() first
  20160. */
  20161. Camera.prototype.restoreState = function () {
  20162. if (this._restoreStateValues()) {
  20163. this.onRestoreStateObservable.notifyObservers(this);
  20164. return true;
  20165. }
  20166. return false;
  20167. };
  20168. Camera.prototype.getClassName = function () {
  20169. return "Camera";
  20170. };
  20171. /**
  20172. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20173. */
  20174. Camera.prototype.toString = function (fullDetails) {
  20175. var ret = "Name: " + this.name;
  20176. ret += ", type: " + this.getClassName();
  20177. if (this.animations) {
  20178. for (var i = 0; i < this.animations.length; i++) {
  20179. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20180. }
  20181. }
  20182. if (fullDetails) {
  20183. }
  20184. return ret;
  20185. };
  20186. Object.defineProperty(Camera.prototype, "globalPosition", {
  20187. get: function () {
  20188. return this._globalPosition;
  20189. },
  20190. enumerable: true,
  20191. configurable: true
  20192. });
  20193. Camera.prototype.getActiveMeshes = function () {
  20194. return this._activeMeshes;
  20195. };
  20196. Camera.prototype.isActiveMesh = function (mesh) {
  20197. return (this._activeMeshes.indexOf(mesh) !== -1);
  20198. };
  20199. //Cache
  20200. Camera.prototype._initCache = function () {
  20201. _super.prototype._initCache.call(this);
  20202. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20203. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20204. this._cache.mode = undefined;
  20205. this._cache.minZ = undefined;
  20206. this._cache.maxZ = undefined;
  20207. this._cache.fov = undefined;
  20208. this._cache.fovMode = undefined;
  20209. this._cache.aspectRatio = undefined;
  20210. this._cache.orthoLeft = undefined;
  20211. this._cache.orthoRight = undefined;
  20212. this._cache.orthoBottom = undefined;
  20213. this._cache.orthoTop = undefined;
  20214. this._cache.renderWidth = undefined;
  20215. this._cache.renderHeight = undefined;
  20216. };
  20217. Camera.prototype._updateCache = function (ignoreParentClass) {
  20218. if (!ignoreParentClass) {
  20219. _super.prototype._updateCache.call(this);
  20220. }
  20221. this._cache.position.copyFrom(this.position);
  20222. this._cache.upVector.copyFrom(this.upVector);
  20223. };
  20224. // Synchronized
  20225. Camera.prototype._isSynchronized = function () {
  20226. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20227. };
  20228. Camera.prototype._isSynchronizedViewMatrix = function () {
  20229. if (!_super.prototype._isSynchronized.call(this))
  20230. return false;
  20231. return this._cache.position.equals(this.position)
  20232. && this._cache.upVector.equals(this.upVector)
  20233. && this.isSynchronizedWithParent();
  20234. };
  20235. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20236. var check = this._cache.mode === this.mode
  20237. && this._cache.minZ === this.minZ
  20238. && this._cache.maxZ === this.maxZ;
  20239. if (!check) {
  20240. return false;
  20241. }
  20242. var engine = this.getEngine();
  20243. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20244. check = this._cache.fov === this.fov
  20245. && this._cache.fovMode === this.fovMode
  20246. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20247. }
  20248. else {
  20249. check = this._cache.orthoLeft === this.orthoLeft
  20250. && this._cache.orthoRight === this.orthoRight
  20251. && this._cache.orthoBottom === this.orthoBottom
  20252. && this._cache.orthoTop === this.orthoTop
  20253. && this._cache.renderWidth === engine.getRenderWidth()
  20254. && this._cache.renderHeight === engine.getRenderHeight();
  20255. }
  20256. return check;
  20257. };
  20258. // Controls
  20259. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20260. };
  20261. Camera.prototype.detachControl = function (element) {
  20262. };
  20263. Camera.prototype.update = function () {
  20264. this._checkInputs();
  20265. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20266. this._updateRigCameras();
  20267. }
  20268. };
  20269. Camera.prototype._checkInputs = function () {
  20270. this.onAfterCheckInputsObservable.notifyObservers(this);
  20271. };
  20272. Object.defineProperty(Camera.prototype, "rigCameras", {
  20273. get: function () {
  20274. return this._rigCameras;
  20275. },
  20276. enumerable: true,
  20277. configurable: true
  20278. });
  20279. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20280. get: function () {
  20281. return this._rigPostProcess;
  20282. },
  20283. enumerable: true,
  20284. configurable: true
  20285. });
  20286. /**
  20287. * Internal, gets the first post proces.
  20288. * @returns the first post process to be run on this camera.
  20289. */
  20290. Camera.prototype._getFirstPostProcess = function () {
  20291. for (var pp in this._postProcesses) {
  20292. if (this._postProcesses[pp] !== null) {
  20293. return this._postProcesses[pp];
  20294. }
  20295. }
  20296. return null;
  20297. };
  20298. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20299. // invalidate framebuffer
  20300. var firstPostProcess = this._getFirstPostProcess();
  20301. if (firstPostProcess) {
  20302. firstPostProcess.markTextureDirty();
  20303. }
  20304. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20305. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20306. var cam = this._rigCameras[i];
  20307. var rigPostProcess = cam._rigPostProcess;
  20308. // for VR rig, there does not have to be a post process
  20309. if (rigPostProcess) {
  20310. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20311. if (isPass) {
  20312. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20313. cam.isIntermediate = this._postProcesses.length === 0;
  20314. }
  20315. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20316. rigPostProcess.markTextureDirty();
  20317. }
  20318. else {
  20319. cam._postProcesses = this._postProcesses.slice(0);
  20320. }
  20321. }
  20322. };
  20323. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20324. if (insertAt === void 0) { insertAt = null; }
  20325. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20326. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20327. return 0;
  20328. }
  20329. if (insertAt == null || insertAt < 0) {
  20330. this._postProcesses.push(postProcess);
  20331. }
  20332. else if (this._postProcesses[insertAt] === null) {
  20333. this._postProcesses[insertAt] = postProcess;
  20334. }
  20335. else {
  20336. this._postProcesses.splice(insertAt, 0, postProcess);
  20337. }
  20338. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20339. return this._postProcesses.indexOf(postProcess);
  20340. };
  20341. Camera.prototype.detachPostProcess = function (postProcess) {
  20342. var idx = this._postProcesses.indexOf(postProcess);
  20343. if (idx !== -1) {
  20344. this._postProcesses[idx] = null;
  20345. }
  20346. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20347. };
  20348. Camera.prototype.getWorldMatrix = function () {
  20349. if (!this._worldMatrix) {
  20350. this._worldMatrix = BABYLON.Matrix.Identity();
  20351. }
  20352. var viewMatrix = this.getViewMatrix();
  20353. viewMatrix.invertToRef(this._worldMatrix);
  20354. return this._worldMatrix;
  20355. };
  20356. Camera.prototype._getViewMatrix = function () {
  20357. return BABYLON.Matrix.Identity();
  20358. };
  20359. Camera.prototype.getViewMatrix = function (force) {
  20360. if (!force && this._isSynchronizedViewMatrix()) {
  20361. return this._computedViewMatrix;
  20362. }
  20363. this.updateCache();
  20364. this._computedViewMatrix = this._getViewMatrix();
  20365. this._currentRenderId = this.getScene().getRenderId();
  20366. this._refreshFrustumPlanes = true;
  20367. if (!this.parent || !this.parent.getWorldMatrix) {
  20368. this._globalPosition.copyFrom(this.position);
  20369. }
  20370. else {
  20371. if (!this._worldMatrix) {
  20372. this._worldMatrix = BABYLON.Matrix.Identity();
  20373. }
  20374. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20375. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20376. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20377. this._computedViewMatrix.invert();
  20378. this._markSyncedWithParent();
  20379. }
  20380. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20381. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20382. }
  20383. this.onViewMatrixChangedObservable.notifyObservers(this);
  20384. return this._computedViewMatrix;
  20385. };
  20386. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20387. this._doNotComputeProjectionMatrix = true;
  20388. if (projection !== undefined) {
  20389. this._projectionMatrix = projection;
  20390. }
  20391. };
  20392. ;
  20393. Camera.prototype.unfreezeProjectionMatrix = function () {
  20394. this._doNotComputeProjectionMatrix = false;
  20395. };
  20396. ;
  20397. Camera.prototype.getProjectionMatrix = function (force) {
  20398. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20399. return this._projectionMatrix;
  20400. }
  20401. // Cache
  20402. this._cache.mode = this.mode;
  20403. this._cache.minZ = this.minZ;
  20404. this._cache.maxZ = this.maxZ;
  20405. // Matrix
  20406. this._refreshFrustumPlanes = true;
  20407. var engine = this.getEngine();
  20408. var scene = this.getScene();
  20409. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20410. this._cache.fov = this.fov;
  20411. this._cache.fovMode = this.fovMode;
  20412. this._cache.aspectRatio = engine.getAspectRatio(this);
  20413. if (this.minZ <= 0) {
  20414. this.minZ = 0.1;
  20415. }
  20416. if (scene.useRightHandedSystem) {
  20417. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20418. }
  20419. else {
  20420. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20421. }
  20422. }
  20423. else {
  20424. var halfWidth = engine.getRenderWidth() / 2.0;
  20425. var halfHeight = engine.getRenderHeight() / 2.0;
  20426. if (scene.useRightHandedSystem) {
  20427. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20428. }
  20429. else {
  20430. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20431. }
  20432. this._cache.orthoLeft = this.orthoLeft;
  20433. this._cache.orthoRight = this.orthoRight;
  20434. this._cache.orthoBottom = this.orthoBottom;
  20435. this._cache.orthoTop = this.orthoTop;
  20436. this._cache.renderWidth = engine.getRenderWidth();
  20437. this._cache.renderHeight = engine.getRenderHeight();
  20438. }
  20439. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20440. return this._projectionMatrix;
  20441. };
  20442. Camera.prototype.getTranformationMatrix = function () {
  20443. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20444. return this._transformMatrix;
  20445. };
  20446. Camera.prototype.updateFrustumPlanes = function () {
  20447. if (!this._refreshFrustumPlanes) {
  20448. return;
  20449. }
  20450. this.getTranformationMatrix();
  20451. if (!this._frustumPlanes) {
  20452. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20453. }
  20454. else {
  20455. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20456. }
  20457. this._refreshFrustumPlanes = false;
  20458. };
  20459. Camera.prototype.isInFrustum = function (target) {
  20460. this.updateFrustumPlanes();
  20461. return target.isInFrustum(this._frustumPlanes);
  20462. };
  20463. Camera.prototype.isCompletelyInFrustum = function (target) {
  20464. this.updateFrustumPlanes();
  20465. return target.isCompletelyInFrustum(this._frustumPlanes);
  20466. };
  20467. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20468. if (length === void 0) { length = 100; }
  20469. if (!transform) {
  20470. transform = this.getWorldMatrix();
  20471. }
  20472. if (!origin) {
  20473. origin = this.position;
  20474. }
  20475. var forward = new BABYLON.Vector3(0, 0, 1);
  20476. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20477. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20478. return new BABYLON.Ray(origin, direction, length);
  20479. };
  20480. /**
  20481. * Releases resources associated with this node.
  20482. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20483. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20484. */
  20485. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20486. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20487. // Observables
  20488. this.onViewMatrixChangedObservable.clear();
  20489. this.onProjectionMatrixChangedObservable.clear();
  20490. this.onAfterCheckInputsObservable.clear();
  20491. this.onRestoreStateObservable.clear();
  20492. // Inputs
  20493. if (this.inputs) {
  20494. this.inputs.clear();
  20495. }
  20496. // Animations
  20497. this.getScene().stopAnimation(this);
  20498. // Remove from scene
  20499. this.getScene().removeCamera(this);
  20500. while (this._rigCameras.length > 0) {
  20501. var camera = this._rigCameras.pop();
  20502. if (camera) {
  20503. camera.dispose();
  20504. }
  20505. }
  20506. // Postprocesses
  20507. if (this._rigPostProcess) {
  20508. this._rigPostProcess.dispose(this);
  20509. this._rigPostProcess = null;
  20510. this._postProcesses = [];
  20511. }
  20512. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20513. this._rigPostProcess = null;
  20514. this._postProcesses = [];
  20515. }
  20516. else {
  20517. var i = this._postProcesses.length;
  20518. while (--i >= 0) {
  20519. var postProcess = this._postProcesses[i];
  20520. if (postProcess) {
  20521. postProcess.dispose(this);
  20522. }
  20523. }
  20524. }
  20525. // Render targets
  20526. var i = this.customRenderTargets.length;
  20527. while (--i >= 0) {
  20528. this.customRenderTargets[i].dispose();
  20529. }
  20530. this.customRenderTargets = [];
  20531. // Active Meshes
  20532. this._activeMeshes.dispose();
  20533. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20534. };
  20535. Object.defineProperty(Camera.prototype, "leftCamera", {
  20536. // ---- Camera rigs section ----
  20537. get: function () {
  20538. if (this._rigCameras.length < 1) {
  20539. return null;
  20540. }
  20541. return this._rigCameras[0];
  20542. },
  20543. enumerable: true,
  20544. configurable: true
  20545. });
  20546. Object.defineProperty(Camera.prototype, "rightCamera", {
  20547. get: function () {
  20548. if (this._rigCameras.length < 2) {
  20549. return null;
  20550. }
  20551. return this._rigCameras[1];
  20552. },
  20553. enumerable: true,
  20554. configurable: true
  20555. });
  20556. Camera.prototype.getLeftTarget = function () {
  20557. if (this._rigCameras.length < 1) {
  20558. return null;
  20559. }
  20560. return this._rigCameras[0].getTarget();
  20561. };
  20562. Camera.prototype.getRightTarget = function () {
  20563. if (this._rigCameras.length < 2) {
  20564. return null;
  20565. }
  20566. return this._rigCameras[1].getTarget();
  20567. };
  20568. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20569. if (this.cameraRigMode === mode) {
  20570. return;
  20571. }
  20572. while (this._rigCameras.length > 0) {
  20573. var camera = this._rigCameras.pop();
  20574. if (camera) {
  20575. camera.dispose();
  20576. }
  20577. }
  20578. this.cameraRigMode = mode;
  20579. this._cameraRigParams = {};
  20580. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20581. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20582. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20583. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20584. // create the rig cameras, unless none
  20585. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20586. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20587. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20588. if (leftCamera && rightCamera) {
  20589. this._rigCameras.push(leftCamera);
  20590. this._rigCameras.push(rightCamera);
  20591. }
  20592. }
  20593. switch (this.cameraRigMode) {
  20594. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20595. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20596. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20597. break;
  20598. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20599. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20600. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20601. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20602. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20603. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20604. break;
  20605. case Camera.RIG_MODE_VR:
  20606. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20607. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20608. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20609. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20610. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20611. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20612. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20613. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20614. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20615. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20616. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20617. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20618. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20619. if (metrics.compensateDistortion) {
  20620. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20621. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20622. }
  20623. break;
  20624. case Camera.RIG_MODE_WEBVR:
  20625. if (rigParams.vrDisplay) {
  20626. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20627. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20628. //Left eye
  20629. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20630. this._rigCameras[0].setCameraRigParameter("left", true);
  20631. //leaving this for future reference
  20632. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20633. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20634. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20635. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20636. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20637. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20638. this._rigCameras[0].parent = this;
  20639. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20640. //Right eye
  20641. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20642. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20643. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20644. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20645. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20646. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20647. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20648. this._rigCameras[1].parent = this;
  20649. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20650. if (Camera.UseAlternateWebVRRendering) {
  20651. this._rigCameras[1]._skipRendering = true;
  20652. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20653. }
  20654. }
  20655. break;
  20656. }
  20657. this._cascadePostProcessesToRigCams();
  20658. this.update();
  20659. };
  20660. Camera.prototype._getVRProjectionMatrix = function () {
  20661. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20662. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20663. return this._projectionMatrix;
  20664. };
  20665. Camera.prototype._updateCameraRotationMatrix = function () {
  20666. //Here for WebVR
  20667. };
  20668. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20669. //Here for WebVR
  20670. };
  20671. /**
  20672. * This function MUST be overwritten by the different WebVR cameras available.
  20673. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20674. */
  20675. Camera.prototype._getWebVRProjectionMatrix = function () {
  20676. return BABYLON.Matrix.Identity();
  20677. };
  20678. /**
  20679. * This function MUST be overwritten by the different WebVR cameras available.
  20680. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20681. */
  20682. Camera.prototype._getWebVRViewMatrix = function () {
  20683. return BABYLON.Matrix.Identity();
  20684. };
  20685. Camera.prototype.setCameraRigParameter = function (name, value) {
  20686. if (!this._cameraRigParams) {
  20687. this._cameraRigParams = {};
  20688. }
  20689. this._cameraRigParams[name] = value;
  20690. //provisionnally:
  20691. if (name === "interaxialDistance") {
  20692. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20693. }
  20694. };
  20695. /**
  20696. * needs to be overridden by children so sub has required properties to be copied
  20697. */
  20698. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20699. return null;
  20700. };
  20701. /**
  20702. * May need to be overridden by children
  20703. */
  20704. Camera.prototype._updateRigCameras = function () {
  20705. for (var i = 0; i < this._rigCameras.length; i++) {
  20706. this._rigCameras[i].minZ = this.minZ;
  20707. this._rigCameras[i].maxZ = this.maxZ;
  20708. this._rigCameras[i].fov = this.fov;
  20709. }
  20710. // only update viewport when ANAGLYPH
  20711. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20712. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20713. }
  20714. };
  20715. Camera.prototype._setupInputs = function () {
  20716. };
  20717. Camera.prototype.serialize = function () {
  20718. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20719. // Type
  20720. serializationObject.type = this.getClassName();
  20721. // Parent
  20722. if (this.parent) {
  20723. serializationObject.parentId = this.parent.id;
  20724. }
  20725. if (this.inputs) {
  20726. this.inputs.serialize(serializationObject);
  20727. }
  20728. // Animations
  20729. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20730. serializationObject.ranges = this.serializeAnimationRanges();
  20731. return serializationObject;
  20732. };
  20733. Camera.prototype.clone = function (name) {
  20734. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20735. };
  20736. Camera.prototype.getDirection = function (localAxis) {
  20737. var result = BABYLON.Vector3.Zero();
  20738. this.getDirectionToRef(localAxis, result);
  20739. return result;
  20740. };
  20741. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20742. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20743. };
  20744. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20745. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20746. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20747. switch (type) {
  20748. case "ArcRotateCamera":
  20749. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20750. case "DeviceOrientationCamera":
  20751. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20752. case "FollowCamera":
  20753. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20754. case "ArcFollowCamera":
  20755. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20756. case "GamepadCamera":
  20757. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20758. case "TouchCamera":
  20759. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20760. case "VirtualJoysticksCamera":
  20761. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20762. case "WebVRFreeCamera":
  20763. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20764. case "WebVRGamepadCamera":
  20765. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20766. case "VRDeviceOrientationFreeCamera":
  20767. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20768. case "VRDeviceOrientationGamepadCamera":
  20769. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20770. case "AnaglyphArcRotateCamera":
  20771. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20772. case "AnaglyphFreeCamera":
  20773. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20774. case "AnaglyphGamepadCamera":
  20775. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20776. case "AnaglyphUniversalCamera":
  20777. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20778. case "StereoscopicArcRotateCamera":
  20779. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20780. case "StereoscopicFreeCamera":
  20781. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20782. case "StereoscopicGamepadCamera":
  20783. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20784. case "StereoscopicUniversalCamera":
  20785. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20786. case "FreeCamera":// Forcing Universal here
  20787. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20788. default:// Universal Camera is the default value
  20789. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20790. }
  20791. };
  20792. Camera.prototype.computeWorldMatrix = function () {
  20793. return this.getWorldMatrix();
  20794. };
  20795. Camera.Parse = function (parsedCamera, scene) {
  20796. var type = parsedCamera.type;
  20797. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20798. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20799. // Parent
  20800. if (parsedCamera.parentId) {
  20801. camera._waitingParentId = parsedCamera.parentId;
  20802. }
  20803. //If camera has an input manager, let it parse inputs settings
  20804. if (camera.inputs) {
  20805. camera.inputs.parse(parsedCamera);
  20806. camera._setupInputs();
  20807. }
  20808. if (camera.setPosition) {
  20809. camera.position.copyFromFloats(0, 0, 0);
  20810. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20811. }
  20812. // Target
  20813. if (parsedCamera.target) {
  20814. if (camera.setTarget) {
  20815. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20816. }
  20817. }
  20818. // Apply 3d rig, when found
  20819. if (parsedCamera.cameraRigMode) {
  20820. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20821. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20822. }
  20823. // Animations
  20824. if (parsedCamera.animations) {
  20825. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20826. var parsedAnimation = parsedCamera.animations[animationIndex];
  20827. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20828. }
  20829. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20830. }
  20831. if (parsedCamera.autoAnimate) {
  20832. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20833. }
  20834. return camera;
  20835. };
  20836. // Statics
  20837. Camera._PERSPECTIVE_CAMERA = 0;
  20838. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20839. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20840. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20841. Camera._RIG_MODE_NONE = 0;
  20842. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20843. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20844. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20845. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20846. Camera._RIG_MODE_VR = 20;
  20847. Camera._RIG_MODE_WEBVR = 21;
  20848. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20849. Camera.UseAlternateWebVRRendering = false;
  20850. __decorate([
  20851. BABYLON.serializeAsVector3()
  20852. ], Camera.prototype, "position", void 0);
  20853. __decorate([
  20854. BABYLON.serializeAsVector3()
  20855. ], Camera.prototype, "upVector", void 0);
  20856. __decorate([
  20857. BABYLON.serialize()
  20858. ], Camera.prototype, "orthoLeft", void 0);
  20859. __decorate([
  20860. BABYLON.serialize()
  20861. ], Camera.prototype, "orthoRight", void 0);
  20862. __decorate([
  20863. BABYLON.serialize()
  20864. ], Camera.prototype, "orthoBottom", void 0);
  20865. __decorate([
  20866. BABYLON.serialize()
  20867. ], Camera.prototype, "orthoTop", void 0);
  20868. __decorate([
  20869. BABYLON.serialize()
  20870. ], Camera.prototype, "fov", void 0);
  20871. __decorate([
  20872. BABYLON.serialize()
  20873. ], Camera.prototype, "minZ", void 0);
  20874. __decorate([
  20875. BABYLON.serialize()
  20876. ], Camera.prototype, "maxZ", void 0);
  20877. __decorate([
  20878. BABYLON.serialize()
  20879. ], Camera.prototype, "inertia", void 0);
  20880. __decorate([
  20881. BABYLON.serialize()
  20882. ], Camera.prototype, "mode", void 0);
  20883. __decorate([
  20884. BABYLON.serialize()
  20885. ], Camera.prototype, "layerMask", void 0);
  20886. __decorate([
  20887. BABYLON.serialize()
  20888. ], Camera.prototype, "fovMode", void 0);
  20889. __decorate([
  20890. BABYLON.serialize()
  20891. ], Camera.prototype, "cameraRigMode", void 0);
  20892. __decorate([
  20893. BABYLON.serialize()
  20894. ], Camera.prototype, "interaxialDistance", void 0);
  20895. __decorate([
  20896. BABYLON.serialize()
  20897. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20898. return Camera;
  20899. }(BABYLON.Node));
  20900. BABYLON.Camera = Camera;
  20901. })(BABYLON || (BABYLON = {}));
  20902. //# sourceMappingURL=babylon.camera.js.map
  20903. "use strict";
  20904. var BABYLON;
  20905. (function (BABYLON) {
  20906. var RenderingManager = /** @class */ (function () {
  20907. function RenderingManager(scene) {
  20908. this._renderingGroups = new Array();
  20909. this._autoClearDepthStencil = {};
  20910. this._customOpaqueSortCompareFn = {};
  20911. this._customAlphaTestSortCompareFn = {};
  20912. this._customTransparentSortCompareFn = {};
  20913. this._renderinGroupInfo = null;
  20914. this._scene = scene;
  20915. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20916. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20917. }
  20918. }
  20919. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20920. if (depth === void 0) { depth = true; }
  20921. if (stencil === void 0) { stencil = true; }
  20922. if (this._depthStencilBufferAlreadyCleaned) {
  20923. return;
  20924. }
  20925. this._scene.getEngine().clear(null, false, depth, stencil);
  20926. this._depthStencilBufferAlreadyCleaned = true;
  20927. };
  20928. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20929. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20930. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20931. var info = null;
  20932. if (observable) {
  20933. if (!this._renderinGroupInfo) {
  20934. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20935. }
  20936. info = this._renderinGroupInfo;
  20937. info.scene = this._scene;
  20938. info.camera = this._scene.activeCamera;
  20939. }
  20940. // Dispatch sprites
  20941. if (renderSprites) {
  20942. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20943. var manager = this._scene.spriteManagers[index];
  20944. this.dispatchSprites(manager);
  20945. }
  20946. }
  20947. // Render
  20948. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20949. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20950. var renderingGroup = this._renderingGroups[index];
  20951. if (!renderingGroup && !observable)
  20952. continue;
  20953. var renderingGroupMask = 0;
  20954. // Fire PRECLEAR stage
  20955. if (observable && info) {
  20956. renderingGroupMask = Math.pow(2, index);
  20957. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20958. info.renderingGroupId = index;
  20959. observable.notifyObservers(info, renderingGroupMask);
  20960. }
  20961. // Clear depth/stencil if needed
  20962. if (RenderingManager.AUTOCLEAR) {
  20963. var autoClear = this._autoClearDepthStencil[index];
  20964. if (autoClear && autoClear.autoClear) {
  20965. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20966. }
  20967. }
  20968. if (observable && info) {
  20969. // Fire PREOPAQUE stage
  20970. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20971. observable.notifyObservers(info, renderingGroupMask);
  20972. // Fire PRETRANSPARENT stage
  20973. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20974. observable.notifyObservers(info, renderingGroupMask);
  20975. }
  20976. if (renderingGroup)
  20977. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20978. // Fire POSTTRANSPARENT stage
  20979. if (observable && info) {
  20980. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20981. observable.notifyObservers(info, renderingGroupMask);
  20982. }
  20983. }
  20984. };
  20985. RenderingManager.prototype.reset = function () {
  20986. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20987. var renderingGroup = this._renderingGroups[index];
  20988. if (renderingGroup) {
  20989. renderingGroup.prepare();
  20990. }
  20991. }
  20992. };
  20993. RenderingManager.prototype.dispose = function () {
  20994. this.freeRenderingGroups();
  20995. this._renderingGroups.length = 0;
  20996. };
  20997. /**
  20998. * Clear the info related to rendering groups preventing retention points during dispose.
  20999. */
  21000. RenderingManager.prototype.freeRenderingGroups = function () {
  21001. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21002. var renderingGroup = this._renderingGroups[index];
  21003. if (renderingGroup) {
  21004. renderingGroup.dispose();
  21005. }
  21006. }
  21007. };
  21008. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21009. if (this._renderingGroups[renderingGroupId] === undefined) {
  21010. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21011. }
  21012. };
  21013. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21014. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21015. this._prepareRenderingGroup(renderingGroupId);
  21016. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21017. };
  21018. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21019. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21020. this._prepareRenderingGroup(renderingGroupId);
  21021. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21022. };
  21023. /**
  21024. * @param subMesh The submesh to dispatch
  21025. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21026. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21027. */
  21028. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21029. if (mesh === undefined) {
  21030. mesh = subMesh.getMesh();
  21031. }
  21032. var renderingGroupId = mesh.renderingGroupId || 0;
  21033. this._prepareRenderingGroup(renderingGroupId);
  21034. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21035. };
  21036. /**
  21037. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21038. * This allowed control for front to back rendering or reversly depending of the special needs.
  21039. *
  21040. * @param renderingGroupId The rendering group id corresponding to its index
  21041. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21042. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21043. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21044. */
  21045. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21046. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21047. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21048. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21049. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21050. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21051. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21052. if (this._renderingGroups[renderingGroupId]) {
  21053. var group = this._renderingGroups[renderingGroupId];
  21054. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21055. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21056. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21057. }
  21058. };
  21059. /**
  21060. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21061. *
  21062. * @param renderingGroupId The rendering group id corresponding to its index
  21063. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21064. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21065. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21066. */
  21067. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21068. if (depth === void 0) { depth = true; }
  21069. if (stencil === void 0) { stencil = true; }
  21070. this._autoClearDepthStencil[renderingGroupId] = {
  21071. autoClear: autoClearDepthStencil,
  21072. depth: depth,
  21073. stencil: stencil
  21074. };
  21075. };
  21076. /**
  21077. * The max id used for rendering groups (not included)
  21078. */
  21079. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21080. /**
  21081. * The min id used for rendering groups (included)
  21082. */
  21083. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21084. /**
  21085. * Used to globally prevent autoclearing scenes.
  21086. */
  21087. RenderingManager.AUTOCLEAR = true;
  21088. return RenderingManager;
  21089. }());
  21090. BABYLON.RenderingManager = RenderingManager;
  21091. })(BABYLON || (BABYLON = {}));
  21092. //# sourceMappingURL=babylon.renderingManager.js.map
  21093. "use strict";
  21094. var BABYLON;
  21095. (function (BABYLON) {
  21096. var RenderingGroup = /** @class */ (function () {
  21097. /**
  21098. * Creates a new rendering group.
  21099. * @param index The rendering group index
  21100. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21101. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21102. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21103. */
  21104. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21105. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21106. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21107. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21108. this.index = index;
  21109. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21110. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21111. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21112. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21113. this._particleSystems = new BABYLON.SmartArray(256);
  21114. this._spriteManagers = new BABYLON.SmartArray(256);
  21115. this._edgesRenderers = new BABYLON.SmartArray(16);
  21116. this._scene = scene;
  21117. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21118. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21119. this.transparentSortCompareFn = transparentSortCompareFn;
  21120. }
  21121. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21122. /**
  21123. * Set the opaque sort comparison function.
  21124. * If null the sub meshes will be render in the order they were created
  21125. */
  21126. set: function (value) {
  21127. this._opaqueSortCompareFn = value;
  21128. if (value) {
  21129. this._renderOpaque = this.renderOpaqueSorted;
  21130. }
  21131. else {
  21132. this._renderOpaque = RenderingGroup.renderUnsorted;
  21133. }
  21134. },
  21135. enumerable: true,
  21136. configurable: true
  21137. });
  21138. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21139. /**
  21140. * Set the alpha test sort comparison function.
  21141. * If null the sub meshes will be render in the order they were created
  21142. */
  21143. set: function (value) {
  21144. this._alphaTestSortCompareFn = value;
  21145. if (value) {
  21146. this._renderAlphaTest = this.renderAlphaTestSorted;
  21147. }
  21148. else {
  21149. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21150. }
  21151. },
  21152. enumerable: true,
  21153. configurable: true
  21154. });
  21155. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21156. /**
  21157. * Set the transparent sort comparison function.
  21158. * If null the sub meshes will be render in the order they were created
  21159. */
  21160. set: function (value) {
  21161. if (value) {
  21162. this._transparentSortCompareFn = value;
  21163. }
  21164. else {
  21165. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21166. }
  21167. this._renderTransparent = this.renderTransparentSorted;
  21168. },
  21169. enumerable: true,
  21170. configurable: true
  21171. });
  21172. /**
  21173. * Render all the sub meshes contained in the group.
  21174. * @param customRenderFunction Used to override the default render behaviour of the group.
  21175. * @returns true if rendered some submeshes.
  21176. */
  21177. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21178. if (customRenderFunction) {
  21179. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21180. return;
  21181. }
  21182. var engine = this._scene.getEngine();
  21183. // Depth only
  21184. if (this._depthOnlySubMeshes.length !== 0) {
  21185. engine.setColorWrite(false);
  21186. this._renderAlphaTest(this._depthOnlySubMeshes);
  21187. engine.setColorWrite(true);
  21188. }
  21189. // Opaque
  21190. if (this._opaqueSubMeshes.length !== 0) {
  21191. this._renderOpaque(this._opaqueSubMeshes);
  21192. }
  21193. // Alpha test
  21194. if (this._alphaTestSubMeshes.length !== 0) {
  21195. this._renderAlphaTest(this._alphaTestSubMeshes);
  21196. }
  21197. var stencilState = engine.getStencilBuffer();
  21198. engine.setStencilBuffer(false);
  21199. // Sprites
  21200. if (renderSprites) {
  21201. this._renderSprites();
  21202. }
  21203. // Particles
  21204. if (renderParticles) {
  21205. this._renderParticles(activeMeshes);
  21206. }
  21207. if (this.onBeforeTransparentRendering) {
  21208. this.onBeforeTransparentRendering();
  21209. }
  21210. // Transparent
  21211. if (this._transparentSubMeshes.length !== 0) {
  21212. this._renderTransparent(this._transparentSubMeshes);
  21213. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21214. }
  21215. // Set back stencil to false in case it changes before the edge renderer.
  21216. engine.setStencilBuffer(false);
  21217. // Edges
  21218. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21219. this._edgesRenderers.data[edgesRendererIndex].render();
  21220. }
  21221. // Restore Stencil state.
  21222. engine.setStencilBuffer(stencilState);
  21223. };
  21224. /**
  21225. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21226. * @param subMeshes The submeshes to render
  21227. */
  21228. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21229. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21230. };
  21231. /**
  21232. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21233. * @param subMeshes The submeshes to render
  21234. */
  21235. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21236. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21237. };
  21238. /**
  21239. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21240. * @param subMeshes The submeshes to render
  21241. */
  21242. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21243. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21244. };
  21245. /**
  21246. * Renders the submeshes in a specified order.
  21247. * @param subMeshes The submeshes to sort before render
  21248. * @param sortCompareFn The comparison function use to sort
  21249. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21250. * @param transparent Specifies to activate blending if true
  21251. */
  21252. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21253. var subIndex = 0;
  21254. var subMesh;
  21255. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21256. for (; subIndex < subMeshes.length; subIndex++) {
  21257. subMesh = subMeshes.data[subIndex];
  21258. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21259. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21260. }
  21261. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21262. if (sortCompareFn) {
  21263. sortedArray.sort(sortCompareFn);
  21264. }
  21265. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21266. subMesh = sortedArray[subIndex];
  21267. if (transparent) {
  21268. var material = subMesh.getMaterial();
  21269. if (material && material.needDepthPrePass) {
  21270. var engine = material.getScene().getEngine();
  21271. engine.setColorWrite(false);
  21272. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21273. subMesh.render(false);
  21274. engine.setColorWrite(true);
  21275. }
  21276. }
  21277. subMesh.render(transparent);
  21278. }
  21279. };
  21280. /**
  21281. * Renders the submeshes in the order they were dispatched (no sort applied).
  21282. * @param subMeshes The submeshes to render
  21283. */
  21284. RenderingGroup.renderUnsorted = function (subMeshes) {
  21285. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21286. var submesh = subMeshes.data[subIndex];
  21287. submesh.render(false);
  21288. }
  21289. };
  21290. /**
  21291. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21292. * are rendered back to front if in the same alpha index.
  21293. *
  21294. * @param a The first submesh
  21295. * @param b The second submesh
  21296. * @returns The result of the comparison
  21297. */
  21298. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21299. // Alpha index first
  21300. if (a._alphaIndex > b._alphaIndex) {
  21301. return 1;
  21302. }
  21303. if (a._alphaIndex < b._alphaIndex) {
  21304. return -1;
  21305. }
  21306. // Then distance to camera
  21307. return RenderingGroup.backToFrontSortCompare(a, b);
  21308. };
  21309. /**
  21310. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21311. * are rendered back to front.
  21312. *
  21313. * @param a The first submesh
  21314. * @param b The second submesh
  21315. * @returns The result of the comparison
  21316. */
  21317. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21318. // Then distance to camera
  21319. if (a._distanceToCamera < b._distanceToCamera) {
  21320. return 1;
  21321. }
  21322. if (a._distanceToCamera > b._distanceToCamera) {
  21323. return -1;
  21324. }
  21325. return 0;
  21326. };
  21327. /**
  21328. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21329. * are rendered front to back (prevent overdraw).
  21330. *
  21331. * @param a The first submesh
  21332. * @param b The second submesh
  21333. * @returns The result of the comparison
  21334. */
  21335. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21336. // Then distance to camera
  21337. if (a._distanceToCamera < b._distanceToCamera) {
  21338. return -1;
  21339. }
  21340. if (a._distanceToCamera > b._distanceToCamera) {
  21341. return 1;
  21342. }
  21343. return 0;
  21344. };
  21345. /**
  21346. * Resets the different lists of submeshes to prepare a new frame.
  21347. */
  21348. RenderingGroup.prototype.prepare = function () {
  21349. this._opaqueSubMeshes.reset();
  21350. this._transparentSubMeshes.reset();
  21351. this._alphaTestSubMeshes.reset();
  21352. this._depthOnlySubMeshes.reset();
  21353. this._particleSystems.reset();
  21354. this._spriteManagers.reset();
  21355. this._edgesRenderers.reset();
  21356. };
  21357. RenderingGroup.prototype.dispose = function () {
  21358. this._opaqueSubMeshes.dispose();
  21359. this._transparentSubMeshes.dispose();
  21360. this._alphaTestSubMeshes.dispose();
  21361. this._depthOnlySubMeshes.dispose();
  21362. this._particleSystems.dispose();
  21363. this._spriteManagers.dispose();
  21364. this._edgesRenderers.dispose();
  21365. };
  21366. /**
  21367. * Inserts the submesh in its correct queue depending on its material.
  21368. * @param subMesh The submesh to dispatch
  21369. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21370. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21371. */
  21372. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21373. // Get mesh and materials if not provided
  21374. if (mesh === undefined) {
  21375. mesh = subMesh.getMesh();
  21376. }
  21377. if (material === undefined) {
  21378. material = subMesh.getMaterial();
  21379. }
  21380. if (material === null || material === undefined) {
  21381. return;
  21382. }
  21383. if (material.needAlphaBlendingForMesh(mesh)) {
  21384. this._transparentSubMeshes.push(subMesh);
  21385. }
  21386. else if (material.needAlphaTesting()) {
  21387. if (material.needDepthPrePass) {
  21388. this._depthOnlySubMeshes.push(subMesh);
  21389. }
  21390. this._alphaTestSubMeshes.push(subMesh);
  21391. }
  21392. else {
  21393. if (material.needDepthPrePass) {
  21394. this._depthOnlySubMeshes.push(subMesh);
  21395. }
  21396. this._opaqueSubMeshes.push(subMesh); // Opaque
  21397. }
  21398. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21399. this._edgesRenderers.push(mesh._edgesRenderer);
  21400. }
  21401. };
  21402. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21403. this._spriteManagers.push(spriteManager);
  21404. };
  21405. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21406. this._particleSystems.push(particleSystem);
  21407. };
  21408. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21409. if (this._particleSystems.length === 0) {
  21410. return;
  21411. }
  21412. // Particles
  21413. var activeCamera = this._scene.activeCamera;
  21414. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21415. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21416. var particleSystem = this._particleSystems.data[particleIndex];
  21417. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21418. continue;
  21419. }
  21420. var emitter = particleSystem.emitter;
  21421. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21422. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21423. }
  21424. }
  21425. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21426. };
  21427. RenderingGroup.prototype._renderSprites = function () {
  21428. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21429. return;
  21430. }
  21431. // Sprites
  21432. var activeCamera = this._scene.activeCamera;
  21433. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21434. for (var id = 0; id < this._spriteManagers.length; id++) {
  21435. var spriteManager = this._spriteManagers.data[id];
  21436. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21437. spriteManager.render();
  21438. }
  21439. }
  21440. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21441. };
  21442. return RenderingGroup;
  21443. }());
  21444. BABYLON.RenderingGroup = RenderingGroup;
  21445. })(BABYLON || (BABYLON = {}));
  21446. //# sourceMappingURL=babylon.renderingGroup.js.map
  21447. "use strict";
  21448. var BABYLON;
  21449. (function (BABYLON) {
  21450. var ClickInfo = /** @class */ (function () {
  21451. function ClickInfo() {
  21452. this._singleClick = false;
  21453. this._doubleClick = false;
  21454. this._hasSwiped = false;
  21455. this._ignore = false;
  21456. }
  21457. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21458. get: function () {
  21459. return this._singleClick;
  21460. },
  21461. set: function (b) {
  21462. this._singleClick = b;
  21463. },
  21464. enumerable: true,
  21465. configurable: true
  21466. });
  21467. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21468. get: function () {
  21469. return this._doubleClick;
  21470. },
  21471. set: function (b) {
  21472. this._doubleClick = b;
  21473. },
  21474. enumerable: true,
  21475. configurable: true
  21476. });
  21477. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21478. get: function () {
  21479. return this._hasSwiped;
  21480. },
  21481. set: function (b) {
  21482. this._hasSwiped = b;
  21483. },
  21484. enumerable: true,
  21485. configurable: true
  21486. });
  21487. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21488. get: function () {
  21489. return this._ignore;
  21490. },
  21491. set: function (b) {
  21492. this._ignore = b;
  21493. },
  21494. enumerable: true,
  21495. configurable: true
  21496. });
  21497. return ClickInfo;
  21498. }());
  21499. /**
  21500. * This class is used by the onRenderingGroupObservable
  21501. */
  21502. var RenderingGroupInfo = /** @class */ (function () {
  21503. function RenderingGroupInfo() {
  21504. }
  21505. /**
  21506. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21507. * This stage will be fired no matter what
  21508. */
  21509. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21510. /**
  21511. * Called before opaque object are rendered.
  21512. * This stage will be fired only if there's 3D Opaque content to render
  21513. */
  21514. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21515. /**
  21516. * Called after the opaque objects are rendered and before the transparent ones
  21517. * This stage will be fired only if there's 3D transparent content to render
  21518. */
  21519. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21520. /**
  21521. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21522. * This stage will be fired no matter what
  21523. */
  21524. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21525. return RenderingGroupInfo;
  21526. }());
  21527. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21528. /**
  21529. * Represents a scene to be rendered by the engine.
  21530. * @see http://doc.babylonjs.com/page.php?p=21911
  21531. */
  21532. var Scene = /** @class */ (function () {
  21533. /**
  21534. * @constructor
  21535. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21536. */
  21537. function Scene(engine) {
  21538. // Members
  21539. this.autoClear = true;
  21540. this.autoClearDepthAndStencil = true;
  21541. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21542. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21543. this._forceWireframe = false;
  21544. this._forcePointsCloud = false;
  21545. this.forceShowBoundingBoxes = false;
  21546. this.animationsEnabled = true;
  21547. this.useConstantAnimationDeltaTime = false;
  21548. this.constantlyUpdateMeshUnderPointer = false;
  21549. this.hoverCursor = "pointer";
  21550. this.defaultCursor = "";
  21551. /**
  21552. * This is used to call preventDefault() on pointer down
  21553. * in order to block unwanted artifacts like system double clicks
  21554. */
  21555. this.preventDefaultOnPointerDown = true;
  21556. // Metadata
  21557. this.metadata = null;
  21558. /**
  21559. * Use this array to add regular expressions used to disable offline support for specific urls
  21560. */
  21561. this.disableOfflineSupportExceptionRules = new Array();
  21562. /**
  21563. * An event triggered when the scene is disposed.
  21564. * @type {BABYLON.Observable}
  21565. */
  21566. this.onDisposeObservable = new BABYLON.Observable();
  21567. this._onDisposeObserver = null;
  21568. /**
  21569. * An event triggered before rendering the scene (right after animations and physics)
  21570. * @type {BABYLON.Observable}
  21571. */
  21572. this.onBeforeRenderObservable = new BABYLON.Observable();
  21573. this._onBeforeRenderObserver = null;
  21574. /**
  21575. * An event triggered after rendering the scene
  21576. * @type {BABYLON.Observable}
  21577. */
  21578. this.onAfterRenderObservable = new BABYLON.Observable();
  21579. this._onAfterRenderObserver = null;
  21580. /**
  21581. * An event triggered before animating the scene
  21582. * @type {BABYLON.Observable}
  21583. */
  21584. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21585. /**
  21586. * An event triggered after animations processing
  21587. * @type {BABYLON.Observable}
  21588. */
  21589. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21590. /**
  21591. * An event triggered before draw calls are ready to be sent
  21592. * @type {BABYLON.Observable}
  21593. */
  21594. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21595. /**
  21596. * An event triggered after draw calls have been sent
  21597. * @type {BABYLON.Observable}
  21598. */
  21599. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21600. /**
  21601. * An event triggered when physic simulation is about to be run
  21602. * @type {BABYLON.Observable}
  21603. */
  21604. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21605. /**
  21606. * An event triggered when physic simulation has been done
  21607. * @type {BABYLON.Observable}
  21608. */
  21609. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21610. /**
  21611. * An event triggered when the scene is ready
  21612. * @type {BABYLON.Observable}
  21613. */
  21614. this.onReadyObservable = new BABYLON.Observable();
  21615. /**
  21616. * An event triggered before rendering a camera
  21617. * @type {BABYLON.Observable}
  21618. */
  21619. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21620. this._onBeforeCameraRenderObserver = null;
  21621. /**
  21622. * An event triggered after rendering a camera
  21623. * @type {BABYLON.Observable}
  21624. */
  21625. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21626. this._onAfterCameraRenderObserver = null;
  21627. /**
  21628. * An event triggered when active meshes evaluation is about to start
  21629. * @type {BABYLON.Observable}
  21630. */
  21631. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21632. /**
  21633. * An event triggered when active meshes evaluation is done
  21634. * @type {BABYLON.Observable}
  21635. */
  21636. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21637. /**
  21638. * An event triggered when particles rendering is about to start
  21639. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21640. * @type {BABYLON.Observable}
  21641. */
  21642. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21643. /**
  21644. * An event triggered when particles rendering is done
  21645. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21646. * @type {BABYLON.Observable}
  21647. */
  21648. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21649. /**
  21650. * An event triggered when sprites rendering is about to start
  21651. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21652. * @type {BABYLON.Observable}
  21653. */
  21654. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21655. /**
  21656. * An event triggered when sprites rendering is done
  21657. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21658. * @type {BABYLON.Observable}
  21659. */
  21660. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21661. /**
  21662. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21663. * @type {BABYLON.Observable}
  21664. */
  21665. this.onDataLoadedObservable = new BABYLON.Observable();
  21666. /**
  21667. * An event triggered when a camera is created
  21668. * @type {BABYLON.Observable}
  21669. */
  21670. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21671. /**
  21672. * An event triggered when a camera is removed
  21673. * @type {BABYLON.Observable}
  21674. */
  21675. this.onCameraRemovedObservable = new BABYLON.Observable();
  21676. /**
  21677. * An event triggered when a light is created
  21678. * @type {BABYLON.Observable}
  21679. */
  21680. this.onNewLightAddedObservable = new BABYLON.Observable();
  21681. /**
  21682. * An event triggered when a light is removed
  21683. * @type {BABYLON.Observable}
  21684. */
  21685. this.onLightRemovedObservable = new BABYLON.Observable();
  21686. /**
  21687. * An event triggered when a geometry is created
  21688. * @type {BABYLON.Observable}
  21689. */
  21690. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21691. /**
  21692. * An event triggered when a geometry is removed
  21693. * @type {BABYLON.Observable}
  21694. */
  21695. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21696. /**
  21697. * An event triggered when a transform node is created
  21698. * @type {BABYLON.Observable}
  21699. */
  21700. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21701. /**
  21702. * An event triggered when a transform node is removed
  21703. * @type {BABYLON.Observable}
  21704. */
  21705. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21706. /**
  21707. * An event triggered when a mesh is created
  21708. * @type {BABYLON.Observable}
  21709. */
  21710. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21711. /**
  21712. * An event triggered when a mesh is removed
  21713. * @type {BABYLON.Observable}
  21714. */
  21715. this.onMeshRemovedObservable = new BABYLON.Observable();
  21716. /**
  21717. * An event triggered when render targets are about to be rendered
  21718. * Can happen multiple times per frame.
  21719. * @type {BABYLON.Observable}
  21720. */
  21721. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21722. /**
  21723. * An event triggered when render targets were rendered.
  21724. * Can happen multiple times per frame.
  21725. * @type {BABYLON.Observable}
  21726. */
  21727. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21728. /**
  21729. * An event triggered before calculating deterministic simulation step
  21730. * @type {BABYLON.Observable}
  21731. */
  21732. this.onBeforeStepObservable = new BABYLON.Observable();
  21733. /**
  21734. * An event triggered after calculating deterministic simulation step
  21735. * @type {BABYLON.Observable}
  21736. */
  21737. this.onAfterStepObservable = new BABYLON.Observable();
  21738. /**
  21739. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21740. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21741. * 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)
  21742. */
  21743. this.onRenderingGroupObservable = new BABYLON.Observable();
  21744. // Animations
  21745. this.animations = [];
  21746. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21747. /**
  21748. * 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).
  21749. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21750. */
  21751. this.onPrePointerObservable = new BABYLON.Observable();
  21752. /**
  21753. * Observable event triggered each time an input event is received from the rendering canvas
  21754. */
  21755. this.onPointerObservable = new BABYLON.Observable();
  21756. this._meshPickProceed = false;
  21757. this._currentPickResult = null;
  21758. this._previousPickResult = null;
  21759. this._totalPointersPressed = 0;
  21760. this._doubleClickOccured = false;
  21761. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21762. this.cameraToUseForPointers = null;
  21763. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21764. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21765. this._startingPointerTime = 0;
  21766. this._previousStartingPointerTime = 0;
  21767. // Deterministic lockstep
  21768. this._timeAccumulator = 0;
  21769. this._currentStepId = 0;
  21770. this._currentInternalStep = 0;
  21771. // Keyboard
  21772. /**
  21773. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21774. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21775. */
  21776. this.onPreKeyboardObservable = new BABYLON.Observable();
  21777. /**
  21778. * Observable event triggered each time an keyboard event is received from the hosting window
  21779. */
  21780. this.onKeyboardObservable = new BABYLON.Observable();
  21781. // Coordinate system
  21782. /**
  21783. * use right-handed coordinate system on this scene.
  21784. * @type {boolean}
  21785. */
  21786. this._useRightHandedSystem = false;
  21787. // Fog
  21788. this._fogEnabled = true;
  21789. this._fogMode = Scene.FOGMODE_NONE;
  21790. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21791. this.fogDensity = 0.1;
  21792. this.fogStart = 0;
  21793. this.fogEnd = 1000.0;
  21794. // Lights
  21795. /**
  21796. * is shadow enabled on this scene.
  21797. * @type {boolean}
  21798. */
  21799. this._shadowsEnabled = true;
  21800. /**
  21801. * is light enabled on this scene.
  21802. * @type {boolean}
  21803. */
  21804. this._lightsEnabled = true;
  21805. /**
  21806. * All of the lights added to this scene.
  21807. * @see BABYLON.Light
  21808. * @type {BABYLON.Light[]}
  21809. */
  21810. this.lights = new Array();
  21811. // Cameras
  21812. /** All of the cameras added to this scene. */
  21813. this.cameras = new Array();
  21814. /** All of the active cameras added to this scene. */
  21815. this.activeCameras = new Array();
  21816. // Meshes
  21817. /**
  21818. * All of the tranform nodes added to this scene.
  21819. * @see BABYLON.TransformNode
  21820. * @type {BABYLON.TransformNode[]}
  21821. */
  21822. this.transformNodes = new Array();
  21823. /**
  21824. * All of the (abstract) meshes added to this scene.
  21825. * @see BABYLON.AbstractMesh
  21826. * @type {BABYLON.AbstractMesh[]}
  21827. */
  21828. this.meshes = new Array();
  21829. /**
  21830. * All of the animation groups added to this scene.
  21831. * @see BABYLON.AnimationGroup
  21832. * @type {BABYLON.AnimationGroup[]}
  21833. */
  21834. this.animationGroups = new Array();
  21835. // Geometries
  21836. this._geometries = new Array();
  21837. this.materials = new Array();
  21838. this.multiMaterials = new Array();
  21839. // Textures
  21840. this._texturesEnabled = true;
  21841. this.textures = new Array();
  21842. // Particles
  21843. this.particlesEnabled = true;
  21844. this.particleSystems = new Array();
  21845. // Sprites
  21846. this.spritesEnabled = true;
  21847. this.spriteManagers = new Array();
  21848. /**
  21849. * The list of layers (background and foreground) of the scene.
  21850. */
  21851. this.layers = new Array();
  21852. /**
  21853. * The list of effect layers (highlights/glow) contained in the scene.
  21854. */
  21855. this.effectLayers = new Array();
  21856. // Skeletons
  21857. this._skeletonsEnabled = true;
  21858. this.skeletons = new Array();
  21859. // Morph targets
  21860. this.morphTargetManagers = new Array();
  21861. // Lens flares
  21862. this.lensFlaresEnabled = true;
  21863. this.lensFlareSystems = new Array();
  21864. // Collisions
  21865. this.collisionsEnabled = true;
  21866. /** Defines the gravity applied to this scene */
  21867. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21868. // Postprocesses
  21869. this.postProcesses = new Array();
  21870. this.postProcessesEnabled = true;
  21871. // Customs render targets
  21872. this.renderTargetsEnabled = true;
  21873. this.dumpNextRenderTargets = false;
  21874. this.customRenderTargets = new Array();
  21875. // Imported meshes
  21876. this.importedMeshesFiles = new Array();
  21877. // Probes
  21878. this.probesEnabled = true;
  21879. this.reflectionProbes = new Array();
  21880. this._actionManagers = new Array();
  21881. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21882. // Procedural textures
  21883. this.proceduralTexturesEnabled = true;
  21884. this._proceduralTextures = new Array();
  21885. this.soundTracks = new Array();
  21886. this._audioEnabled = true;
  21887. this._headphone = false;
  21888. // Performance counters
  21889. this._totalVertices = new BABYLON.PerfCounter();
  21890. this._activeIndices = new BABYLON.PerfCounter();
  21891. this._activeParticles = new BABYLON.PerfCounter();
  21892. this._activeBones = new BABYLON.PerfCounter();
  21893. this._animationTime = 0;
  21894. this.animationTimeScale = 1;
  21895. this._renderId = 0;
  21896. this._executeWhenReadyTimeoutId = -1;
  21897. this._intermediateRendering = false;
  21898. this._viewUpdateFlag = -1;
  21899. this._projectionUpdateFlag = -1;
  21900. this._alternateViewUpdateFlag = -1;
  21901. this._alternateProjectionUpdateFlag = -1;
  21902. this._toBeDisposed = new BABYLON.SmartArray(256);
  21903. this._activeRequests = new Array();
  21904. this._pendingData = new Array();
  21905. this._isDisposed = false;
  21906. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21907. this._activeMeshes = new BABYLON.SmartArray(256);
  21908. this._processedMaterials = new BABYLON.SmartArray(256);
  21909. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21910. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21911. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21912. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21913. this._activeAnimatables = new Array();
  21914. this._transformMatrix = BABYLON.Matrix.Zero();
  21915. this._useAlternateCameraConfiguration = false;
  21916. this._alternateRendering = false;
  21917. this.requireLightSorting = false;
  21918. this._depthRenderer = {};
  21919. this._activeMeshesFrozen = false;
  21920. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21921. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21922. this._engine.scenes.push(this);
  21923. this._uid = null;
  21924. this._renderingManager = new BABYLON.RenderingManager(this);
  21925. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21926. if (BABYLON.OutlineRenderer) {
  21927. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21928. }
  21929. if (BABYLON.Tools.IsWindowObjectExist()) {
  21930. this.attachControl();
  21931. }
  21932. //simplification queue
  21933. if (BABYLON.SimplificationQueue) {
  21934. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21935. }
  21936. //collision coordinator initialization. For now legacy per default.
  21937. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21938. // Uniform Buffer
  21939. this._createUbo();
  21940. // Default Image processing definition.
  21941. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21942. }
  21943. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21944. /** The fog is deactivated */
  21945. get: function () {
  21946. return Scene._FOGMODE_NONE;
  21947. },
  21948. enumerable: true,
  21949. configurable: true
  21950. });
  21951. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21952. /** The fog density is following an exponential function */
  21953. get: function () {
  21954. return Scene._FOGMODE_EXP;
  21955. },
  21956. enumerable: true,
  21957. configurable: true
  21958. });
  21959. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21960. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21961. get: function () {
  21962. return Scene._FOGMODE_EXP2;
  21963. },
  21964. enumerable: true,
  21965. configurable: true
  21966. });
  21967. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21968. /** The fog density is following a linear function. */
  21969. get: function () {
  21970. return Scene._FOGMODE_LINEAR;
  21971. },
  21972. enumerable: true,
  21973. configurable: true
  21974. });
  21975. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21976. /**
  21977. * Texture used in all pbr material as the reflection texture.
  21978. * As in the majority of the scene they are the same (exception for multi room and so on),
  21979. * this is easier to reference from here than from all the materials.
  21980. */
  21981. get: function () {
  21982. return this._environmentTexture;
  21983. },
  21984. /**
  21985. * Texture used in all pbr material as the reflection texture.
  21986. * As in the majority of the scene they are the same (exception for multi room and so on),
  21987. * this is easier to set here than in all the materials.
  21988. */
  21989. set: function (value) {
  21990. if (this._environmentTexture === value) {
  21991. return;
  21992. }
  21993. this._environmentTexture = value;
  21994. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21995. },
  21996. enumerable: true,
  21997. configurable: true
  21998. });
  21999. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22000. /**
  22001. * Default image processing configuration used either in the rendering
  22002. * Forward main pass or through the imageProcessingPostProcess if present.
  22003. * As in the majority of the scene they are the same (exception for multi camera),
  22004. * this is easier to reference from here than from all the materials and post process.
  22005. *
  22006. * No setter as we it is a shared configuration, you can set the values instead.
  22007. */
  22008. get: function () {
  22009. return this._imageProcessingConfiguration;
  22010. },
  22011. enumerable: true,
  22012. configurable: true
  22013. });
  22014. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22015. get: function () {
  22016. return this._forceWireframe;
  22017. },
  22018. set: function (value) {
  22019. if (this._forceWireframe === value) {
  22020. return;
  22021. }
  22022. this._forceWireframe = value;
  22023. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22024. },
  22025. enumerable: true,
  22026. configurable: true
  22027. });
  22028. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22029. get: function () {
  22030. return this._forcePointsCloud;
  22031. },
  22032. set: function (value) {
  22033. if (this._forcePointsCloud === value) {
  22034. return;
  22035. }
  22036. this._forcePointsCloud = value;
  22037. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22038. },
  22039. enumerable: true,
  22040. configurable: true
  22041. });
  22042. Object.defineProperty(Scene.prototype, "onDispose", {
  22043. /** A function to be executed when this scene is disposed. */
  22044. set: function (callback) {
  22045. if (this._onDisposeObserver) {
  22046. this.onDisposeObservable.remove(this._onDisposeObserver);
  22047. }
  22048. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22049. },
  22050. enumerable: true,
  22051. configurable: true
  22052. });
  22053. Object.defineProperty(Scene.prototype, "beforeRender", {
  22054. /** A function to be executed before rendering this scene */
  22055. set: function (callback) {
  22056. if (this._onBeforeRenderObserver) {
  22057. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22058. }
  22059. if (callback) {
  22060. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22061. }
  22062. },
  22063. enumerable: true,
  22064. configurable: true
  22065. });
  22066. Object.defineProperty(Scene.prototype, "afterRender", {
  22067. /** A function to be executed after rendering this scene */
  22068. set: function (callback) {
  22069. if (this._onAfterRenderObserver) {
  22070. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22071. }
  22072. if (callback) {
  22073. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22074. }
  22075. },
  22076. enumerable: true,
  22077. configurable: true
  22078. });
  22079. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22080. set: function (callback) {
  22081. if (this._onBeforeCameraRenderObserver) {
  22082. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22083. }
  22084. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22085. },
  22086. enumerable: true,
  22087. configurable: true
  22088. });
  22089. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22090. set: function (callback) {
  22091. if (this._onAfterCameraRenderObserver) {
  22092. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22093. }
  22094. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22095. },
  22096. enumerable: true,
  22097. configurable: true
  22098. });
  22099. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22100. get: function () {
  22101. if (!this._gamepadManager) {
  22102. this._gamepadManager = new BABYLON.GamepadManager(this);
  22103. }
  22104. return this._gamepadManager;
  22105. },
  22106. enumerable: true,
  22107. configurable: true
  22108. });
  22109. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22110. get: function () {
  22111. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22112. },
  22113. enumerable: true,
  22114. configurable: true
  22115. });
  22116. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22117. get: function () {
  22118. return this._useRightHandedSystem;
  22119. },
  22120. set: function (value) {
  22121. if (this._useRightHandedSystem === value) {
  22122. return;
  22123. }
  22124. this._useRightHandedSystem = value;
  22125. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22126. },
  22127. enumerable: true,
  22128. configurable: true
  22129. });
  22130. Scene.prototype.setStepId = function (newStepId) {
  22131. this._currentStepId = newStepId;
  22132. };
  22133. ;
  22134. Scene.prototype.getStepId = function () {
  22135. return this._currentStepId;
  22136. };
  22137. ;
  22138. Scene.prototype.getInternalStep = function () {
  22139. return this._currentInternalStep;
  22140. };
  22141. ;
  22142. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22143. get: function () {
  22144. return this._fogEnabled;
  22145. },
  22146. /**
  22147. * is fog enabled on this scene.
  22148. */
  22149. set: function (value) {
  22150. if (this._fogEnabled === value) {
  22151. return;
  22152. }
  22153. this._fogEnabled = value;
  22154. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22155. },
  22156. enumerable: true,
  22157. configurable: true
  22158. });
  22159. Object.defineProperty(Scene.prototype, "fogMode", {
  22160. get: function () {
  22161. return this._fogMode;
  22162. },
  22163. set: function (value) {
  22164. if (this._fogMode === value) {
  22165. return;
  22166. }
  22167. this._fogMode = value;
  22168. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22169. },
  22170. enumerable: true,
  22171. configurable: true
  22172. });
  22173. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22174. get: function () {
  22175. return this._shadowsEnabled;
  22176. },
  22177. set: function (value) {
  22178. if (this._shadowsEnabled === value) {
  22179. return;
  22180. }
  22181. this._shadowsEnabled = value;
  22182. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22183. },
  22184. enumerable: true,
  22185. configurable: true
  22186. });
  22187. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22188. get: function () {
  22189. return this._lightsEnabled;
  22190. },
  22191. set: function (value) {
  22192. if (this._lightsEnabled === value) {
  22193. return;
  22194. }
  22195. this._lightsEnabled = value;
  22196. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22197. },
  22198. enumerable: true,
  22199. configurable: true
  22200. });
  22201. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22202. /** The default material used on meshes when no material is affected */
  22203. get: function () {
  22204. if (!this._defaultMaterial) {
  22205. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22206. }
  22207. return this._defaultMaterial;
  22208. },
  22209. /** The default material used on meshes when no material is affected */
  22210. set: function (value) {
  22211. this._defaultMaterial = value;
  22212. },
  22213. enumerable: true,
  22214. configurable: true
  22215. });
  22216. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22217. get: function () {
  22218. return this._texturesEnabled;
  22219. },
  22220. set: function (value) {
  22221. if (this._texturesEnabled === value) {
  22222. return;
  22223. }
  22224. this._texturesEnabled = value;
  22225. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22226. },
  22227. enumerable: true,
  22228. configurable: true
  22229. });
  22230. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22231. get: function () {
  22232. return this._skeletonsEnabled;
  22233. },
  22234. set: function (value) {
  22235. if (this._skeletonsEnabled === value) {
  22236. return;
  22237. }
  22238. this._skeletonsEnabled = value;
  22239. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22240. },
  22241. enumerable: true,
  22242. configurable: true
  22243. });
  22244. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22245. get: function () {
  22246. if (!this._postProcessRenderPipelineManager) {
  22247. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22248. }
  22249. return this._postProcessRenderPipelineManager;
  22250. },
  22251. enumerable: true,
  22252. configurable: true
  22253. });
  22254. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22255. get: function () {
  22256. if (!this._mainSoundTrack) {
  22257. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22258. }
  22259. return this._mainSoundTrack;
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22265. get: function () {
  22266. return this._alternateRendering;
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22272. get: function () {
  22273. return this._frustumPlanes;
  22274. },
  22275. enumerable: true,
  22276. configurable: true
  22277. });
  22278. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22279. /**
  22280. * Gets the current geometry buffer associated to the scene.
  22281. */
  22282. get: function () {
  22283. return this._geometryBufferRenderer;
  22284. },
  22285. /**
  22286. * Sets the current geometry buffer for the scene.
  22287. */
  22288. set: function (geometryBufferRenderer) {
  22289. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22290. this._geometryBufferRenderer = geometryBufferRenderer;
  22291. }
  22292. },
  22293. enumerable: true,
  22294. configurable: true
  22295. });
  22296. Object.defineProperty(Scene.prototype, "debugLayer", {
  22297. // Properties
  22298. get: function () {
  22299. if (!this._debugLayer) {
  22300. this._debugLayer = new BABYLON.DebugLayer(this);
  22301. }
  22302. return this._debugLayer;
  22303. },
  22304. enumerable: true,
  22305. configurable: true
  22306. });
  22307. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22308. get: function () {
  22309. return this._workerCollisions;
  22310. },
  22311. set: function (enabled) {
  22312. if (!BABYLON.CollisionCoordinatorLegacy) {
  22313. return;
  22314. }
  22315. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22316. this._workerCollisions = enabled;
  22317. if (this.collisionCoordinator) {
  22318. this.collisionCoordinator.destroy();
  22319. }
  22320. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22321. this.collisionCoordinator.init(this);
  22322. },
  22323. enumerable: true,
  22324. configurable: true
  22325. });
  22326. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22327. get: function () {
  22328. return this._selectionOctree;
  22329. },
  22330. enumerable: true,
  22331. configurable: true
  22332. });
  22333. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22334. /**
  22335. * The mesh that is currently under the pointer.
  22336. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22337. */
  22338. get: function () {
  22339. return this._pointerOverMesh;
  22340. },
  22341. enumerable: true,
  22342. configurable: true
  22343. });
  22344. Object.defineProperty(Scene.prototype, "pointerX", {
  22345. /**
  22346. * Current on-screen X position of the pointer
  22347. * @return {number} X position of the pointer
  22348. */
  22349. get: function () {
  22350. return this._pointerX;
  22351. },
  22352. enumerable: true,
  22353. configurable: true
  22354. });
  22355. Object.defineProperty(Scene.prototype, "pointerY", {
  22356. /**
  22357. * Current on-screen Y position of the pointer
  22358. * @return {number} Y position of the pointer
  22359. */
  22360. get: function () {
  22361. return this._pointerY;
  22362. },
  22363. enumerable: true,
  22364. configurable: true
  22365. });
  22366. Scene.prototype.getCachedMaterial = function () {
  22367. return this._cachedMaterial;
  22368. };
  22369. Scene.prototype.getCachedEffect = function () {
  22370. return this._cachedEffect;
  22371. };
  22372. Scene.prototype.getCachedVisibility = function () {
  22373. return this._cachedVisibility;
  22374. };
  22375. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22376. if (visibility === void 0) { visibility = 1; }
  22377. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22378. };
  22379. Scene.prototype.getBoundingBoxRenderer = function () {
  22380. if (!this._boundingBoxRenderer) {
  22381. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22382. }
  22383. return this._boundingBoxRenderer;
  22384. };
  22385. Scene.prototype.getOutlineRenderer = function () {
  22386. return this._outlineRenderer;
  22387. };
  22388. Scene.prototype.getEngine = function () {
  22389. return this._engine;
  22390. };
  22391. Scene.prototype.getTotalVertices = function () {
  22392. return this._totalVertices.current;
  22393. };
  22394. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22395. get: function () {
  22396. return this._totalVertices;
  22397. },
  22398. enumerable: true,
  22399. configurable: true
  22400. });
  22401. Scene.prototype.getActiveIndices = function () {
  22402. return this._activeIndices.current;
  22403. };
  22404. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22405. get: function () {
  22406. return this._activeIndices;
  22407. },
  22408. enumerable: true,
  22409. configurable: true
  22410. });
  22411. Scene.prototype.getActiveParticles = function () {
  22412. return this._activeParticles.current;
  22413. };
  22414. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22415. get: function () {
  22416. return this._activeParticles;
  22417. },
  22418. enumerable: true,
  22419. configurable: true
  22420. });
  22421. Scene.prototype.getActiveBones = function () {
  22422. return this._activeBones.current;
  22423. };
  22424. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22425. get: function () {
  22426. return this._activeBones;
  22427. },
  22428. enumerable: true,
  22429. configurable: true
  22430. });
  22431. // Stats
  22432. Scene.prototype.getInterFramePerfCounter = function () {
  22433. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22434. return 0;
  22435. };
  22436. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22437. get: function () {
  22438. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22439. return null;
  22440. },
  22441. enumerable: true,
  22442. configurable: true
  22443. });
  22444. Scene.prototype.getLastFrameDuration = function () {
  22445. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22446. return 0;
  22447. };
  22448. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22449. get: function () {
  22450. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22451. return null;
  22452. },
  22453. enumerable: true,
  22454. configurable: true
  22455. });
  22456. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22457. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22458. return 0;
  22459. };
  22460. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22461. get: function () {
  22462. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22463. return null;
  22464. },
  22465. enumerable: true,
  22466. configurable: true
  22467. });
  22468. Scene.prototype.getActiveMeshes = function () {
  22469. return this._activeMeshes;
  22470. };
  22471. Scene.prototype.getRenderTargetsDuration = function () {
  22472. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22473. return 0;
  22474. };
  22475. Scene.prototype.getRenderDuration = function () {
  22476. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22477. return 0;
  22478. };
  22479. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22480. get: function () {
  22481. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22482. return null;
  22483. },
  22484. enumerable: true,
  22485. configurable: true
  22486. });
  22487. Scene.prototype.getParticlesDuration = function () {
  22488. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22489. return 0;
  22490. };
  22491. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22492. get: function () {
  22493. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22494. return null;
  22495. },
  22496. enumerable: true,
  22497. configurable: true
  22498. });
  22499. Scene.prototype.getSpritesDuration = function () {
  22500. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22501. return 0;
  22502. };
  22503. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22504. get: function () {
  22505. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22506. return null;
  22507. },
  22508. enumerable: true,
  22509. configurable: true
  22510. });
  22511. Scene.prototype.getAnimationRatio = function () {
  22512. return this._animationRatio;
  22513. };
  22514. Scene.prototype.getRenderId = function () {
  22515. return this._renderId;
  22516. };
  22517. Scene.prototype.incrementRenderId = function () {
  22518. this._renderId++;
  22519. };
  22520. Scene.prototype._updatePointerPosition = function (evt) {
  22521. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22522. if (!canvasRect) {
  22523. return;
  22524. }
  22525. this._pointerX = evt.clientX - canvasRect.left;
  22526. this._pointerY = evt.clientY - canvasRect.top;
  22527. this._unTranslatedPointerX = this._pointerX;
  22528. this._unTranslatedPointerY = this._pointerY;
  22529. };
  22530. Scene.prototype._createUbo = function () {
  22531. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22532. this._sceneUbo.addUniform("viewProjection", 16);
  22533. this._sceneUbo.addUniform("view", 16);
  22534. };
  22535. Scene.prototype._createAlternateUbo = function () {
  22536. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22537. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22538. this._alternateSceneUbo.addUniform("view", 16);
  22539. };
  22540. // Pointers handling
  22541. /**
  22542. * Use this method to simulate a pointer move on a mesh
  22543. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22544. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22545. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22546. */
  22547. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22548. var evt = new PointerEvent("pointermove", pointerEventInit);
  22549. return this._processPointerMove(pickResult, evt);
  22550. };
  22551. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22552. var canvas = this._engine.getRenderingCanvas();
  22553. if (!canvas) {
  22554. return this;
  22555. }
  22556. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22557. this.setPointerOverSprite(null);
  22558. this.setPointerOverMesh(pickResult.pickedMesh);
  22559. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22560. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22561. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22562. }
  22563. else {
  22564. canvas.style.cursor = this.hoverCursor;
  22565. }
  22566. }
  22567. else {
  22568. canvas.style.cursor = this.defaultCursor;
  22569. }
  22570. }
  22571. else {
  22572. this.setPointerOverMesh(null);
  22573. // Sprites
  22574. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22575. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22576. this.setPointerOverSprite(pickResult.pickedSprite);
  22577. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22578. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22579. }
  22580. else {
  22581. canvas.style.cursor = this.hoverCursor;
  22582. }
  22583. }
  22584. else {
  22585. this.setPointerOverSprite(null);
  22586. // Restore pointer
  22587. canvas.style.cursor = this.defaultCursor;
  22588. }
  22589. }
  22590. if (pickResult) {
  22591. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22592. if (this.onPointerMove) {
  22593. this.onPointerMove(evt, pickResult, type);
  22594. }
  22595. if (this.onPointerObservable.hasObservers()) {
  22596. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22597. this.onPointerObservable.notifyObservers(pi, type);
  22598. }
  22599. }
  22600. return this;
  22601. };
  22602. /**
  22603. * Use this method to simulate a pointer down on a mesh
  22604. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22605. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22606. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22607. */
  22608. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22609. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22610. return this._processPointerDown(pickResult, evt);
  22611. };
  22612. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22613. var _this = this;
  22614. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22615. this._pickedDownMesh = pickResult.pickedMesh;
  22616. var actionManager = pickResult.pickedMesh.actionManager;
  22617. if (actionManager) {
  22618. if (actionManager.hasPickTriggers) {
  22619. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22620. switch (evt.button) {
  22621. case 0:
  22622. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22623. break;
  22624. case 1:
  22625. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22626. break;
  22627. case 2:
  22628. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22629. break;
  22630. }
  22631. }
  22632. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22633. window.setTimeout(function () {
  22634. 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);
  22635. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22636. if (_this._totalPointersPressed !== 0 &&
  22637. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22638. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22639. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22640. _this._startingPointerTime = 0;
  22641. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22642. }
  22643. }
  22644. }, Scene.LongPressDelay);
  22645. }
  22646. }
  22647. }
  22648. if (pickResult) {
  22649. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22650. if (this.onPointerDown) {
  22651. this.onPointerDown(evt, pickResult, type);
  22652. }
  22653. if (this.onPointerObservable.hasObservers()) {
  22654. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22655. this.onPointerObservable.notifyObservers(pi, type);
  22656. }
  22657. }
  22658. return this;
  22659. };
  22660. /**
  22661. * Use this method to simulate a pointer up on a mesh
  22662. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22663. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22664. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22665. */
  22666. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22667. var evt = new PointerEvent("pointerup", pointerEventInit);
  22668. var clickInfo = new ClickInfo();
  22669. clickInfo.singleClick = true;
  22670. clickInfo.ignore = true;
  22671. return this._processPointerUp(pickResult, evt, clickInfo);
  22672. };
  22673. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22674. if (pickResult && pickResult && pickResult.pickedMesh) {
  22675. this._pickedUpMesh = pickResult.pickedMesh;
  22676. if (this._pickedDownMesh === this._pickedUpMesh) {
  22677. if (this.onPointerPick) {
  22678. this.onPointerPick(evt, pickResult);
  22679. }
  22680. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22681. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22682. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22683. this.onPointerObservable.notifyObservers(pi, type_1);
  22684. }
  22685. }
  22686. if (pickResult.pickedMesh.actionManager) {
  22687. if (clickInfo.ignore) {
  22688. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22689. }
  22690. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22691. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22692. }
  22693. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22694. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22695. }
  22696. }
  22697. }
  22698. if (this._pickedDownMesh &&
  22699. this._pickedDownMesh.actionManager &&
  22700. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22701. this._pickedDownMesh !== this._pickedUpMesh) {
  22702. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22703. }
  22704. var type = BABYLON.PointerEventTypes.POINTERUP;
  22705. if (this.onPointerObservable.hasObservers()) {
  22706. if (!clickInfo.ignore) {
  22707. if (!clickInfo.hasSwiped) {
  22708. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22709. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22710. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22711. this.onPointerObservable.notifyObservers(pi, type_2);
  22712. }
  22713. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22714. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22715. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22716. this.onPointerObservable.notifyObservers(pi, type_3);
  22717. }
  22718. }
  22719. }
  22720. else {
  22721. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22722. this.onPointerObservable.notifyObservers(pi, type);
  22723. }
  22724. }
  22725. if (this.onPointerUp) {
  22726. this.onPointerUp(evt, pickResult, type);
  22727. }
  22728. return this;
  22729. };
  22730. /**
  22731. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22732. * @param attachUp defines if you want to attach events to pointerup
  22733. * @param attachDown defines if you want to attach events to pointerdown
  22734. * @param attachMove defines if you want to attach events to pointermove
  22735. */
  22736. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22737. var _this = this;
  22738. if (attachUp === void 0) { attachUp = true; }
  22739. if (attachDown === void 0) { attachDown = true; }
  22740. if (attachMove === void 0) { attachMove = true; }
  22741. this._initActionManager = function (act, clickInfo) {
  22742. if (!_this._meshPickProceed) {
  22743. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22744. _this._currentPickResult = pickResult;
  22745. if (pickResult) {
  22746. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22747. }
  22748. _this._meshPickProceed = true;
  22749. }
  22750. return act;
  22751. };
  22752. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22753. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22754. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22755. btn !== _this._previousButtonPressed) {
  22756. _this._doubleClickOccured = false;
  22757. clickInfo.singleClick = true;
  22758. clickInfo.ignore = false;
  22759. cb(clickInfo, _this._currentPickResult);
  22760. }
  22761. };
  22762. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22763. var clickInfo = new ClickInfo();
  22764. _this._currentPickResult = null;
  22765. var act = null;
  22766. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22767. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22768. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22769. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22770. act = _this._initActionManager(act, clickInfo);
  22771. if (act)
  22772. checkPicking = act.hasPickTriggers;
  22773. }
  22774. if (checkPicking) {
  22775. var btn = evt.button;
  22776. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22777. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22778. if (!clickInfo.hasSwiped) {
  22779. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22780. if (!checkSingleClickImmediately) {
  22781. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22782. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22783. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22784. act = _this._initActionManager(act, clickInfo);
  22785. if (act)
  22786. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22787. }
  22788. }
  22789. if (checkSingleClickImmediately) {
  22790. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22791. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22792. btn !== _this._previousButtonPressed) {
  22793. clickInfo.singleClick = true;
  22794. cb(clickInfo, _this._currentPickResult);
  22795. }
  22796. }
  22797. else {
  22798. // wait that no double click has been raised during the double click delay
  22799. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22800. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22801. }
  22802. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22803. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22804. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22805. act = _this._initActionManager(act, clickInfo);
  22806. if (act)
  22807. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22808. }
  22809. if (checkDoubleClick) {
  22810. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22811. if (btn === _this._previousButtonPressed &&
  22812. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22813. !_this._doubleClickOccured) {
  22814. // pointer has not moved for 2 clicks, it's a double click
  22815. if (!clickInfo.hasSwiped &&
  22816. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22817. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22818. _this._previousStartingPointerTime = 0;
  22819. _this._doubleClickOccured = true;
  22820. clickInfo.doubleClick = true;
  22821. clickInfo.ignore = false;
  22822. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22823. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22824. }
  22825. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22826. cb(clickInfo, _this._currentPickResult);
  22827. }
  22828. else {
  22829. _this._doubleClickOccured = false;
  22830. _this._previousStartingPointerTime = _this._startingPointerTime;
  22831. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22832. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22833. _this._previousButtonPressed = btn;
  22834. if (Scene.ExclusiveDoubleClickMode) {
  22835. if (_this._previousDelayedSimpleClickTimeout) {
  22836. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22837. }
  22838. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22839. cb(clickInfo, _this._previousPickResult);
  22840. }
  22841. else {
  22842. cb(clickInfo, _this._currentPickResult);
  22843. }
  22844. }
  22845. }
  22846. else {
  22847. _this._doubleClickOccured = false;
  22848. _this._previousStartingPointerTime = _this._startingPointerTime;
  22849. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22850. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22851. _this._previousButtonPressed = btn;
  22852. }
  22853. }
  22854. }
  22855. }
  22856. clickInfo.ignore = true;
  22857. cb(clickInfo, _this._currentPickResult);
  22858. };
  22859. this._spritePredicate = function (sprite) {
  22860. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22861. };
  22862. this._onPointerMove = function (evt) {
  22863. _this._updatePointerPosition(evt);
  22864. // PreObservable support
  22865. if (_this.onPrePointerObservable.hasObservers()) {
  22866. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22867. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22868. _this.onPrePointerObservable.notifyObservers(pi, type);
  22869. if (pi.skipOnPointerObservable) {
  22870. return;
  22871. }
  22872. }
  22873. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22874. return;
  22875. }
  22876. if (!_this.pointerMovePredicate) {
  22877. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22878. }
  22879. // Meshes
  22880. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22881. _this._processPointerMove(pickResult, evt);
  22882. };
  22883. this._onPointerDown = function (evt) {
  22884. _this._totalPointersPressed++;
  22885. _this._pickedDownMesh = null;
  22886. _this._meshPickProceed = false;
  22887. _this._updatePointerPosition(evt);
  22888. if (_this.preventDefaultOnPointerDown && canvas) {
  22889. evt.preventDefault();
  22890. canvas.focus();
  22891. }
  22892. // PreObservable support
  22893. if (_this.onPrePointerObservable.hasObservers()) {
  22894. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22895. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22896. _this.onPrePointerObservable.notifyObservers(pi, type);
  22897. if (pi.skipOnPointerObservable) {
  22898. return;
  22899. }
  22900. }
  22901. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22902. return;
  22903. }
  22904. _this._startingPointerPosition.x = _this._pointerX;
  22905. _this._startingPointerPosition.y = _this._pointerY;
  22906. _this._startingPointerTime = new Date().getTime();
  22907. if (!_this.pointerDownPredicate) {
  22908. _this.pointerDownPredicate = function (mesh) {
  22909. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22910. };
  22911. }
  22912. // Meshes
  22913. _this._pickedDownMesh = null;
  22914. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22915. _this._processPointerDown(pickResult, evt);
  22916. // Sprites
  22917. _this._pickedDownSprite = null;
  22918. if (_this.spriteManagers.length > 0) {
  22919. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22920. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22921. if (pickResult.pickedSprite.actionManager) {
  22922. _this._pickedDownSprite = pickResult.pickedSprite;
  22923. switch (evt.button) {
  22924. case 0:
  22925. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22926. break;
  22927. case 1:
  22928. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22929. break;
  22930. case 2:
  22931. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22932. break;
  22933. }
  22934. if (pickResult.pickedSprite.actionManager) {
  22935. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22936. }
  22937. }
  22938. }
  22939. }
  22940. };
  22941. this._onPointerUp = function (evt) {
  22942. if (_this._totalPointersPressed === 0) {
  22943. return; // So we need to test it the pointer down was pressed before.
  22944. }
  22945. _this._totalPointersPressed--;
  22946. _this._pickedUpMesh = null;
  22947. _this._meshPickProceed = false;
  22948. _this._updatePointerPosition(evt);
  22949. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22950. // PreObservable support
  22951. if (_this.onPrePointerObservable.hasObservers()) {
  22952. if (!clickInfo.ignore) {
  22953. if (!clickInfo.hasSwiped) {
  22954. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22955. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22956. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22957. _this.onPrePointerObservable.notifyObservers(pi, type);
  22958. if (pi.skipOnPointerObservable) {
  22959. return;
  22960. }
  22961. }
  22962. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22963. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22964. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22965. _this.onPrePointerObservable.notifyObservers(pi, type);
  22966. if (pi.skipOnPointerObservable) {
  22967. return;
  22968. }
  22969. }
  22970. }
  22971. }
  22972. else {
  22973. var type = BABYLON.PointerEventTypes.POINTERUP;
  22974. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22975. _this.onPrePointerObservable.notifyObservers(pi, type);
  22976. if (pi.skipOnPointerObservable) {
  22977. return;
  22978. }
  22979. }
  22980. }
  22981. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22982. return;
  22983. }
  22984. if (!_this.pointerUpPredicate) {
  22985. _this.pointerUpPredicate = function (mesh) {
  22986. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22987. };
  22988. }
  22989. // Meshes
  22990. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22991. _this._initActionManager(null, clickInfo);
  22992. }
  22993. if (!pickResult) {
  22994. pickResult = _this._currentPickResult;
  22995. }
  22996. _this._processPointerUp(pickResult, evt, clickInfo);
  22997. // Sprites
  22998. if (_this.spriteManagers.length > 0) {
  22999. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23000. if (spritePickResult) {
  23001. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23002. if (spritePickResult.pickedSprite.actionManager) {
  23003. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23004. if (spritePickResult.pickedSprite.actionManager) {
  23005. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23006. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23007. }
  23008. }
  23009. }
  23010. }
  23011. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23012. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23013. }
  23014. }
  23015. }
  23016. _this._previousPickResult = _this._currentPickResult;
  23017. });
  23018. };
  23019. this._onKeyDown = function (evt) {
  23020. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23021. if (_this.onPreKeyboardObservable.hasObservers()) {
  23022. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23023. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23024. if (pi.skipOnPointerObservable) {
  23025. return;
  23026. }
  23027. }
  23028. if (_this.onKeyboardObservable.hasObservers()) {
  23029. var pi = new BABYLON.KeyboardInfo(type, evt);
  23030. _this.onKeyboardObservable.notifyObservers(pi, type);
  23031. }
  23032. if (_this.actionManager) {
  23033. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23034. }
  23035. };
  23036. this._onKeyUp = function (evt) {
  23037. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23038. if (_this.onPreKeyboardObservable.hasObservers()) {
  23039. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23040. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23041. if (pi.skipOnPointerObservable) {
  23042. return;
  23043. }
  23044. }
  23045. if (_this.onKeyboardObservable.hasObservers()) {
  23046. var pi = new BABYLON.KeyboardInfo(type, evt);
  23047. _this.onKeyboardObservable.notifyObservers(pi, type);
  23048. }
  23049. if (_this.actionManager) {
  23050. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23051. }
  23052. };
  23053. var engine = this.getEngine();
  23054. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23055. if (!canvas) {
  23056. return;
  23057. }
  23058. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23059. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23060. });
  23061. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23062. if (!canvas) {
  23063. return;
  23064. }
  23065. canvas.removeEventListener("keydown", _this._onKeyDown);
  23066. canvas.removeEventListener("keyup", _this._onKeyUp);
  23067. });
  23068. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23069. var canvas = this._engine.getRenderingCanvas();
  23070. if (!canvas) {
  23071. return;
  23072. }
  23073. if (attachMove) {
  23074. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23075. // Wheel
  23076. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23077. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23078. }
  23079. if (attachDown) {
  23080. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23081. }
  23082. if (attachUp) {
  23083. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23084. }
  23085. canvas.tabIndex = 1;
  23086. };
  23087. Scene.prototype.detachControl = function () {
  23088. var engine = this.getEngine();
  23089. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23090. var canvas = engine.getRenderingCanvas();
  23091. if (!canvas) {
  23092. return;
  23093. }
  23094. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23095. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23096. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23097. if (this._onCanvasBlurObserver) {
  23098. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23099. }
  23100. if (this._onCanvasFocusObserver) {
  23101. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23102. }
  23103. // Wheel
  23104. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23105. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23106. // Keyboard
  23107. canvas.removeEventListener("keydown", this._onKeyDown);
  23108. canvas.removeEventListener("keyup", this._onKeyUp);
  23109. // Observables
  23110. this.onKeyboardObservable.clear();
  23111. this.onPreKeyboardObservable.clear();
  23112. this.onPointerObservable.clear();
  23113. this.onPrePointerObservable.clear();
  23114. };
  23115. /**
  23116. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23117. * Delay loaded resources are not taking in account
  23118. * @return true if all required resources are ready
  23119. */
  23120. Scene.prototype.isReady = function () {
  23121. if (this._isDisposed) {
  23122. return false;
  23123. }
  23124. if (this._pendingData.length > 0) {
  23125. return false;
  23126. }
  23127. var index;
  23128. var engine = this.getEngine();
  23129. // Geometries
  23130. for (index = 0; index < this._geometries.length; index++) {
  23131. var geometry = this._geometries[index];
  23132. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23133. return false;
  23134. }
  23135. }
  23136. // Meshes
  23137. for (index = 0; index < this.meshes.length; index++) {
  23138. var mesh = this.meshes[index];
  23139. if (!mesh.isEnabled()) {
  23140. continue;
  23141. }
  23142. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23143. continue;
  23144. }
  23145. if (!mesh.isReady(true)) {
  23146. return false;
  23147. }
  23148. // Effect layers
  23149. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23150. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23151. var layer = _a[_i];
  23152. if (!layer.hasMesh(mesh)) {
  23153. continue;
  23154. }
  23155. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23156. var subMesh = _c[_b];
  23157. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23158. return false;
  23159. }
  23160. }
  23161. }
  23162. }
  23163. // Particles
  23164. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  23165. var particleSystem = _e[_d];
  23166. if (!particleSystem.isReady()) {
  23167. return false;
  23168. }
  23169. }
  23170. return true;
  23171. };
  23172. Scene.prototype.resetCachedMaterial = function () {
  23173. this._cachedMaterial = null;
  23174. this._cachedEffect = null;
  23175. this._cachedVisibility = null;
  23176. };
  23177. Scene.prototype.registerBeforeRender = function (func) {
  23178. this.onBeforeRenderObservable.add(func);
  23179. };
  23180. Scene.prototype.unregisterBeforeRender = function (func) {
  23181. this.onBeforeRenderObservable.removeCallback(func);
  23182. };
  23183. Scene.prototype.registerAfterRender = function (func) {
  23184. this.onAfterRenderObservable.add(func);
  23185. };
  23186. Scene.prototype.unregisterAfterRender = function (func) {
  23187. this.onAfterRenderObservable.removeCallback(func);
  23188. };
  23189. Scene.prototype._executeOnceBeforeRender = function (func) {
  23190. var _this = this;
  23191. var execFunc = function () {
  23192. func();
  23193. setTimeout(function () {
  23194. _this.unregisterBeforeRender(execFunc);
  23195. });
  23196. };
  23197. this.registerBeforeRender(execFunc);
  23198. };
  23199. /**
  23200. * The provided function will run before render once and will be disposed afterwards.
  23201. * A timeout delay can be provided so that the function will be executed in N ms.
  23202. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23203. * @param func The function to be executed.
  23204. * @param timeout optional delay in ms
  23205. */
  23206. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23207. var _this = this;
  23208. if (timeout !== undefined) {
  23209. setTimeout(function () {
  23210. _this._executeOnceBeforeRender(func);
  23211. }, timeout);
  23212. }
  23213. else {
  23214. this._executeOnceBeforeRender(func);
  23215. }
  23216. };
  23217. Scene.prototype._addPendingData = function (data) {
  23218. this._pendingData.push(data);
  23219. };
  23220. Scene.prototype._removePendingData = function (data) {
  23221. var wasLoading = this.isLoading;
  23222. var index = this._pendingData.indexOf(data);
  23223. if (index !== -1) {
  23224. this._pendingData.splice(index, 1);
  23225. }
  23226. if (wasLoading && !this.isLoading) {
  23227. this.onDataLoadedObservable.notifyObservers(this);
  23228. }
  23229. };
  23230. Scene.prototype.getWaitingItemsCount = function () {
  23231. return this._pendingData.length;
  23232. };
  23233. Object.defineProperty(Scene.prototype, "isLoading", {
  23234. get: function () {
  23235. return this._pendingData.length > 0;
  23236. },
  23237. enumerable: true,
  23238. configurable: true
  23239. });
  23240. /**
  23241. * Registers a function to be executed when the scene is ready.
  23242. * @param {Function} func - the function to be executed.
  23243. */
  23244. Scene.prototype.executeWhenReady = function (func) {
  23245. var _this = this;
  23246. this.onReadyObservable.add(func);
  23247. if (this._executeWhenReadyTimeoutId !== -1) {
  23248. return;
  23249. }
  23250. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23251. _this._checkIsReady();
  23252. }, 150);
  23253. };
  23254. /**
  23255. * Returns a promise that resolves when the scene is ready.
  23256. * @returns A promise that resolves when the scene is ready.
  23257. */
  23258. Scene.prototype.whenReadyAsync = function () {
  23259. var _this = this;
  23260. return new Promise(function (resolve) {
  23261. _this.executeWhenReady(function () {
  23262. resolve();
  23263. });
  23264. });
  23265. };
  23266. Scene.prototype._checkIsReady = function () {
  23267. var _this = this;
  23268. if (this.isReady()) {
  23269. this.onReadyObservable.notifyObservers(this);
  23270. this.onReadyObservable.clear();
  23271. this._executeWhenReadyTimeoutId = -1;
  23272. return;
  23273. }
  23274. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23275. _this._checkIsReady();
  23276. }, 150);
  23277. };
  23278. // Animations
  23279. /**
  23280. * Will start the animation sequence of a given target
  23281. * @param target defines the target
  23282. * @param from defines from which frame should animation start
  23283. * @param to defines until which frame should animation run.
  23284. * @param weight defines the weight to apply to the animation (1.0 by default)
  23285. * @param loop defines if the animation loops
  23286. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23287. * @param onAnimationEnd defines the function to be executed when the animation ends
  23288. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23289. * @returns the animatable object created for this animation
  23290. * @see BABYLON.Animatable
  23291. */
  23292. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23293. if (weight === void 0) { weight = 1.0; }
  23294. if (speedRatio === void 0) { speedRatio = 1.0; }
  23295. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23296. returnedAnimatable.weight = weight;
  23297. return returnedAnimatable;
  23298. };
  23299. /**
  23300. * Will start the animation sequence of a given target
  23301. * @param target defines the target
  23302. * @param from defines from which frame should animation start
  23303. * @param to defines until which frame should animation run.
  23304. * @param loop defines if the animation loops
  23305. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23306. * @param onAnimationEnd defines the function to be executed when the animation ends
  23307. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23308. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23309. * @returns the animatable object created for this animation
  23310. * @see BABYLON.Animatable
  23311. */
  23312. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23313. if (speedRatio === void 0) { speedRatio = 1.0; }
  23314. if (stopCurrent === void 0) { stopCurrent = true; }
  23315. if (from > to && speedRatio > 0) {
  23316. speedRatio *= -1;
  23317. }
  23318. if (stopCurrent) {
  23319. this.stopAnimation(target);
  23320. }
  23321. if (!animatable) {
  23322. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23323. }
  23324. // Local animations
  23325. if (target.animations) {
  23326. animatable.appendAnimations(target, target.animations);
  23327. }
  23328. // Children animations
  23329. if (target.getAnimatables) {
  23330. var animatables = target.getAnimatables();
  23331. for (var index = 0; index < animatables.length; index++) {
  23332. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23333. }
  23334. }
  23335. animatable.reset();
  23336. return animatable;
  23337. };
  23338. /**
  23339. * Begin a new animation on a given node
  23340. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23341. * @param {BABYLON.Animation[]} defines the list of animations to start
  23342. * @param {number} from defines the initial value
  23343. * @param {number} to defines the final value
  23344. * @param {boolean} loop defines if you want animation to loop (off by default)
  23345. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23346. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23347. * @returns the list of created animatables
  23348. */
  23349. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23350. if (speedRatio === undefined) {
  23351. speedRatio = 1.0;
  23352. }
  23353. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23354. return animatable;
  23355. };
  23356. /**
  23357. * Begin a new animation on a given node and its hierarchy
  23358. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23359. * @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.
  23360. * @param {BABYLON.Animation[]} defines the list of animations to start
  23361. * @param {number} from defines the initial value
  23362. * @param {number} to defines the final value
  23363. * @param {boolean} loop defines if you want animation to loop (off by default)
  23364. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23365. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23366. * @returns the list of animatables created for all nodes
  23367. */
  23368. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23369. var children = target.getDescendants(directDescendantsOnly);
  23370. var result = [];
  23371. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23372. var child = children_1[_i];
  23373. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23374. }
  23375. return result;
  23376. };
  23377. Scene.prototype.getAnimatableByTarget = function (target) {
  23378. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23379. if (this._activeAnimatables[index].target === target) {
  23380. return this._activeAnimatables[index];
  23381. }
  23382. }
  23383. return null;
  23384. };
  23385. /**
  23386. * Gets all animatables associated with a given target
  23387. * @param target defines the target to look animatables for
  23388. * @returns an array of Animatables
  23389. */
  23390. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23391. var result = [];
  23392. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23393. if (this._activeAnimatables[index].target === target) {
  23394. result.push(this._activeAnimatables[index]);
  23395. }
  23396. }
  23397. return result;
  23398. };
  23399. Object.defineProperty(Scene.prototype, "animatables", {
  23400. get: function () {
  23401. return this._activeAnimatables;
  23402. },
  23403. enumerable: true,
  23404. configurable: true
  23405. });
  23406. /**
  23407. * Will stop the animation of the given target
  23408. * @param target - the target
  23409. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23410. * @see beginAnimation
  23411. */
  23412. Scene.prototype.stopAnimation = function (target, animationName) {
  23413. var animatables = this.getAllAnimatablesByTarget(target);
  23414. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23415. var animatable = animatables_1[_i];
  23416. animatable.stop(animationName);
  23417. }
  23418. };
  23419. /**
  23420. * Stops and removes all animations that have been applied to the scene
  23421. */
  23422. Scene.prototype.stopAllAnimations = function () {
  23423. if (this._activeAnimatables) {
  23424. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23425. this._activeAnimatables[i].stop();
  23426. }
  23427. this._activeAnimatables = [];
  23428. }
  23429. };
  23430. Scene.prototype._animate = function () {
  23431. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23432. return;
  23433. }
  23434. // Getting time
  23435. var now = BABYLON.Tools.Now;
  23436. if (!this._animationTimeLast) {
  23437. if (this._pendingData.length > 0) {
  23438. return;
  23439. }
  23440. this._animationTimeLast = now;
  23441. }
  23442. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23443. this._animationTime += deltaTime;
  23444. this._animationTimeLast = now;
  23445. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23446. this._activeAnimatables[index]._animate(this._animationTime);
  23447. }
  23448. // Late animation bindings
  23449. this._processLateAnimationBindings();
  23450. };
  23451. /** @ignore */
  23452. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23453. var target = runtimeAnimation.target;
  23454. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23455. if (!target._lateAnimationHolders) {
  23456. target._lateAnimationHolders = {};
  23457. }
  23458. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23459. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23460. totalWeight: 0,
  23461. animations: []
  23462. };
  23463. }
  23464. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23465. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23466. };
  23467. Scene.prototype._processLateAnimationBindings = function () {
  23468. if (!this._registeredForLateAnimationBindings.length) {
  23469. return;
  23470. }
  23471. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23472. var target = this._registeredForLateAnimationBindings.data[index];
  23473. for (var path in target._lateAnimationHolders) {
  23474. var holder = target._lateAnimationHolders[path];
  23475. // Sanity check
  23476. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23477. continue;
  23478. }
  23479. var normalizer = 1.0;
  23480. var finalValue = void 0;
  23481. if (holder.totalWeight < 1.0) {
  23482. // We need to mix the original value in
  23483. var originalValue = holder.animations[0].originalValue;
  23484. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23485. }
  23486. else {
  23487. // We need to normalize the weights
  23488. normalizer = holder.totalWeight;
  23489. }
  23490. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23491. var runtimeAnimation = holder.animations[animIndex];
  23492. if (finalValue) {
  23493. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23494. }
  23495. else {
  23496. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23497. }
  23498. }
  23499. runtimeAnimation.target[path] = finalValue;
  23500. }
  23501. target._lateAnimationHolders = {};
  23502. }
  23503. this._registeredForLateAnimationBindings.reset();
  23504. };
  23505. // Matrix
  23506. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23507. this._useAlternateCameraConfiguration = active;
  23508. };
  23509. Scene.prototype.getViewMatrix = function () {
  23510. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23511. };
  23512. Scene.prototype.getProjectionMatrix = function () {
  23513. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23514. };
  23515. Scene.prototype.getTransformMatrix = function () {
  23516. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23517. };
  23518. Scene.prototype.setTransformMatrix = function (view, projection) {
  23519. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23520. return;
  23521. }
  23522. this._viewUpdateFlag = view.updateFlag;
  23523. this._projectionUpdateFlag = projection.updateFlag;
  23524. this._viewMatrix = view;
  23525. this._projectionMatrix = projection;
  23526. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23527. // Update frustum
  23528. if (!this._frustumPlanes) {
  23529. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23530. }
  23531. else {
  23532. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23533. }
  23534. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23535. var otherCamera = this.activeCamera._alternateCamera;
  23536. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23537. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23538. }
  23539. if (this._sceneUbo.useUbo) {
  23540. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23541. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23542. this._sceneUbo.update();
  23543. }
  23544. };
  23545. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23546. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23547. return;
  23548. }
  23549. this._alternateViewUpdateFlag = view.updateFlag;
  23550. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23551. this._alternateViewMatrix = view;
  23552. this._alternateProjectionMatrix = projection;
  23553. if (!this._alternateTransformMatrix) {
  23554. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23555. }
  23556. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23557. if (!this._alternateSceneUbo) {
  23558. this._createAlternateUbo();
  23559. }
  23560. if (this._alternateSceneUbo.useUbo) {
  23561. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23562. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23563. this._alternateSceneUbo.update();
  23564. }
  23565. };
  23566. Scene.prototype.getSceneUniformBuffer = function () {
  23567. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23568. };
  23569. // Methods
  23570. Scene.prototype.getUniqueId = function () {
  23571. var result = Scene._uniqueIdCounter;
  23572. Scene._uniqueIdCounter++;
  23573. return result;
  23574. };
  23575. Scene.prototype.addMesh = function (newMesh) {
  23576. this.meshes.push(newMesh);
  23577. //notify the collision coordinator
  23578. if (this.collisionCoordinator) {
  23579. this.collisionCoordinator.onMeshAdded(newMesh);
  23580. }
  23581. newMesh._resyncLightSources();
  23582. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23583. };
  23584. Scene.prototype.removeMesh = function (toRemove) {
  23585. var index = this.meshes.indexOf(toRemove);
  23586. if (index !== -1) {
  23587. // Remove from the scene if mesh found
  23588. this.meshes.splice(index, 1);
  23589. }
  23590. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23591. return index;
  23592. };
  23593. Scene.prototype.addTransformNode = function (newTransformNode) {
  23594. this.transformNodes.push(newTransformNode);
  23595. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23596. };
  23597. Scene.prototype.removeTransformNode = function (toRemove) {
  23598. var index = this.transformNodes.indexOf(toRemove);
  23599. if (index !== -1) {
  23600. // Remove from the scene if found
  23601. this.transformNodes.splice(index, 1);
  23602. }
  23603. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23604. return index;
  23605. };
  23606. Scene.prototype.removeSkeleton = function (toRemove) {
  23607. var index = this.skeletons.indexOf(toRemove);
  23608. if (index !== -1) {
  23609. // Remove from the scene if found
  23610. this.skeletons.splice(index, 1);
  23611. }
  23612. return index;
  23613. };
  23614. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23615. var index = this.morphTargetManagers.indexOf(toRemove);
  23616. if (index !== -1) {
  23617. // Remove from the scene if found
  23618. this.morphTargetManagers.splice(index, 1);
  23619. }
  23620. return index;
  23621. };
  23622. Scene.prototype.removeLight = function (toRemove) {
  23623. var index = this.lights.indexOf(toRemove);
  23624. if (index !== -1) {
  23625. // Remove from meshes
  23626. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23627. var mesh = _a[_i];
  23628. mesh._removeLightSource(toRemove);
  23629. }
  23630. // Remove from the scene if mesh found
  23631. this.lights.splice(index, 1);
  23632. this.sortLightsByPriority();
  23633. }
  23634. this.onLightRemovedObservable.notifyObservers(toRemove);
  23635. return index;
  23636. };
  23637. Scene.prototype.removeCamera = function (toRemove) {
  23638. var index = this.cameras.indexOf(toRemove);
  23639. if (index !== -1) {
  23640. // Remove from the scene if mesh found
  23641. this.cameras.splice(index, 1);
  23642. }
  23643. // Remove from activeCameras
  23644. var index2 = this.activeCameras.indexOf(toRemove);
  23645. if (index2 !== -1) {
  23646. // Remove from the scene if mesh found
  23647. this.activeCameras.splice(index2, 1);
  23648. }
  23649. // Reset the activeCamera
  23650. if (this.activeCamera === toRemove) {
  23651. if (this.cameras.length > 0) {
  23652. this.activeCamera = this.cameras[0];
  23653. }
  23654. else {
  23655. this.activeCamera = null;
  23656. }
  23657. }
  23658. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23659. return index;
  23660. };
  23661. Scene.prototype.removeParticleSystem = function (toRemove) {
  23662. var index = this.particleSystems.indexOf(toRemove);
  23663. if (index !== -1) {
  23664. this.particleSystems.splice(index, 1);
  23665. }
  23666. return index;
  23667. };
  23668. ;
  23669. Scene.prototype.removeAnimation = function (toRemove) {
  23670. var index = this.animations.indexOf(toRemove);
  23671. if (index !== -1) {
  23672. this.animations.splice(index, 1);
  23673. }
  23674. return index;
  23675. };
  23676. ;
  23677. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23678. var index = this.multiMaterials.indexOf(toRemove);
  23679. if (index !== -1) {
  23680. this.multiMaterials.splice(index, 1);
  23681. }
  23682. return index;
  23683. };
  23684. ;
  23685. Scene.prototype.removeMaterial = function (toRemove) {
  23686. var index = this.materials.indexOf(toRemove);
  23687. if (index !== -1) {
  23688. this.materials.splice(index, 1);
  23689. }
  23690. return index;
  23691. };
  23692. ;
  23693. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23694. var index = this.lensFlareSystems.indexOf(toRemove);
  23695. if (index !== -1) {
  23696. this.lensFlareSystems.splice(index, 1);
  23697. }
  23698. return index;
  23699. };
  23700. ;
  23701. Scene.prototype.removeActionManager = function (toRemove) {
  23702. var index = this._actionManagers.indexOf(toRemove);
  23703. if (index !== -1) {
  23704. this._actionManagers.splice(index, 1);
  23705. }
  23706. return index;
  23707. };
  23708. ;
  23709. Scene.prototype.addLight = function (newLight) {
  23710. this.lights.push(newLight);
  23711. this.sortLightsByPriority();
  23712. // Add light to all meshes (To support if the light is removed and then readded)
  23713. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23714. var mesh = _a[_i];
  23715. if (mesh._lightSources.indexOf(newLight) === -1) {
  23716. mesh._lightSources.push(newLight);
  23717. mesh._resyncLightSources();
  23718. }
  23719. }
  23720. this.onNewLightAddedObservable.notifyObservers(newLight);
  23721. };
  23722. Scene.prototype.sortLightsByPriority = function () {
  23723. if (this.requireLightSorting) {
  23724. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23725. }
  23726. };
  23727. Scene.prototype.addCamera = function (newCamera) {
  23728. this.cameras.push(newCamera);
  23729. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23730. };
  23731. Scene.prototype.addSkeleton = function (newSkeleton) {
  23732. this.skeletons.push(newSkeleton);
  23733. };
  23734. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23735. this.particleSystems.push(newParticleSystem);
  23736. };
  23737. Scene.prototype.addAnimation = function (newAnimation) {
  23738. this.animations.push(newAnimation);
  23739. };
  23740. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23741. this.multiMaterials.push(newMultiMaterial);
  23742. };
  23743. Scene.prototype.addMaterial = function (newMaterial) {
  23744. this.materials.push(newMaterial);
  23745. };
  23746. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23747. this.morphTargetManagers.push(newMorphTargetManager);
  23748. };
  23749. Scene.prototype.addGeometry = function (newGeometrie) {
  23750. this._geometries.push(newGeometrie);
  23751. };
  23752. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23753. this.lensFlareSystems.push(newLensFlareSystem);
  23754. };
  23755. Scene.prototype.addActionManager = function (newActionManager) {
  23756. this._actionManagers.push(newActionManager);
  23757. };
  23758. /**
  23759. * Switch active camera
  23760. * @param {Camera} newCamera - new active camera
  23761. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23762. */
  23763. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23764. if (attachControl === void 0) { attachControl = true; }
  23765. var canvas = this._engine.getRenderingCanvas();
  23766. if (!canvas) {
  23767. return;
  23768. }
  23769. if (this.activeCamera) {
  23770. this.activeCamera.detachControl(canvas);
  23771. }
  23772. this.activeCamera = newCamera;
  23773. if (attachControl) {
  23774. newCamera.attachControl(canvas);
  23775. }
  23776. };
  23777. /**
  23778. * sets the active camera of the scene using its ID
  23779. * @param {string} id - the camera's ID
  23780. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23781. * @see activeCamera
  23782. */
  23783. Scene.prototype.setActiveCameraByID = function (id) {
  23784. var camera = this.getCameraByID(id);
  23785. if (camera) {
  23786. this.activeCamera = camera;
  23787. return camera;
  23788. }
  23789. return null;
  23790. };
  23791. /**
  23792. * sets the active camera of the scene using its name
  23793. * @param {string} name - the camera's name
  23794. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23795. * @see activeCamera
  23796. */
  23797. Scene.prototype.setActiveCameraByName = function (name) {
  23798. var camera = this.getCameraByName(name);
  23799. if (camera) {
  23800. this.activeCamera = camera;
  23801. return camera;
  23802. }
  23803. return null;
  23804. };
  23805. /**
  23806. * get an animation group using its name
  23807. * @param {string} the material's name
  23808. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23809. */
  23810. Scene.prototype.getAnimationGroupByName = function (name) {
  23811. for (var index = 0; index < this.animationGroups.length; index++) {
  23812. if (this.animationGroups[index].name === name) {
  23813. return this.animationGroups[index];
  23814. }
  23815. }
  23816. return null;
  23817. };
  23818. /**
  23819. * get a material using its id
  23820. * @param {string} the material's ID
  23821. * @return {BABYLON.Material|null} the material or null if none found.
  23822. */
  23823. Scene.prototype.getMaterialByID = function (id) {
  23824. for (var index = 0; index < this.materials.length; index++) {
  23825. if (this.materials[index].id === id) {
  23826. return this.materials[index];
  23827. }
  23828. }
  23829. return null;
  23830. };
  23831. /**
  23832. * get a material using its name
  23833. * @param {string} the material's name
  23834. * @return {BABYLON.Material|null} the material or null if none found.
  23835. */
  23836. Scene.prototype.getMaterialByName = function (name) {
  23837. for (var index = 0; index < this.materials.length; index++) {
  23838. if (this.materials[index].name === name) {
  23839. return this.materials[index];
  23840. }
  23841. }
  23842. return null;
  23843. };
  23844. Scene.prototype.getLensFlareSystemByName = function (name) {
  23845. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23846. if (this.lensFlareSystems[index].name === name) {
  23847. return this.lensFlareSystems[index];
  23848. }
  23849. }
  23850. return null;
  23851. };
  23852. Scene.prototype.getLensFlareSystemByID = function (id) {
  23853. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23854. if (this.lensFlareSystems[index].id === id) {
  23855. return this.lensFlareSystems[index];
  23856. }
  23857. }
  23858. return null;
  23859. };
  23860. Scene.prototype.getCameraByID = function (id) {
  23861. for (var index = 0; index < this.cameras.length; index++) {
  23862. if (this.cameras[index].id === id) {
  23863. return this.cameras[index];
  23864. }
  23865. }
  23866. return null;
  23867. };
  23868. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23869. for (var index = 0; index < this.cameras.length; index++) {
  23870. if (this.cameras[index].uniqueId === uniqueId) {
  23871. return this.cameras[index];
  23872. }
  23873. }
  23874. return null;
  23875. };
  23876. /**
  23877. * get a camera using its name
  23878. * @param {string} the camera's name
  23879. * @return {BABYLON.Camera|null} the camera or null if none found.
  23880. */
  23881. Scene.prototype.getCameraByName = function (name) {
  23882. for (var index = 0; index < this.cameras.length; index++) {
  23883. if (this.cameras[index].name === name) {
  23884. return this.cameras[index];
  23885. }
  23886. }
  23887. return null;
  23888. };
  23889. /**
  23890. * get a bone using its id
  23891. * @param {string} the bone's id
  23892. * @return {BABYLON.Bone|null} the bone or null if not found
  23893. */
  23894. Scene.prototype.getBoneByID = function (id) {
  23895. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23896. var skeleton = this.skeletons[skeletonIndex];
  23897. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23898. if (skeleton.bones[boneIndex].id === id) {
  23899. return skeleton.bones[boneIndex];
  23900. }
  23901. }
  23902. }
  23903. return null;
  23904. };
  23905. /**
  23906. * get a bone using its id
  23907. * @param {string} the bone's name
  23908. * @return {BABYLON.Bone|null} the bone or null if not found
  23909. */
  23910. Scene.prototype.getBoneByName = function (name) {
  23911. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23912. var skeleton = this.skeletons[skeletonIndex];
  23913. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23914. if (skeleton.bones[boneIndex].name === name) {
  23915. return skeleton.bones[boneIndex];
  23916. }
  23917. }
  23918. }
  23919. return null;
  23920. };
  23921. /**
  23922. * get a light node using its name
  23923. * @param {string} the light's name
  23924. * @return {BABYLON.Light|null} the light or null if none found.
  23925. */
  23926. Scene.prototype.getLightByName = function (name) {
  23927. for (var index = 0; index < this.lights.length; index++) {
  23928. if (this.lights[index].name === name) {
  23929. return this.lights[index];
  23930. }
  23931. }
  23932. return null;
  23933. };
  23934. /**
  23935. * get a light node using its ID
  23936. * @param {string} the light's id
  23937. * @return {BABYLON.Light|null} the light or null if none found.
  23938. */
  23939. Scene.prototype.getLightByID = function (id) {
  23940. for (var index = 0; index < this.lights.length; index++) {
  23941. if (this.lights[index].id === id) {
  23942. return this.lights[index];
  23943. }
  23944. }
  23945. return null;
  23946. };
  23947. /**
  23948. * get a light node using its scene-generated unique ID
  23949. * @param {number} the light's unique id
  23950. * @return {BABYLON.Light|null} the light or null if none found.
  23951. */
  23952. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23953. for (var index = 0; index < this.lights.length; index++) {
  23954. if (this.lights[index].uniqueId === uniqueId) {
  23955. return this.lights[index];
  23956. }
  23957. }
  23958. return null;
  23959. };
  23960. /**
  23961. * get a particle system by id
  23962. * @param id {number} the particle system id
  23963. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23964. */
  23965. Scene.prototype.getParticleSystemByID = function (id) {
  23966. for (var index = 0; index < this.particleSystems.length; index++) {
  23967. if (this.particleSystems[index].id === id) {
  23968. return this.particleSystems[index];
  23969. }
  23970. }
  23971. return null;
  23972. };
  23973. /**
  23974. * get a geometry using its ID
  23975. * @param {string} the geometry's id
  23976. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23977. */
  23978. Scene.prototype.getGeometryByID = function (id) {
  23979. for (var index = 0; index < this._geometries.length; index++) {
  23980. if (this._geometries[index].id === id) {
  23981. return this._geometries[index];
  23982. }
  23983. }
  23984. return null;
  23985. };
  23986. /**
  23987. * add a new geometry to this scene.
  23988. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23989. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23990. * @return {boolean} was the geometry added or not
  23991. */
  23992. Scene.prototype.pushGeometry = function (geometry, force) {
  23993. if (!force && this.getGeometryByID(geometry.id)) {
  23994. return false;
  23995. }
  23996. this._geometries.push(geometry);
  23997. //notify the collision coordinator
  23998. if (this.collisionCoordinator) {
  23999. this.collisionCoordinator.onGeometryAdded(geometry);
  24000. }
  24001. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24002. return true;
  24003. };
  24004. /**
  24005. * Removes an existing geometry
  24006. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24007. * @return {boolean} was the geometry removed or not
  24008. */
  24009. Scene.prototype.removeGeometry = function (geometry) {
  24010. var index = this._geometries.indexOf(geometry);
  24011. if (index > -1) {
  24012. this._geometries.splice(index, 1);
  24013. //notify the collision coordinator
  24014. if (this.collisionCoordinator) {
  24015. this.collisionCoordinator.onGeometryDeleted(geometry);
  24016. }
  24017. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24018. return true;
  24019. }
  24020. return false;
  24021. };
  24022. Scene.prototype.getGeometries = function () {
  24023. return this._geometries;
  24024. };
  24025. /**
  24026. * Get the first added mesh found of a given ID
  24027. * @param {string} id - the id to search for
  24028. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24029. */
  24030. Scene.prototype.getMeshByID = function (id) {
  24031. for (var index = 0; index < this.meshes.length; index++) {
  24032. if (this.meshes[index].id === id) {
  24033. return this.meshes[index];
  24034. }
  24035. }
  24036. return null;
  24037. };
  24038. Scene.prototype.getMeshesByID = function (id) {
  24039. return this.meshes.filter(function (m) {
  24040. return m.id === id;
  24041. });
  24042. };
  24043. /**
  24044. * Get the first added transform node found of a given ID
  24045. * @param {string} id - the id to search for
  24046. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24047. */
  24048. Scene.prototype.getTransformNodeByID = function (id) {
  24049. for (var index = 0; index < this.transformNodes.length; index++) {
  24050. if (this.transformNodes[index].id === id) {
  24051. return this.transformNodes[index];
  24052. }
  24053. }
  24054. return null;
  24055. };
  24056. Scene.prototype.getTransformNodesByID = function (id) {
  24057. return this.transformNodes.filter(function (m) {
  24058. return m.id === id;
  24059. });
  24060. };
  24061. /**
  24062. * Get a mesh with its auto-generated unique id
  24063. * @param {number} uniqueId - the unique id to search for
  24064. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24065. */
  24066. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24067. for (var index = 0; index < this.meshes.length; index++) {
  24068. if (this.meshes[index].uniqueId === uniqueId) {
  24069. return this.meshes[index];
  24070. }
  24071. }
  24072. return null;
  24073. };
  24074. /**
  24075. * Get a the last added mesh found of a given ID
  24076. * @param {string} id - the id to search for
  24077. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24078. */
  24079. Scene.prototype.getLastMeshByID = function (id) {
  24080. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24081. if (this.meshes[index].id === id) {
  24082. return this.meshes[index];
  24083. }
  24084. }
  24085. return null;
  24086. };
  24087. /**
  24088. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24089. * @param {string} id - the id to search for
  24090. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24091. */
  24092. Scene.prototype.getLastEntryByID = function (id) {
  24093. var index;
  24094. for (index = this.meshes.length - 1; index >= 0; index--) {
  24095. if (this.meshes[index].id === id) {
  24096. return this.meshes[index];
  24097. }
  24098. }
  24099. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24100. if (this.transformNodes[index].id === id) {
  24101. return this.transformNodes[index];
  24102. }
  24103. }
  24104. for (index = this.cameras.length - 1; index >= 0; index--) {
  24105. if (this.cameras[index].id === id) {
  24106. return this.cameras[index];
  24107. }
  24108. }
  24109. for (index = this.lights.length - 1; index >= 0; index--) {
  24110. if (this.lights[index].id === id) {
  24111. return this.lights[index];
  24112. }
  24113. }
  24114. return null;
  24115. };
  24116. Scene.prototype.getNodeByID = function (id) {
  24117. var mesh = this.getMeshByID(id);
  24118. if (mesh) {
  24119. return mesh;
  24120. }
  24121. var light = this.getLightByID(id);
  24122. if (light) {
  24123. return light;
  24124. }
  24125. var camera = this.getCameraByID(id);
  24126. if (camera) {
  24127. return camera;
  24128. }
  24129. var bone = this.getBoneByID(id);
  24130. return bone;
  24131. };
  24132. Scene.prototype.getNodeByName = function (name) {
  24133. var mesh = this.getMeshByName(name);
  24134. if (mesh) {
  24135. return mesh;
  24136. }
  24137. var light = this.getLightByName(name);
  24138. if (light) {
  24139. return light;
  24140. }
  24141. var camera = this.getCameraByName(name);
  24142. if (camera) {
  24143. return camera;
  24144. }
  24145. var bone = this.getBoneByName(name);
  24146. return bone;
  24147. };
  24148. Scene.prototype.getMeshByName = function (name) {
  24149. for (var index = 0; index < this.meshes.length; index++) {
  24150. if (this.meshes[index].name === name) {
  24151. return this.meshes[index];
  24152. }
  24153. }
  24154. return null;
  24155. };
  24156. Scene.prototype.getTransformNodeByName = function (name) {
  24157. for (var index = 0; index < this.transformNodes.length; index++) {
  24158. if (this.transformNodes[index].name === name) {
  24159. return this.transformNodes[index];
  24160. }
  24161. }
  24162. return null;
  24163. };
  24164. Scene.prototype.getSoundByName = function (name) {
  24165. var index;
  24166. if (BABYLON.AudioEngine) {
  24167. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24168. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24169. return this.mainSoundTrack.soundCollection[index];
  24170. }
  24171. }
  24172. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24173. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24174. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24175. return this.soundTracks[sdIndex].soundCollection[index];
  24176. }
  24177. }
  24178. }
  24179. }
  24180. return null;
  24181. };
  24182. Scene.prototype.getLastSkeletonByID = function (id) {
  24183. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24184. if (this.skeletons[index].id === id) {
  24185. return this.skeletons[index];
  24186. }
  24187. }
  24188. return null;
  24189. };
  24190. Scene.prototype.getSkeletonById = function (id) {
  24191. for (var index = 0; index < this.skeletons.length; index++) {
  24192. if (this.skeletons[index].id === id) {
  24193. return this.skeletons[index];
  24194. }
  24195. }
  24196. return null;
  24197. };
  24198. Scene.prototype.getSkeletonByName = function (name) {
  24199. for (var index = 0; index < this.skeletons.length; index++) {
  24200. if (this.skeletons[index].name === name) {
  24201. return this.skeletons[index];
  24202. }
  24203. }
  24204. return null;
  24205. };
  24206. Scene.prototype.getMorphTargetManagerById = function (id) {
  24207. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24208. if (this.morphTargetManagers[index].uniqueId === id) {
  24209. return this.morphTargetManagers[index];
  24210. }
  24211. }
  24212. return null;
  24213. };
  24214. Scene.prototype.isActiveMesh = function (mesh) {
  24215. return (this._activeMeshes.indexOf(mesh) !== -1);
  24216. };
  24217. /**
  24218. * Return a the first highlight layer of the scene with a given name.
  24219. * @param name The name of the highlight layer to look for.
  24220. * @return The highlight layer if found otherwise null.
  24221. */
  24222. Scene.prototype.getHighlightLayerByName = function (name) {
  24223. for (var index = 0; index < this.effectLayers.length; index++) {
  24224. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24225. return this.effectLayers[index];
  24226. }
  24227. }
  24228. return null;
  24229. };
  24230. /**
  24231. * Return a the first highlight layer of the scene with a given name.
  24232. * @param name The name of the highlight layer to look for.
  24233. * @return The highlight layer if found otherwise null.
  24234. */
  24235. Scene.prototype.getGlowLayerByName = function (name) {
  24236. for (var index = 0; index < this.effectLayers.length; index++) {
  24237. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24238. return this.effectLayers[index];
  24239. }
  24240. }
  24241. return null;
  24242. };
  24243. Object.defineProperty(Scene.prototype, "uid", {
  24244. /**
  24245. * Return a unique id as a string which can serve as an identifier for the scene
  24246. */
  24247. get: function () {
  24248. if (!this._uid) {
  24249. this._uid = BABYLON.Tools.RandomId();
  24250. }
  24251. return this._uid;
  24252. },
  24253. enumerable: true,
  24254. configurable: true
  24255. });
  24256. /**
  24257. * Add an externaly attached data from its key.
  24258. * This method call will fail and return false, if such key already exists.
  24259. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24260. * @param key the unique key that identifies the data
  24261. * @param data the data object to associate to the key for this Engine instance
  24262. * @return true if no such key were already present and the data was added successfully, false otherwise
  24263. */
  24264. Scene.prototype.addExternalData = function (key, data) {
  24265. if (!this._externalData) {
  24266. this._externalData = new BABYLON.StringDictionary();
  24267. }
  24268. return this._externalData.add(key, data);
  24269. };
  24270. /**
  24271. * Get an externaly attached data from its key
  24272. * @param key the unique key that identifies the data
  24273. * @return the associated data, if present (can be null), or undefined if not present
  24274. */
  24275. Scene.prototype.getExternalData = function (key) {
  24276. if (!this._externalData) {
  24277. return null;
  24278. }
  24279. return this._externalData.get(key);
  24280. };
  24281. /**
  24282. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24283. * @param key the unique key that identifies the data
  24284. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24285. * @return the associated data, can be null if the factory returned null.
  24286. */
  24287. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24288. if (!this._externalData) {
  24289. this._externalData = new BABYLON.StringDictionary();
  24290. }
  24291. return this._externalData.getOrAddWithFactory(key, factory);
  24292. };
  24293. /**
  24294. * Remove an externaly attached data from the Engine instance
  24295. * @param key the unique key that identifies the data
  24296. * @return true if the data was successfully removed, false if it doesn't exist
  24297. */
  24298. Scene.prototype.removeExternalData = function (key) {
  24299. return this._externalData.remove(key);
  24300. };
  24301. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24302. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24303. if (mesh.showSubMeshesBoundingBox) {
  24304. var boundingInfo = subMesh.getBoundingInfo();
  24305. if (boundingInfo !== null && boundingInfo !== undefined) {
  24306. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24307. }
  24308. }
  24309. var material = subMesh.getMaterial();
  24310. if (material !== null && material !== undefined) {
  24311. // Render targets
  24312. if (material.getRenderTargetTextures !== undefined) {
  24313. if (this._processedMaterials.indexOf(material) === -1) {
  24314. this._processedMaterials.push(material);
  24315. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24316. }
  24317. }
  24318. // Dispatch
  24319. this._activeIndices.addCount(subMesh.indexCount, false);
  24320. this._renderingManager.dispatch(subMesh, mesh, material);
  24321. }
  24322. }
  24323. };
  24324. /**
  24325. * Clear the processed materials smart array preventing retention point in material dispose.
  24326. */
  24327. Scene.prototype.freeProcessedMaterials = function () {
  24328. this._processedMaterials.dispose();
  24329. };
  24330. /**
  24331. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24332. */
  24333. Scene.prototype.freeActiveMeshes = function () {
  24334. this._activeMeshes.dispose();
  24335. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24336. this.activeCamera._activeMeshes.dispose();
  24337. }
  24338. if (this.activeCameras) {
  24339. for (var i = 0; i < this.activeCameras.length; i++) {
  24340. var activeCamera = this.activeCameras[i];
  24341. if (activeCamera && activeCamera._activeMeshes) {
  24342. activeCamera._activeMeshes.dispose();
  24343. }
  24344. }
  24345. }
  24346. };
  24347. /**
  24348. * Clear the info related to rendering groups preventing retention points during dispose.
  24349. */
  24350. Scene.prototype.freeRenderingGroups = function () {
  24351. if (this._renderingManager) {
  24352. this._renderingManager.freeRenderingGroups();
  24353. }
  24354. if (this.textures) {
  24355. for (var i = 0; i < this.textures.length; i++) {
  24356. var texture = this.textures[i];
  24357. if (texture && texture.renderList) {
  24358. texture.freeRenderingGroups();
  24359. }
  24360. }
  24361. }
  24362. };
  24363. Scene.prototype._isInIntermediateRendering = function () {
  24364. return this._intermediateRendering;
  24365. };
  24366. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24367. this._activeMeshCandidateProvider = provider;
  24368. };
  24369. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24370. return this._activeMeshCandidateProvider;
  24371. };
  24372. /**
  24373. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24374. */
  24375. Scene.prototype.freezeActiveMeshes = function () {
  24376. if (!this.activeCamera) {
  24377. return this;
  24378. }
  24379. if (!this._frustumPlanes) {
  24380. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24381. }
  24382. this._evaluateActiveMeshes();
  24383. this._activeMeshesFrozen = true;
  24384. return this;
  24385. };
  24386. /**
  24387. * Use this function to restart evaluating active meshes on every frame
  24388. */
  24389. Scene.prototype.unfreezeActiveMeshes = function () {
  24390. this._activeMeshesFrozen = false;
  24391. return this;
  24392. };
  24393. Scene.prototype._evaluateActiveMeshes = function () {
  24394. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24395. return;
  24396. }
  24397. if (!this.activeCamera) {
  24398. return;
  24399. }
  24400. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24401. this.activeCamera._activeMeshes.reset();
  24402. this._activeMeshes.reset();
  24403. this._renderingManager.reset();
  24404. this._processedMaterials.reset();
  24405. this._activeParticleSystems.reset();
  24406. this._activeSkeletons.reset();
  24407. this._softwareSkinnedMeshes.reset();
  24408. if (this._boundingBoxRenderer) {
  24409. this._boundingBoxRenderer.reset();
  24410. }
  24411. // Meshes
  24412. var meshes;
  24413. var len;
  24414. var checkIsEnabled = true;
  24415. // Determine mesh candidates
  24416. if (this._activeMeshCandidateProvider !== undefined) {
  24417. // Use _activeMeshCandidateProvider
  24418. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24419. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24420. if (meshes !== undefined) {
  24421. len = meshes.length;
  24422. }
  24423. else {
  24424. len = 0;
  24425. }
  24426. }
  24427. else if (this._selectionOctree !== undefined) {
  24428. // Octree
  24429. var selection = this._selectionOctree.select(this._frustumPlanes);
  24430. meshes = selection.data;
  24431. len = selection.length;
  24432. }
  24433. else {
  24434. // Full scene traversal
  24435. len = this.meshes.length;
  24436. meshes = this.meshes;
  24437. }
  24438. // Check each mesh
  24439. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24440. mesh = meshes[meshIndex];
  24441. if (mesh.isBlocked) {
  24442. continue;
  24443. }
  24444. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24445. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24446. continue;
  24447. }
  24448. mesh.computeWorldMatrix();
  24449. // Intersections
  24450. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24451. this._meshesForIntersections.pushNoDuplicate(mesh);
  24452. }
  24453. // Switch to current LOD
  24454. meshLOD = mesh.getLOD(this.activeCamera);
  24455. if (meshLOD === undefined || meshLOD === null) {
  24456. continue;
  24457. }
  24458. mesh._preActivate();
  24459. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24460. this._activeMeshes.push(mesh);
  24461. this.activeCamera._activeMeshes.push(mesh);
  24462. mesh._activate(this._renderId);
  24463. if (meshLOD !== mesh) {
  24464. meshLOD._activate(this._renderId);
  24465. }
  24466. this._activeMesh(mesh, meshLOD);
  24467. }
  24468. }
  24469. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24470. // Particle systems
  24471. if (this.particlesEnabled) {
  24472. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24473. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24474. var particleSystem = this.particleSystems[particleIndex];
  24475. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24476. continue;
  24477. }
  24478. var emitter = particleSystem.emitter;
  24479. if (!emitter.position || emitter.isEnabled()) {
  24480. this._activeParticleSystems.push(particleSystem);
  24481. particleSystem.animate();
  24482. this._renderingManager.dispatchParticles(particleSystem);
  24483. }
  24484. }
  24485. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24486. }
  24487. };
  24488. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24489. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24490. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24491. mesh.skeleton.prepare();
  24492. }
  24493. if (!mesh.computeBonesUsingShaders) {
  24494. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24495. }
  24496. }
  24497. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24498. var boundingInfo = sourceMesh.getBoundingInfo();
  24499. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24500. }
  24501. if (mesh !== undefined && mesh !== null
  24502. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24503. // Submeshes Octrees
  24504. var len;
  24505. var subMeshes;
  24506. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24507. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24508. len = intersections.length;
  24509. subMeshes = intersections.data;
  24510. }
  24511. else {
  24512. subMeshes = mesh.subMeshes;
  24513. len = subMeshes.length;
  24514. }
  24515. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24516. subMesh = subMeshes[subIndex];
  24517. this._evaluateSubMesh(subMesh, mesh);
  24518. }
  24519. }
  24520. };
  24521. Scene.prototype.updateTransformMatrix = function (force) {
  24522. if (!this.activeCamera) {
  24523. return;
  24524. }
  24525. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24526. };
  24527. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24528. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24529. };
  24530. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24531. if (camera && camera._skipRendering) {
  24532. return;
  24533. }
  24534. var engine = this._engine;
  24535. this.activeCamera = camera;
  24536. if (!this.activeCamera)
  24537. throw new Error("Active camera not set");
  24538. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24539. // Viewport
  24540. engine.setViewport(this.activeCamera.viewport);
  24541. // Camera
  24542. this.resetCachedMaterial();
  24543. this._renderId++;
  24544. this.updateTransformMatrix();
  24545. if (camera._alternateCamera) {
  24546. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24547. this._alternateRendering = true;
  24548. }
  24549. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24550. // Meshes
  24551. this._evaluateActiveMeshes();
  24552. // Software skinning
  24553. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24554. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24555. mesh.applySkeleton(mesh.skeleton);
  24556. }
  24557. // Render targets
  24558. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24559. var needsRestoreFrameBuffer = false;
  24560. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24561. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24562. }
  24563. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24564. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24565. }
  24566. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24567. this._intermediateRendering = true;
  24568. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24569. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24570. var renderTarget = this._renderTargets.data[renderIndex];
  24571. if (renderTarget._shouldRender()) {
  24572. this._renderId++;
  24573. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24574. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24575. }
  24576. }
  24577. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24578. this._intermediateRendering = false;
  24579. this._renderId++;
  24580. needsRestoreFrameBuffer = true; // Restore back buffer
  24581. }
  24582. // Render EffecttLayer Texture
  24583. var stencilState = this._engine.getStencilBuffer();
  24584. var renderEffects = false;
  24585. var needStencil = false;
  24586. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24587. this._intermediateRendering = true;
  24588. for (var i = 0; i < this.effectLayers.length; i++) {
  24589. var effectLayer = this.effectLayers[i];
  24590. if (effectLayer.shouldRender() &&
  24591. (!effectLayer.camera ||
  24592. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24593. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24594. renderEffects = true;
  24595. needStencil = needStencil || effectLayer.needStencil();
  24596. var renderTarget = effectLayer._mainTexture;
  24597. if (renderTarget._shouldRender()) {
  24598. this._renderId++;
  24599. renderTarget.render(false, false);
  24600. needsRestoreFrameBuffer = true;
  24601. }
  24602. }
  24603. }
  24604. this._intermediateRendering = false;
  24605. this._renderId++;
  24606. }
  24607. if (needsRestoreFrameBuffer) {
  24608. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24609. }
  24610. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24611. // Prepare Frame
  24612. this.postProcessManager._prepareFrame();
  24613. // Backgrounds
  24614. var layerIndex;
  24615. var layer;
  24616. if (this.layers.length) {
  24617. engine.setDepthBuffer(false);
  24618. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24619. layer = this.layers[layerIndex];
  24620. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24621. layer.render();
  24622. }
  24623. }
  24624. engine.setDepthBuffer(true);
  24625. }
  24626. // Activate effect Layer stencil
  24627. if (needStencil) {
  24628. this._engine.setStencilBuffer(true);
  24629. }
  24630. // Render
  24631. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24632. this._renderingManager.render(null, null, true, true);
  24633. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24634. // Restore effect Layer stencil
  24635. if (needStencil) {
  24636. this._engine.setStencilBuffer(stencilState);
  24637. }
  24638. // Bounding boxes
  24639. if (this._boundingBoxRenderer) {
  24640. this._boundingBoxRenderer.render();
  24641. }
  24642. // Lens flares
  24643. if (this.lensFlaresEnabled) {
  24644. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24645. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24646. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24647. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24648. lensFlareSystem.render();
  24649. }
  24650. }
  24651. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24652. }
  24653. // Foregrounds
  24654. if (this.layers.length) {
  24655. engine.setDepthBuffer(false);
  24656. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24657. layer = this.layers[layerIndex];
  24658. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24659. layer.render();
  24660. }
  24661. }
  24662. engine.setDepthBuffer(true);
  24663. }
  24664. // Effect Layer
  24665. if (renderEffects) {
  24666. engine.setDepthBuffer(false);
  24667. for (var i = 0; i < this.effectLayers.length; i++) {
  24668. if (this.effectLayers[i].shouldRender()) {
  24669. this.effectLayers[i].render();
  24670. }
  24671. }
  24672. engine.setDepthBuffer(true);
  24673. }
  24674. // Finalize frame
  24675. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24676. // Reset some special arrays
  24677. this._renderTargets.reset();
  24678. this._alternateRendering = false;
  24679. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24680. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24681. };
  24682. Scene.prototype._processSubCameras = function (camera) {
  24683. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24684. this._renderForCamera(camera);
  24685. return;
  24686. }
  24687. // rig cameras
  24688. for (var index = 0; index < camera._rigCameras.length; index++) {
  24689. this._renderForCamera(camera._rigCameras[index], camera);
  24690. }
  24691. this.activeCamera = camera;
  24692. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24693. };
  24694. Scene.prototype._checkIntersections = function () {
  24695. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24696. var sourceMesh = this._meshesForIntersections.data[index];
  24697. if (!sourceMesh.actionManager) {
  24698. continue;
  24699. }
  24700. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24701. var action = sourceMesh.actionManager.actions[actionIndex];
  24702. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24703. var parameters = action.getTriggerParameter();
  24704. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24705. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24706. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24707. if (areIntersecting && currentIntersectionInProgress === -1) {
  24708. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24709. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24710. sourceMesh._intersectionsInProgress.push(otherMesh);
  24711. }
  24712. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24713. sourceMesh._intersectionsInProgress.push(otherMesh);
  24714. }
  24715. }
  24716. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24717. //They intersected, and now they don't.
  24718. //is this trigger an exit trigger? execute an event.
  24719. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24720. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24721. }
  24722. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24723. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24724. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24725. }
  24726. }
  24727. }
  24728. }
  24729. }
  24730. };
  24731. Scene.prototype.render = function () {
  24732. if (this.isDisposed) {
  24733. return;
  24734. }
  24735. this._activeParticles.fetchNewFrame();
  24736. this._totalVertices.fetchNewFrame();
  24737. this._activeIndices.fetchNewFrame();
  24738. this._activeBones.fetchNewFrame();
  24739. this._meshesForIntersections.reset();
  24740. this.resetCachedMaterial();
  24741. this.onBeforeAnimationsObservable.notifyObservers(this);
  24742. // Actions
  24743. if (this.actionManager) {
  24744. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24745. }
  24746. //Simplification Queue
  24747. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24748. this.simplificationQueue.executeNext();
  24749. }
  24750. if (this._engine.isDeterministicLockStep()) {
  24751. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24752. var defaultFPS = (60.0 / 1000.0);
  24753. var defaultFrameTime = 1000 / 60; // frame time in MS
  24754. if (this._physicsEngine) {
  24755. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24756. }
  24757. var stepsTaken = 0;
  24758. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24759. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24760. internalSteps = Math.min(internalSteps, maxSubSteps);
  24761. do {
  24762. this.onBeforeStepObservable.notifyObservers(this);
  24763. // Animations
  24764. this._animationRatio = defaultFrameTime * defaultFPS;
  24765. this._animate();
  24766. this.onAfterAnimationsObservable.notifyObservers(this);
  24767. // Physics
  24768. if (this._physicsEngine) {
  24769. this.onBeforePhysicsObservable.notifyObservers(this);
  24770. this._physicsEngine._step(defaultFrameTime / 1000);
  24771. this.onAfterPhysicsObservable.notifyObservers(this);
  24772. }
  24773. this.onAfterStepObservable.notifyObservers(this);
  24774. this._currentStepId++;
  24775. stepsTaken++;
  24776. deltaTime -= defaultFrameTime;
  24777. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24778. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24779. }
  24780. else {
  24781. // Animations
  24782. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24783. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24784. this._animate();
  24785. this.onAfterAnimationsObservable.notifyObservers(this);
  24786. // Physics
  24787. if (this._physicsEngine) {
  24788. this.onBeforePhysicsObservable.notifyObservers(this);
  24789. this._physicsEngine._step(deltaTime / 1000.0);
  24790. this.onAfterPhysicsObservable.notifyObservers(this);
  24791. }
  24792. }
  24793. // update gamepad manager
  24794. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24795. this._gamepadManager._checkGamepadsStatus();
  24796. }
  24797. // Update Cameras
  24798. if (this.activeCameras.length > 0) {
  24799. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24800. var camera = this.activeCameras[cameraIndex];
  24801. camera.update();
  24802. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24803. // rig cameras
  24804. for (var index = 0; index < camera._rigCameras.length; index++) {
  24805. camera._rigCameras[index].update();
  24806. }
  24807. }
  24808. }
  24809. }
  24810. else if (this.activeCamera) {
  24811. this.activeCamera.update();
  24812. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24813. // rig cameras
  24814. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24815. this.activeCamera._rigCameras[index].update();
  24816. }
  24817. }
  24818. }
  24819. // Before render
  24820. this.onBeforeRenderObservable.notifyObservers(this);
  24821. // Customs render targets
  24822. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24823. var engine = this.getEngine();
  24824. var currentActiveCamera = this.activeCamera;
  24825. if (this.renderTargetsEnabled) {
  24826. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24827. this._intermediateRendering = true;
  24828. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24829. var renderTarget = this.customRenderTargets[customIndex];
  24830. if (renderTarget._shouldRender()) {
  24831. this._renderId++;
  24832. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24833. if (!this.activeCamera)
  24834. throw new Error("Active camera not set");
  24835. // Viewport
  24836. engine.setViewport(this.activeCamera.viewport);
  24837. // Camera
  24838. this.updateTransformMatrix();
  24839. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24840. }
  24841. }
  24842. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24843. this._intermediateRendering = false;
  24844. this._renderId++;
  24845. }
  24846. // Restore back buffer
  24847. if (this.customRenderTargets.length > 0) {
  24848. engine.restoreDefaultFramebuffer();
  24849. }
  24850. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24851. this.activeCamera = currentActiveCamera;
  24852. // Procedural textures
  24853. if (this.proceduralTexturesEnabled) {
  24854. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24855. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24856. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24857. if (proceduralTexture._shouldRender()) {
  24858. proceduralTexture.render();
  24859. }
  24860. }
  24861. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24862. }
  24863. // Clear
  24864. if (this.autoClearDepthAndStencil || this.autoClear) {
  24865. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24866. }
  24867. // Shadows
  24868. if (this.shadowsEnabled) {
  24869. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24870. var light = this.lights[lightIndex];
  24871. var shadowGenerator = light.getShadowGenerator();
  24872. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24873. var shadowMap = (shadowGenerator.getShadowMap());
  24874. if (this.textures.indexOf(shadowMap) !== -1) {
  24875. this._renderTargets.push(shadowMap);
  24876. }
  24877. }
  24878. }
  24879. }
  24880. // Depth renderer
  24881. for (var key in this._depthRenderer) {
  24882. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24883. }
  24884. // Geometry renderer
  24885. if (this._geometryBufferRenderer) {
  24886. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24887. }
  24888. // RenderPipeline
  24889. if (this._postProcessRenderPipelineManager) {
  24890. this._postProcessRenderPipelineManager.update();
  24891. }
  24892. // Multi-cameras?
  24893. if (this.activeCameras.length > 0) {
  24894. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24895. if (cameraIndex > 0) {
  24896. this._engine.clear(null, false, true, true);
  24897. }
  24898. this._processSubCameras(this.activeCameras[cameraIndex]);
  24899. }
  24900. }
  24901. else {
  24902. if (!this.activeCamera) {
  24903. throw new Error("No camera defined");
  24904. }
  24905. this._processSubCameras(this.activeCamera);
  24906. }
  24907. // Intersection checks
  24908. this._checkIntersections();
  24909. // Update the audio listener attached to the camera
  24910. if (BABYLON.AudioEngine) {
  24911. this._updateAudioParameters();
  24912. }
  24913. // After render
  24914. if (this.afterRender) {
  24915. this.afterRender();
  24916. }
  24917. this.onAfterRenderObservable.notifyObservers(this);
  24918. // Cleaning
  24919. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24920. var data = this._toBeDisposed.data[index];
  24921. if (data) {
  24922. data.dispose();
  24923. }
  24924. this._toBeDisposed[index] = null;
  24925. }
  24926. this._toBeDisposed.reset();
  24927. if (this.dumpNextRenderTargets) {
  24928. this.dumpNextRenderTargets = false;
  24929. }
  24930. this._activeBones.addCount(0, true);
  24931. this._activeIndices.addCount(0, true);
  24932. this._activeParticles.addCount(0, true);
  24933. };
  24934. Scene.prototype._updateAudioParameters = function () {
  24935. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24936. return;
  24937. }
  24938. var listeningCamera;
  24939. var audioEngine = BABYLON.Engine.audioEngine;
  24940. if (this.activeCameras.length > 0) {
  24941. listeningCamera = this.activeCameras[0];
  24942. }
  24943. else {
  24944. listeningCamera = this.activeCamera;
  24945. }
  24946. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24947. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24948. // for VR cameras
  24949. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24950. listeningCamera = listeningCamera.rigCameras[0];
  24951. }
  24952. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24953. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24954. cameraDirection.normalize();
  24955. // To avoid some errors on GearVR
  24956. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24957. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24958. }
  24959. var i;
  24960. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24961. var sound = this.mainSoundTrack.soundCollection[i];
  24962. if (sound.useCustomAttenuation) {
  24963. sound.updateDistanceFromListener();
  24964. }
  24965. }
  24966. for (i = 0; i < this.soundTracks.length; i++) {
  24967. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24968. sound = this.soundTracks[i].soundCollection[j];
  24969. if (sound.useCustomAttenuation) {
  24970. sound.updateDistanceFromListener();
  24971. }
  24972. }
  24973. }
  24974. }
  24975. };
  24976. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24977. // Audio
  24978. get: function () {
  24979. return this._audioEnabled;
  24980. },
  24981. set: function (value) {
  24982. this._audioEnabled = value;
  24983. if (BABYLON.AudioEngine) {
  24984. if (this._audioEnabled) {
  24985. this._enableAudio();
  24986. }
  24987. else {
  24988. this._disableAudio();
  24989. }
  24990. }
  24991. },
  24992. enumerable: true,
  24993. configurable: true
  24994. });
  24995. Scene.prototype._disableAudio = function () {
  24996. var i;
  24997. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24998. this.mainSoundTrack.soundCollection[i].pause();
  24999. }
  25000. for (i = 0; i < this.soundTracks.length; i++) {
  25001. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25002. this.soundTracks[i].soundCollection[j].pause();
  25003. }
  25004. }
  25005. };
  25006. Scene.prototype._enableAudio = function () {
  25007. var i;
  25008. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25009. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25010. this.mainSoundTrack.soundCollection[i].play();
  25011. }
  25012. }
  25013. for (i = 0; i < this.soundTracks.length; i++) {
  25014. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25015. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25016. this.soundTracks[i].soundCollection[j].play();
  25017. }
  25018. }
  25019. }
  25020. };
  25021. Object.defineProperty(Scene.prototype, "headphone", {
  25022. get: function () {
  25023. return this._headphone;
  25024. },
  25025. set: function (value) {
  25026. this._headphone = value;
  25027. if (BABYLON.AudioEngine) {
  25028. if (this._headphone) {
  25029. this._switchAudioModeForHeadphones();
  25030. }
  25031. else {
  25032. this._switchAudioModeForNormalSpeakers();
  25033. }
  25034. }
  25035. },
  25036. enumerable: true,
  25037. configurable: true
  25038. });
  25039. Scene.prototype._switchAudioModeForHeadphones = function () {
  25040. this.mainSoundTrack.switchPanningModelToHRTF();
  25041. for (var i = 0; i < this.soundTracks.length; i++) {
  25042. this.soundTracks[i].switchPanningModelToHRTF();
  25043. }
  25044. };
  25045. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25046. this.mainSoundTrack.switchPanningModelToEqualPower();
  25047. for (var i = 0; i < this.soundTracks.length; i++) {
  25048. this.soundTracks[i].switchPanningModelToEqualPower();
  25049. }
  25050. };
  25051. /**
  25052. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25053. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25054. * @returns the created depth renderer
  25055. */
  25056. Scene.prototype.enableDepthRenderer = function (camera) {
  25057. camera = camera || this.activeCamera;
  25058. if (!camera) {
  25059. throw "No camera available to enable depth renderer";
  25060. }
  25061. if (!this._depthRenderer[camera.id]) {
  25062. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  25063. }
  25064. return this._depthRenderer[camera.id];
  25065. };
  25066. /**
  25067. * Disables a depth renderer for a given camera
  25068. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25069. */
  25070. Scene.prototype.disableDepthRenderer = function (camera) {
  25071. camera = camera || this.activeCamera;
  25072. if (!camera || !this._depthRenderer[camera.id]) {
  25073. return;
  25074. }
  25075. this._depthRenderer[camera.id].dispose();
  25076. delete this._depthRenderer[camera.id];
  25077. };
  25078. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25079. if (ratio === void 0) { ratio = 1; }
  25080. if (this._geometryBufferRenderer) {
  25081. return this._geometryBufferRenderer;
  25082. }
  25083. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25084. if (!this._geometryBufferRenderer.isSupported) {
  25085. this._geometryBufferRenderer = null;
  25086. }
  25087. return this._geometryBufferRenderer;
  25088. };
  25089. Scene.prototype.disableGeometryBufferRenderer = function () {
  25090. if (!this._geometryBufferRenderer) {
  25091. return;
  25092. }
  25093. this._geometryBufferRenderer.dispose();
  25094. this._geometryBufferRenderer = null;
  25095. };
  25096. Scene.prototype.freezeMaterials = function () {
  25097. for (var i = 0; i < this.materials.length; i++) {
  25098. this.materials[i].freeze();
  25099. }
  25100. };
  25101. Scene.prototype.unfreezeMaterials = function () {
  25102. for (var i = 0; i < this.materials.length; i++) {
  25103. this.materials[i].unfreeze();
  25104. }
  25105. };
  25106. Scene.prototype.dispose = function () {
  25107. this.beforeRender = null;
  25108. this.afterRender = null;
  25109. this.skeletons = [];
  25110. this.morphTargetManagers = [];
  25111. this.importedMeshesFiles = new Array();
  25112. this.stopAllAnimations();
  25113. this.resetCachedMaterial();
  25114. for (var key in this._depthRenderer) {
  25115. this._depthRenderer[key].dispose();
  25116. }
  25117. if (this._gamepadManager) {
  25118. this._gamepadManager.dispose();
  25119. this._gamepadManager = null;
  25120. }
  25121. // Smart arrays
  25122. if (this.activeCamera) {
  25123. this.activeCamera._activeMeshes.dispose();
  25124. this.activeCamera = null;
  25125. }
  25126. this._activeMeshes.dispose();
  25127. this._renderingManager.dispose();
  25128. this._processedMaterials.dispose();
  25129. this._activeParticleSystems.dispose();
  25130. this._activeSkeletons.dispose();
  25131. this._softwareSkinnedMeshes.dispose();
  25132. this._renderTargets.dispose();
  25133. this._registeredForLateAnimationBindings.dispose();
  25134. if (this._boundingBoxRenderer) {
  25135. this._boundingBoxRenderer.dispose();
  25136. }
  25137. this._meshesForIntersections.dispose();
  25138. this._toBeDisposed.dispose();
  25139. // Abort active requests
  25140. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25141. var request = _a[_i];
  25142. request.abort();
  25143. }
  25144. // Debug layer
  25145. if (this._debugLayer) {
  25146. this._debugLayer.hide();
  25147. }
  25148. // Events
  25149. this.onDisposeObservable.notifyObservers(this);
  25150. this.onDisposeObservable.clear();
  25151. this.onBeforeRenderObservable.clear();
  25152. this.onAfterRenderObservable.clear();
  25153. this.OnBeforeRenderTargetsRenderObservable.clear();
  25154. this.OnAfterRenderTargetsRenderObservable.clear();
  25155. this.onAfterStepObservable.clear();
  25156. this.onBeforeStepObservable.clear();
  25157. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25158. this.onAfterActiveMeshesEvaluationObservable.clear();
  25159. this.onBeforeParticlesRenderingObservable.clear();
  25160. this.onAfterParticlesRenderingObservable.clear();
  25161. this.onBeforeSpritesRenderingObservable.clear();
  25162. this.onAfterSpritesRenderingObservable.clear();
  25163. this.onBeforeDrawPhaseObservable.clear();
  25164. this.onAfterDrawPhaseObservable.clear();
  25165. this.onBeforePhysicsObservable.clear();
  25166. this.onAfterPhysicsObservable.clear();
  25167. this.onBeforeAnimationsObservable.clear();
  25168. this.onAfterAnimationsObservable.clear();
  25169. this.onDataLoadedObservable.clear();
  25170. this.detachControl();
  25171. // Release sounds & sounds tracks
  25172. if (BABYLON.AudioEngine) {
  25173. this.disposeSounds();
  25174. }
  25175. // VR Helper
  25176. if (this.VRHelper) {
  25177. this.VRHelper.dispose();
  25178. }
  25179. // Detach cameras
  25180. var canvas = this._engine.getRenderingCanvas();
  25181. if (canvas) {
  25182. var index;
  25183. for (index = 0; index < this.cameras.length; index++) {
  25184. this.cameras[index].detachControl(canvas);
  25185. }
  25186. }
  25187. // Release animation groups
  25188. while (this.animationGroups.length) {
  25189. this.animationGroups[0].dispose();
  25190. }
  25191. // Release lights
  25192. while (this.lights.length) {
  25193. this.lights[0].dispose();
  25194. }
  25195. // Release meshes
  25196. while (this.meshes.length) {
  25197. this.meshes[0].dispose(true);
  25198. }
  25199. while (this.transformNodes.length) {
  25200. this.removeTransformNode(this.transformNodes[0]);
  25201. }
  25202. // Release cameras
  25203. while (this.cameras.length) {
  25204. this.cameras[0].dispose();
  25205. }
  25206. // Release materials
  25207. if (this.defaultMaterial) {
  25208. this.defaultMaterial.dispose();
  25209. }
  25210. while (this.multiMaterials.length) {
  25211. this.multiMaterials[0].dispose();
  25212. }
  25213. while (this.materials.length) {
  25214. this.materials[0].dispose();
  25215. }
  25216. // Release particles
  25217. while (this.particleSystems.length) {
  25218. this.particleSystems[0].dispose();
  25219. }
  25220. // Release sprites
  25221. while (this.spriteManagers.length) {
  25222. this.spriteManagers[0].dispose();
  25223. }
  25224. // Release postProcesses
  25225. while (this.postProcesses.length) {
  25226. this.postProcesses[0].dispose();
  25227. }
  25228. // Release layers
  25229. while (this.layers.length) {
  25230. this.layers[0].dispose();
  25231. }
  25232. while (this.effectLayers.length) {
  25233. this.effectLayers[0].dispose();
  25234. }
  25235. // Release textures
  25236. while (this.textures.length) {
  25237. this.textures[0].dispose();
  25238. }
  25239. // Release UBO
  25240. this._sceneUbo.dispose();
  25241. if (this._alternateSceneUbo) {
  25242. this._alternateSceneUbo.dispose();
  25243. }
  25244. // Post-processes
  25245. this.postProcessManager.dispose();
  25246. if (this._postProcessRenderPipelineManager) {
  25247. this._postProcessRenderPipelineManager.dispose();
  25248. }
  25249. // Physics
  25250. if (this._physicsEngine) {
  25251. this.disablePhysicsEngine();
  25252. }
  25253. // Remove from engine
  25254. index = this._engine.scenes.indexOf(this);
  25255. if (index > -1) {
  25256. this._engine.scenes.splice(index, 1);
  25257. }
  25258. this._engine.wipeCaches(true);
  25259. this._isDisposed = true;
  25260. };
  25261. Object.defineProperty(Scene.prototype, "isDisposed", {
  25262. get: function () {
  25263. return this._isDisposed;
  25264. },
  25265. enumerable: true,
  25266. configurable: true
  25267. });
  25268. // Release sounds & sounds tracks
  25269. Scene.prototype.disposeSounds = function () {
  25270. if (!this._mainSoundTrack) {
  25271. return;
  25272. }
  25273. this.mainSoundTrack.dispose();
  25274. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25275. this.soundTracks[scIndex].dispose();
  25276. }
  25277. };
  25278. // Octrees
  25279. /**
  25280. * Get the world extend vectors with an optional filter
  25281. *
  25282. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25283. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25284. */
  25285. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25286. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25287. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25288. filterPredicate = filterPredicate || (function () { return true; });
  25289. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25290. mesh.computeWorldMatrix(true);
  25291. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25292. return;
  25293. }
  25294. var boundingInfo = mesh.getBoundingInfo();
  25295. var minBox = boundingInfo.boundingBox.minimumWorld;
  25296. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25297. BABYLON.Tools.CheckExtends(minBox, min, max);
  25298. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25299. });
  25300. return {
  25301. min: min,
  25302. max: max
  25303. };
  25304. };
  25305. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25306. if (maxCapacity === void 0) { maxCapacity = 64; }
  25307. if (maxDepth === void 0) { maxDepth = 2; }
  25308. if (!this._selectionOctree) {
  25309. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25310. }
  25311. var worldExtends = this.getWorldExtends();
  25312. // Update octree
  25313. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25314. return this._selectionOctree;
  25315. };
  25316. // Picking
  25317. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25318. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25319. var result = BABYLON.Ray.Zero();
  25320. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25321. return result;
  25322. };
  25323. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25324. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25325. var engine = this._engine;
  25326. if (!camera) {
  25327. if (!this.activeCamera)
  25328. throw new Error("Active camera not set");
  25329. camera = this.activeCamera;
  25330. }
  25331. var cameraViewport = camera.viewport;
  25332. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25333. // Moving coordinates to local viewport world
  25334. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25335. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25336. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25337. return this;
  25338. };
  25339. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25340. var result = BABYLON.Ray.Zero();
  25341. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25342. return result;
  25343. };
  25344. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25345. if (!BABYLON.PickingInfo) {
  25346. return this;
  25347. }
  25348. var engine = this._engine;
  25349. if (!camera) {
  25350. if (!this.activeCamera)
  25351. throw new Error("Active camera not set");
  25352. camera = this.activeCamera;
  25353. }
  25354. var cameraViewport = camera.viewport;
  25355. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25356. var identity = BABYLON.Matrix.Identity();
  25357. // Moving coordinates to local viewport world
  25358. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25359. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25360. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25361. return this;
  25362. };
  25363. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25364. if (!BABYLON.PickingInfo) {
  25365. return null;
  25366. }
  25367. var pickingInfo = null;
  25368. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25369. var mesh = this.meshes[meshIndex];
  25370. if (predicate) {
  25371. if (!predicate(mesh)) {
  25372. continue;
  25373. }
  25374. }
  25375. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25376. continue;
  25377. }
  25378. var world = mesh.getWorldMatrix();
  25379. var ray = rayFunction(world);
  25380. var result = mesh.intersects(ray, fastCheck);
  25381. if (!result || !result.hit)
  25382. continue;
  25383. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25384. continue;
  25385. pickingInfo = result;
  25386. if (fastCheck) {
  25387. break;
  25388. }
  25389. }
  25390. return pickingInfo || new BABYLON.PickingInfo();
  25391. };
  25392. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25393. if (!BABYLON.PickingInfo) {
  25394. return null;
  25395. }
  25396. var pickingInfos = new Array();
  25397. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25398. var mesh = this.meshes[meshIndex];
  25399. if (predicate) {
  25400. if (!predicate(mesh)) {
  25401. continue;
  25402. }
  25403. }
  25404. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25405. continue;
  25406. }
  25407. var world = mesh.getWorldMatrix();
  25408. var ray = rayFunction(world);
  25409. var result = mesh.intersects(ray, false);
  25410. if (!result || !result.hit)
  25411. continue;
  25412. pickingInfos.push(result);
  25413. }
  25414. return pickingInfos;
  25415. };
  25416. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25417. if (!BABYLON.PickingInfo) {
  25418. return null;
  25419. }
  25420. var pickingInfo = null;
  25421. if (!camera) {
  25422. if (!this.activeCamera) {
  25423. return null;
  25424. }
  25425. camera = this.activeCamera;
  25426. }
  25427. if (this.spriteManagers.length > 0) {
  25428. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25429. var spriteManager = this.spriteManagers[spriteIndex];
  25430. if (!spriteManager.isPickable) {
  25431. continue;
  25432. }
  25433. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25434. if (!result || !result.hit)
  25435. continue;
  25436. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25437. continue;
  25438. pickingInfo = result;
  25439. if (fastCheck) {
  25440. break;
  25441. }
  25442. }
  25443. }
  25444. return pickingInfo || new BABYLON.PickingInfo();
  25445. };
  25446. /** Launch a ray to try to pick a mesh in the scene
  25447. * @param x position on screen
  25448. * @param y position on screen
  25449. * @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
  25450. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25451. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25452. */
  25453. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25454. var _this = this;
  25455. if (!BABYLON.PickingInfo) {
  25456. return null;
  25457. }
  25458. return this._internalPick(function (world) {
  25459. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25460. return _this._tempPickingRay;
  25461. }, predicate, fastCheck);
  25462. };
  25463. /** Launch a ray to try to pick a sprite in the scene
  25464. * @param x position on screen
  25465. * @param y position on screen
  25466. * @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
  25467. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25468. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25469. */
  25470. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25471. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25472. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25473. };
  25474. /** Use the given ray to pick a mesh in the scene
  25475. * @param ray The ray to use to pick meshes
  25476. * @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
  25477. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25478. */
  25479. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25480. var _this = this;
  25481. return this._internalPick(function (world) {
  25482. if (!_this._pickWithRayInverseMatrix) {
  25483. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25484. }
  25485. world.invertToRef(_this._pickWithRayInverseMatrix);
  25486. if (!_this._cachedRayForTransform) {
  25487. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25488. }
  25489. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25490. return _this._cachedRayForTransform;
  25491. }, predicate, fastCheck);
  25492. };
  25493. /**
  25494. * Launch a ray to try to pick a mesh in the scene
  25495. * @param x X position on screen
  25496. * @param y Y position on screen
  25497. * @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
  25498. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25499. */
  25500. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25501. var _this = this;
  25502. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25503. };
  25504. /**
  25505. * Launch a ray to try to pick a mesh in the scene
  25506. * @param ray Ray to use
  25507. * @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
  25508. */
  25509. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25510. var _this = this;
  25511. return this._internalMultiPick(function (world) {
  25512. if (!_this._pickWithRayInverseMatrix) {
  25513. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25514. }
  25515. world.invertToRef(_this._pickWithRayInverseMatrix);
  25516. if (!_this._cachedRayForTransform) {
  25517. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25518. }
  25519. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25520. return _this._cachedRayForTransform;
  25521. }, predicate);
  25522. };
  25523. Scene.prototype.setPointerOverMesh = function (mesh) {
  25524. if (this._pointerOverMesh === mesh) {
  25525. return;
  25526. }
  25527. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25528. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25529. }
  25530. this._pointerOverMesh = mesh;
  25531. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25532. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25533. }
  25534. };
  25535. Scene.prototype.getPointerOverMesh = function () {
  25536. return this._pointerOverMesh;
  25537. };
  25538. Scene.prototype.setPointerOverSprite = function (sprite) {
  25539. if (this._pointerOverSprite === sprite) {
  25540. return;
  25541. }
  25542. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25543. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25544. }
  25545. this._pointerOverSprite = sprite;
  25546. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25547. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25548. }
  25549. };
  25550. Scene.prototype.getPointerOverSprite = function () {
  25551. return this._pointerOverSprite;
  25552. };
  25553. // Physics
  25554. Scene.prototype.getPhysicsEngine = function () {
  25555. return this._physicsEngine;
  25556. };
  25557. /**
  25558. * Enables physics to the current scene
  25559. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25560. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25561. * @return {boolean} was the physics engine initialized
  25562. */
  25563. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25564. if (gravity === void 0) { gravity = null; }
  25565. if (this._physicsEngine) {
  25566. return true;
  25567. }
  25568. try {
  25569. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25570. return true;
  25571. }
  25572. catch (e) {
  25573. BABYLON.Tools.Error(e.message);
  25574. return false;
  25575. }
  25576. };
  25577. Scene.prototype.disablePhysicsEngine = function () {
  25578. if (!this._physicsEngine) {
  25579. return;
  25580. }
  25581. this._physicsEngine.dispose();
  25582. this._physicsEngine = null;
  25583. };
  25584. Scene.prototype.isPhysicsEnabled = function () {
  25585. return this._physicsEngine !== undefined;
  25586. };
  25587. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25588. var mesh = compound.parts[0].mesh;
  25589. if (mesh.physicsImpostor) {
  25590. mesh.physicsImpostor.dispose();
  25591. mesh.physicsImpostor = null;
  25592. }
  25593. };
  25594. // Misc.
  25595. Scene.prototype._rebuildGeometries = function () {
  25596. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25597. var geometry = _a[_i];
  25598. geometry._rebuild();
  25599. }
  25600. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25601. var mesh = _c[_b];
  25602. mesh._rebuild();
  25603. }
  25604. if (this.postProcessManager) {
  25605. this.postProcessManager._rebuild();
  25606. }
  25607. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25608. var layer = _e[_d];
  25609. layer._rebuild();
  25610. }
  25611. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25612. var effectLayer = _g[_f];
  25613. effectLayer._rebuild();
  25614. }
  25615. if (this._boundingBoxRenderer) {
  25616. this._boundingBoxRenderer._rebuild();
  25617. }
  25618. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25619. var system = _j[_h];
  25620. system.rebuild();
  25621. }
  25622. if (this._postProcessRenderPipelineManager) {
  25623. this._postProcessRenderPipelineManager._rebuild();
  25624. }
  25625. };
  25626. Scene.prototype._rebuildTextures = function () {
  25627. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25628. var texture = _a[_i];
  25629. texture._rebuild();
  25630. }
  25631. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25632. };
  25633. /**
  25634. * Creates a default light for the scene.
  25635. * @param replace Whether to replace the existing lights in the scene.
  25636. */
  25637. Scene.prototype.createDefaultLight = function (replace) {
  25638. if (replace === void 0) { replace = false; }
  25639. // Dispose existing light in replace mode.
  25640. if (replace) {
  25641. if (this.lights) {
  25642. for (var i = 0; i < this.lights.length; i++) {
  25643. this.lights[i].dispose();
  25644. }
  25645. }
  25646. }
  25647. // Light
  25648. if (this.lights.length === 0) {
  25649. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25650. }
  25651. };
  25652. /**
  25653. * Creates a default camera for the scene.
  25654. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25655. * @param replace Whether to replace the existing active camera in the scene.
  25656. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25657. */
  25658. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25659. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25660. if (replace === void 0) { replace = false; }
  25661. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25662. // Dispose existing camera in replace mode.
  25663. if (replace) {
  25664. if (this.activeCamera) {
  25665. this.activeCamera.dispose();
  25666. this.activeCamera = null;
  25667. }
  25668. }
  25669. // Camera
  25670. if (!this.activeCamera) {
  25671. var worldExtends = this.getWorldExtends();
  25672. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25673. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25674. var camera;
  25675. var radius = worldSize.length() * 1.5;
  25676. // empty scene scenario!
  25677. if (!isFinite(radius)) {
  25678. radius = 1;
  25679. worldCenter.copyFromFloats(0, 0, 0);
  25680. }
  25681. if (createArcRotateCamera) {
  25682. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25683. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25684. arcRotateCamera.wheelPrecision = 100 / radius;
  25685. camera = arcRotateCamera;
  25686. }
  25687. else {
  25688. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25689. freeCamera.setTarget(worldCenter);
  25690. camera = freeCamera;
  25691. }
  25692. camera.minZ = radius * 0.01;
  25693. camera.maxZ = radius * 1000;
  25694. camera.speed = radius * 0.2;
  25695. this.activeCamera = camera;
  25696. var canvas = this.getEngine().getRenderingCanvas();
  25697. if (attachCameraControls && canvas) {
  25698. camera.attachControl(canvas);
  25699. }
  25700. }
  25701. };
  25702. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25703. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25704. if (replace === void 0) { replace = false; }
  25705. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25706. this.createDefaultLight(replace);
  25707. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25708. };
  25709. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25710. if (pbr === void 0) { pbr = false; }
  25711. if (scale === void 0) { scale = 1000; }
  25712. if (blur === void 0) { blur = 0; }
  25713. if (environmentTexture) {
  25714. this.environmentTexture = environmentTexture;
  25715. }
  25716. if (!this.environmentTexture) {
  25717. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25718. return null;
  25719. }
  25720. // Skybox
  25721. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25722. if (pbr) {
  25723. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25724. hdrSkyboxMaterial.backFaceCulling = false;
  25725. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25726. if (hdrSkyboxMaterial.reflectionTexture) {
  25727. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25728. }
  25729. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25730. hdrSkyboxMaterial.disableLighting = true;
  25731. hdrSkyboxMaterial.twoSidedLighting = true;
  25732. hdrSkybox.infiniteDistance = true;
  25733. hdrSkybox.material = hdrSkyboxMaterial;
  25734. }
  25735. else {
  25736. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25737. skyboxMaterial.backFaceCulling = false;
  25738. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25739. if (skyboxMaterial.reflectionTexture) {
  25740. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25741. }
  25742. skyboxMaterial.disableLighting = true;
  25743. hdrSkybox.infiniteDistance = true;
  25744. hdrSkybox.material = skyboxMaterial;
  25745. }
  25746. return hdrSkybox;
  25747. };
  25748. Scene.prototype.createDefaultEnvironment = function (options) {
  25749. if (BABYLON.EnvironmentHelper) {
  25750. return new BABYLON.EnvironmentHelper(options, this);
  25751. }
  25752. return null;
  25753. };
  25754. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25755. if (webVROptions === void 0) { webVROptions = {}; }
  25756. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25757. };
  25758. // Tags
  25759. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25760. if (tagsQuery === undefined) {
  25761. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25762. return list;
  25763. }
  25764. var listByTags = [];
  25765. forEach = forEach || (function (item) { return; });
  25766. for (var i in list) {
  25767. var item = list[i];
  25768. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25769. listByTags.push(item);
  25770. forEach(item);
  25771. }
  25772. }
  25773. return listByTags;
  25774. };
  25775. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25776. return this._getByTags(this.meshes, tagsQuery, forEach);
  25777. };
  25778. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25779. return this._getByTags(this.cameras, tagsQuery, forEach);
  25780. };
  25781. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25782. return this._getByTags(this.lights, tagsQuery, forEach);
  25783. };
  25784. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25785. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25786. };
  25787. /**
  25788. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25789. * This allowed control for front to back rendering or reversly depending of the special needs.
  25790. *
  25791. * @param renderingGroupId The rendering group id corresponding to its index
  25792. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25793. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25794. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25795. */
  25796. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25797. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25798. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25799. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25800. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25801. };
  25802. /**
  25803. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25804. *
  25805. * @param renderingGroupId The rendering group id corresponding to its index
  25806. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25807. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25808. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25809. */
  25810. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25811. if (depth === void 0) { depth = true; }
  25812. if (stencil === void 0) { stencil = true; }
  25813. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25814. };
  25815. /**
  25816. * Will flag all materials as dirty to trigger new shader compilation
  25817. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25818. */
  25819. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25820. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25821. var material = _a[_i];
  25822. if (predicate && !predicate(material)) {
  25823. continue;
  25824. }
  25825. material.markAsDirty(flag);
  25826. }
  25827. };
  25828. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25829. var _this = this;
  25830. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25831. this._activeRequests.push(request);
  25832. request.onCompleteObservable.add(function (request) {
  25833. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25834. });
  25835. return request;
  25836. };
  25837. /** @ignore */
  25838. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25839. var _this = this;
  25840. return new Promise(function (resolve, reject) {
  25841. _this._loadFile(url, function (data) {
  25842. resolve(data);
  25843. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25844. reject(exception);
  25845. });
  25846. });
  25847. };
  25848. // Statics
  25849. Scene._FOGMODE_NONE = 0;
  25850. Scene._FOGMODE_EXP = 1;
  25851. Scene._FOGMODE_EXP2 = 2;
  25852. Scene._FOGMODE_LINEAR = 3;
  25853. Scene._uniqueIdCounter = 0;
  25854. Scene.MinDeltaTime = 1.0;
  25855. Scene.MaxDeltaTime = 1000.0;
  25856. /** The distance in pixel that you have to move to prevent some events */
  25857. Scene.DragMovementThreshold = 10; // in pixels
  25858. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25859. Scene.LongPressDelay = 500; // in milliseconds
  25860. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25861. Scene.DoubleClickDelay = 300; // in milliseconds
  25862. /** If you need to check double click without raising a single click at first click, enable this flag */
  25863. Scene.ExclusiveDoubleClickMode = false;
  25864. return Scene;
  25865. }());
  25866. BABYLON.Scene = Scene;
  25867. })(BABYLON || (BABYLON = {}));
  25868. //# sourceMappingURL=babylon.scene.js.map
  25869. "use strict";
  25870. var BABYLON;
  25871. (function (BABYLON) {
  25872. /**
  25873. * Set of assets to keep when moving a scene into an asset container.
  25874. */
  25875. var KeepAssets = /** @class */ (function () {
  25876. function KeepAssets() {
  25877. /**
  25878. * Cameras to keep.
  25879. */
  25880. this.cameras = new Array();
  25881. /**
  25882. * Lights to keep.
  25883. */
  25884. this.lights = new Array();
  25885. /**
  25886. * Meshes to keep.
  25887. */
  25888. this.meshes = new Array();
  25889. /**
  25890. * Skeletons to keep.
  25891. */
  25892. this.skeletons = new Array();
  25893. /**
  25894. * ParticleSystems to keep.
  25895. */
  25896. this.particleSystems = new Array();
  25897. /**
  25898. * Animations to keep.
  25899. */
  25900. this.animations = new Array();
  25901. /**
  25902. * MultiMaterials to keep.
  25903. */
  25904. this.multiMaterials = new Array();
  25905. /**
  25906. * Materials to keep.
  25907. */
  25908. this.materials = new Array();
  25909. /**
  25910. * MorphTargetManagers to keep.
  25911. */
  25912. this.morphTargetManagers = new Array();
  25913. /**
  25914. * Geometries to keep.
  25915. */
  25916. this.geometries = new Array();
  25917. /**
  25918. * TransformNodes to keep.
  25919. */
  25920. this.transformNodes = new Array();
  25921. /**
  25922. * LensFlareSystems to keep.
  25923. */
  25924. this.lensFlareSystems = new Array();
  25925. /**
  25926. * ShadowGenerators to keep.
  25927. */
  25928. this.shadowGenerators = new Array();
  25929. /**
  25930. * ActionManagers to keep.
  25931. */
  25932. this.actionManagers = new Array();
  25933. /**
  25934. * Sounds to keep.
  25935. */
  25936. this.sounds = new Array();
  25937. }
  25938. return KeepAssets;
  25939. }());
  25940. BABYLON.KeepAssets = KeepAssets;
  25941. /**
  25942. * Container with a set of assets that can be added or removed from a scene.
  25943. */
  25944. var AssetContainer = /** @class */ (function () {
  25945. /**
  25946. * Instantiates an AssetContainer.
  25947. * @param scene The scene the AssetContainer belongs to.
  25948. */
  25949. function AssetContainer(scene) {
  25950. // Objects
  25951. /**
  25952. * Cameras populated in the container.
  25953. */
  25954. this.cameras = new Array();
  25955. /**
  25956. * Lights populated in the container.
  25957. */
  25958. this.lights = new Array();
  25959. /**
  25960. * Meshes populated in the container.
  25961. */
  25962. this.meshes = new Array();
  25963. /**
  25964. * Skeletons populated in the container.
  25965. */
  25966. this.skeletons = new Array();
  25967. /**
  25968. * ParticleSystems populated in the container.
  25969. */
  25970. this.particleSystems = new Array();
  25971. /**
  25972. * Animations populated in the container.
  25973. */
  25974. this.animations = new Array();
  25975. /**
  25976. * MultiMaterials populated in the container.
  25977. */
  25978. this.multiMaterials = new Array();
  25979. /**
  25980. * Materials populated in the container.
  25981. */
  25982. this.materials = new Array();
  25983. /**
  25984. * MorphTargetManagers populated in the container.
  25985. */
  25986. this.morphTargetManagers = new Array();
  25987. /**
  25988. * Geometries populated in the container.
  25989. */
  25990. this.geometries = new Array();
  25991. /**
  25992. * TransformNodes populated in the container.
  25993. */
  25994. this.transformNodes = new Array();
  25995. /**
  25996. * LensFlareSystems populated in the container.
  25997. */
  25998. this.lensFlareSystems = new Array();
  25999. /**
  26000. * ShadowGenerators populated in the container.
  26001. */
  26002. this.shadowGenerators = new Array();
  26003. /**
  26004. * ActionManagers populated in the container.
  26005. */
  26006. this.actionManagers = new Array();
  26007. /**
  26008. * Sounds populated in the container.
  26009. */
  26010. this.sounds = new Array();
  26011. this.scene = scene;
  26012. }
  26013. /**
  26014. * Adds all the assets from the container to the scene.
  26015. */
  26016. AssetContainer.prototype.addAllToScene = function () {
  26017. var _this = this;
  26018. this.cameras.forEach(function (o) {
  26019. _this.scene.addCamera(o);
  26020. });
  26021. this.lights.forEach(function (o) {
  26022. _this.scene.addLight(o);
  26023. });
  26024. this.meshes.forEach(function (o) {
  26025. _this.scene.addMesh(o);
  26026. });
  26027. this.skeletons.forEach(function (o) {
  26028. _this.scene.addSkeleton(o);
  26029. });
  26030. this.particleSystems.forEach(function (o) {
  26031. _this.scene.addParticleSystem(o);
  26032. });
  26033. this.animations.forEach(function (o) {
  26034. _this.scene.addAnimation(o);
  26035. });
  26036. this.multiMaterials.forEach(function (o) {
  26037. _this.scene.addMultiMaterial(o);
  26038. });
  26039. this.materials.forEach(function (o) {
  26040. _this.scene.addMaterial(o);
  26041. });
  26042. this.morphTargetManagers.forEach(function (o) {
  26043. _this.scene.addMorphTargetManager(o);
  26044. });
  26045. this.geometries.forEach(function (o) {
  26046. _this.scene.addGeometry(o);
  26047. });
  26048. this.transformNodes.forEach(function (o) {
  26049. _this.scene.addTransformNode(o);
  26050. });
  26051. this.lensFlareSystems.forEach(function (o) {
  26052. _this.scene.addLensFlareSystem(o);
  26053. });
  26054. this.actionManagers.forEach(function (o) {
  26055. _this.scene.addActionManager(o);
  26056. });
  26057. this.sounds.forEach(function (o) {
  26058. o.play();
  26059. o.autoplay = true;
  26060. _this.scene.mainSoundTrack.AddSound(o);
  26061. });
  26062. };
  26063. /**
  26064. * Removes all the assets in the container from the scene
  26065. */
  26066. AssetContainer.prototype.removeAllFromScene = function () {
  26067. var _this = this;
  26068. this.cameras.forEach(function (o) {
  26069. _this.scene.removeCamera(o);
  26070. });
  26071. this.lights.forEach(function (o) {
  26072. _this.scene.removeLight(o);
  26073. });
  26074. this.meshes.forEach(function (o) {
  26075. _this.scene.removeMesh(o);
  26076. });
  26077. this.skeletons.forEach(function (o) {
  26078. _this.scene.removeSkeleton(o);
  26079. });
  26080. this.particleSystems.forEach(function (o) {
  26081. _this.scene.removeParticleSystem(o);
  26082. });
  26083. this.animations.forEach(function (o) {
  26084. _this.scene.removeAnimation(o);
  26085. });
  26086. this.multiMaterials.forEach(function (o) {
  26087. _this.scene.removeMultiMaterial(o);
  26088. });
  26089. this.materials.forEach(function (o) {
  26090. _this.scene.removeMaterial(o);
  26091. });
  26092. this.morphTargetManagers.forEach(function (o) {
  26093. _this.scene.removeMorphTargetManager(o);
  26094. });
  26095. this.geometries.forEach(function (o) {
  26096. _this.scene.removeGeometry(o);
  26097. });
  26098. this.transformNodes.forEach(function (o) {
  26099. _this.scene.removeTransformNode(o);
  26100. });
  26101. this.lensFlareSystems.forEach(function (o) {
  26102. _this.scene.removeLensFlareSystem(o);
  26103. });
  26104. this.actionManagers.forEach(function (o) {
  26105. _this.scene.removeActionManager(o);
  26106. });
  26107. this.sounds.forEach(function (o) {
  26108. o.stop();
  26109. o.autoplay = false;
  26110. _this.scene.mainSoundTrack.RemoveSound(o);
  26111. });
  26112. };
  26113. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26114. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26115. var asset = sourceAssets_1[_i];
  26116. var move = true;
  26117. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26118. var keepAsset = keepAssets_1[_a];
  26119. if (asset === keepAsset) {
  26120. move = false;
  26121. break;
  26122. }
  26123. }
  26124. if (move) {
  26125. targetAssets.push(asset);
  26126. }
  26127. }
  26128. };
  26129. /**
  26130. * Removes all the assets contained in the scene and adds them to the container.
  26131. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26132. */
  26133. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26134. if (keepAssets === undefined) {
  26135. keepAssets = new KeepAssets();
  26136. }
  26137. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26138. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26139. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26140. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26141. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26142. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26143. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26144. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26145. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26146. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26147. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26148. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26149. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26150. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26151. this.removeAllFromScene();
  26152. };
  26153. return AssetContainer;
  26154. }());
  26155. BABYLON.AssetContainer = AssetContainer;
  26156. })(BABYLON || (BABYLON = {}));
  26157. //# sourceMappingURL=babylon.assetContainer.js.map
  26158. "use strict";
  26159. var BABYLON;
  26160. (function (BABYLON) {
  26161. var Buffer = /** @class */ (function () {
  26162. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26163. if (instanced === void 0) { instanced = false; }
  26164. if (engine instanceof BABYLON.Mesh) {
  26165. this._engine = engine.getScene().getEngine();
  26166. }
  26167. else {
  26168. this._engine = engine;
  26169. }
  26170. this._updatable = updatable;
  26171. this._instanced = instanced;
  26172. this._data = data;
  26173. this._strideSize = stride;
  26174. if (!postponeInternalCreation) {
  26175. this.create();
  26176. }
  26177. }
  26178. /**
  26179. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26180. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26181. * @param offset defines offset in the buffer (0 by default)
  26182. * @param size defines the size in floats of attributes (position is 3 for instance)
  26183. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26184. * @param instanced defines if the vertex buffer contains indexed data
  26185. * @returns the new vertex buffer
  26186. */
  26187. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26188. // a lot of these parameters are ignored as they are overriden by the buffer
  26189. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26190. };
  26191. // Properties
  26192. Buffer.prototype.isUpdatable = function () {
  26193. return this._updatable;
  26194. };
  26195. Buffer.prototype.getData = function () {
  26196. return this._data;
  26197. };
  26198. Buffer.prototype.getBuffer = function () {
  26199. return this._buffer;
  26200. };
  26201. Buffer.prototype.getStrideSize = function () {
  26202. return this._strideSize;
  26203. };
  26204. // public getIsInstanced(): boolean {
  26205. // return this._instanced;
  26206. // }
  26207. // public get instanceDivisor(): number {
  26208. // return this._instanceDivisor;
  26209. // }
  26210. // public set instanceDivisor(value: number) {
  26211. // this._instanceDivisor = value;
  26212. // if (value == 0) {
  26213. // this._instanced = false;
  26214. // } else {
  26215. // this._instanced = true;
  26216. // }
  26217. // }
  26218. // Methods
  26219. Buffer.prototype.create = function (data) {
  26220. if (data === void 0) { data = null; }
  26221. if (!data && this._buffer) {
  26222. return; // nothing to do
  26223. }
  26224. data = data || this._data;
  26225. if (!data) {
  26226. return;
  26227. }
  26228. if (!this._buffer) {
  26229. if (this._updatable) {
  26230. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26231. this._data = data;
  26232. }
  26233. else {
  26234. this._buffer = this._engine.createVertexBuffer(data);
  26235. }
  26236. }
  26237. else if (this._updatable) {
  26238. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26239. this._data = data;
  26240. }
  26241. };
  26242. Buffer.prototype._rebuild = function () {
  26243. this._buffer = null;
  26244. this.create(this._data);
  26245. };
  26246. Buffer.prototype.update = function (data) {
  26247. this.create(data);
  26248. };
  26249. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26250. if (!this._buffer) {
  26251. return;
  26252. }
  26253. if (this._updatable) {
  26254. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26255. this._data = null;
  26256. }
  26257. };
  26258. Buffer.prototype.dispose = function () {
  26259. if (!this._buffer) {
  26260. return;
  26261. }
  26262. if (this._engine._releaseBuffer(this._buffer)) {
  26263. this._buffer = null;
  26264. }
  26265. };
  26266. return Buffer;
  26267. }());
  26268. BABYLON.Buffer = Buffer;
  26269. })(BABYLON || (BABYLON = {}));
  26270. //# sourceMappingURL=babylon.buffer.js.map
  26271. "use strict";
  26272. var BABYLON;
  26273. (function (BABYLON) {
  26274. var VertexBuffer = /** @class */ (function () {
  26275. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26276. if (data instanceof BABYLON.Buffer) {
  26277. if (!stride) {
  26278. stride = data.getStrideSize();
  26279. }
  26280. this._buffer = data;
  26281. this._ownsBuffer = false;
  26282. }
  26283. else {
  26284. if (!stride) {
  26285. stride = VertexBuffer.DeduceStride(kind);
  26286. }
  26287. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26288. this._ownsBuffer = true;
  26289. }
  26290. this._stride = stride;
  26291. this._instanced = instanced !== undefined ? instanced : false;
  26292. this._instanceDivisor = instanced ? 1 : 0;
  26293. this._offset = offset ? offset : 0;
  26294. this._size = size ? size : stride;
  26295. this._kind = kind;
  26296. }
  26297. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26298. /**
  26299. * Gets or sets the instance divisor when in instanced mode
  26300. */
  26301. get: function () {
  26302. return this._instanceDivisor;
  26303. },
  26304. set: function (value) {
  26305. this._instanceDivisor = value;
  26306. if (value == 0) {
  26307. this._instanced = false;
  26308. }
  26309. else {
  26310. this._instanced = true;
  26311. }
  26312. },
  26313. enumerable: true,
  26314. configurable: true
  26315. });
  26316. VertexBuffer.prototype._rebuild = function () {
  26317. if (!this._buffer) {
  26318. return;
  26319. }
  26320. this._buffer._rebuild();
  26321. };
  26322. /**
  26323. * Returns the kind of the VertexBuffer (string).
  26324. */
  26325. VertexBuffer.prototype.getKind = function () {
  26326. return this._kind;
  26327. };
  26328. // Properties
  26329. /**
  26330. * Boolean : is the VertexBuffer updatable ?
  26331. */
  26332. VertexBuffer.prototype.isUpdatable = function () {
  26333. return this._buffer.isUpdatable();
  26334. };
  26335. /**
  26336. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26337. */
  26338. VertexBuffer.prototype.getData = function () {
  26339. return this._buffer.getData();
  26340. };
  26341. /**
  26342. * Returns the WebGLBuffer associated to the VertexBuffer.
  26343. */
  26344. VertexBuffer.prototype.getBuffer = function () {
  26345. return this._buffer.getBuffer();
  26346. };
  26347. /**
  26348. * Returns the stride of the VertexBuffer (integer).
  26349. */
  26350. VertexBuffer.prototype.getStrideSize = function () {
  26351. return this._stride;
  26352. };
  26353. /**
  26354. * Returns the offset (integer).
  26355. */
  26356. VertexBuffer.prototype.getOffset = function () {
  26357. return this._offset;
  26358. };
  26359. /**
  26360. * Returns the VertexBuffer total size (integer).
  26361. */
  26362. VertexBuffer.prototype.getSize = function () {
  26363. return this._size;
  26364. };
  26365. /**
  26366. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26367. */
  26368. VertexBuffer.prototype.getIsInstanced = function () {
  26369. return this._instanced;
  26370. };
  26371. /**
  26372. * Returns the instancing divisor, zero for non-instanced (integer).
  26373. */
  26374. VertexBuffer.prototype.getInstanceDivisor = function () {
  26375. return this._instanceDivisor;
  26376. };
  26377. // Methods
  26378. /**
  26379. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26380. * Returns the created WebGLBuffer.
  26381. */
  26382. VertexBuffer.prototype.create = function (data) {
  26383. return this._buffer.create(data);
  26384. };
  26385. /**
  26386. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26387. * This function will create a new buffer if the current one is not updatable
  26388. * Returns the updated WebGLBuffer.
  26389. */
  26390. VertexBuffer.prototype.update = function (data) {
  26391. return this._buffer.update(data);
  26392. };
  26393. /**
  26394. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26395. * Returns the directly updated WebGLBuffer.
  26396. */
  26397. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26398. return this._buffer.updateDirectly(data, offset);
  26399. };
  26400. /**
  26401. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26402. */
  26403. VertexBuffer.prototype.dispose = function () {
  26404. if (this._ownsBuffer) {
  26405. this._buffer.dispose();
  26406. }
  26407. };
  26408. Object.defineProperty(VertexBuffer, "PositionKind", {
  26409. get: function () {
  26410. return VertexBuffer._PositionKind;
  26411. },
  26412. enumerable: true,
  26413. configurable: true
  26414. });
  26415. Object.defineProperty(VertexBuffer, "NormalKind", {
  26416. get: function () {
  26417. return VertexBuffer._NormalKind;
  26418. },
  26419. enumerable: true,
  26420. configurable: true
  26421. });
  26422. Object.defineProperty(VertexBuffer, "TangentKind", {
  26423. get: function () {
  26424. return VertexBuffer._TangentKind;
  26425. },
  26426. enumerable: true,
  26427. configurable: true
  26428. });
  26429. Object.defineProperty(VertexBuffer, "UVKind", {
  26430. get: function () {
  26431. return VertexBuffer._UVKind;
  26432. },
  26433. enumerable: true,
  26434. configurable: true
  26435. });
  26436. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26437. get: function () {
  26438. return VertexBuffer._UV2Kind;
  26439. },
  26440. enumerable: true,
  26441. configurable: true
  26442. });
  26443. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26444. get: function () {
  26445. return VertexBuffer._UV3Kind;
  26446. },
  26447. enumerable: true,
  26448. configurable: true
  26449. });
  26450. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26451. get: function () {
  26452. return VertexBuffer._UV4Kind;
  26453. },
  26454. enumerable: true,
  26455. configurable: true
  26456. });
  26457. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26458. get: function () {
  26459. return VertexBuffer._UV5Kind;
  26460. },
  26461. enumerable: true,
  26462. configurable: true
  26463. });
  26464. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26465. get: function () {
  26466. return VertexBuffer._UV6Kind;
  26467. },
  26468. enumerable: true,
  26469. configurable: true
  26470. });
  26471. Object.defineProperty(VertexBuffer, "ColorKind", {
  26472. get: function () {
  26473. return VertexBuffer._ColorKind;
  26474. },
  26475. enumerable: true,
  26476. configurable: true
  26477. });
  26478. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26479. get: function () {
  26480. return VertexBuffer._MatricesIndicesKind;
  26481. },
  26482. enumerable: true,
  26483. configurable: true
  26484. });
  26485. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26486. get: function () {
  26487. return VertexBuffer._MatricesWeightsKind;
  26488. },
  26489. enumerable: true,
  26490. configurable: true
  26491. });
  26492. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26493. get: function () {
  26494. return VertexBuffer._MatricesIndicesExtraKind;
  26495. },
  26496. enumerable: true,
  26497. configurable: true
  26498. });
  26499. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26500. get: function () {
  26501. return VertexBuffer._MatricesWeightsExtraKind;
  26502. },
  26503. enumerable: true,
  26504. configurable: true
  26505. });
  26506. /**
  26507. * Deduces the stride given a kind.
  26508. * @param kind The kind string to deduce
  26509. * @returns The deduced stride
  26510. */
  26511. VertexBuffer.DeduceStride = function (kind) {
  26512. switch (kind) {
  26513. case VertexBuffer.UVKind:
  26514. case VertexBuffer.UV2Kind:
  26515. case VertexBuffer.UV3Kind:
  26516. case VertexBuffer.UV4Kind:
  26517. case VertexBuffer.UV5Kind:
  26518. case VertexBuffer.UV6Kind:
  26519. return 2;
  26520. case VertexBuffer.NormalKind:
  26521. case VertexBuffer.PositionKind:
  26522. return 3;
  26523. case VertexBuffer.ColorKind:
  26524. case VertexBuffer.MatricesIndicesKind:
  26525. case VertexBuffer.MatricesIndicesExtraKind:
  26526. case VertexBuffer.MatricesWeightsKind:
  26527. case VertexBuffer.MatricesWeightsExtraKind:
  26528. case VertexBuffer.TangentKind:
  26529. return 4;
  26530. default:
  26531. throw new Error("Invalid kind '" + kind + "'");
  26532. }
  26533. };
  26534. // Enums
  26535. VertexBuffer._PositionKind = "position";
  26536. VertexBuffer._NormalKind = "normal";
  26537. VertexBuffer._TangentKind = "tangent";
  26538. VertexBuffer._UVKind = "uv";
  26539. VertexBuffer._UV2Kind = "uv2";
  26540. VertexBuffer._UV3Kind = "uv3";
  26541. VertexBuffer._UV4Kind = "uv4";
  26542. VertexBuffer._UV5Kind = "uv5";
  26543. VertexBuffer._UV6Kind = "uv6";
  26544. VertexBuffer._ColorKind = "color";
  26545. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26546. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26547. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26548. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26549. return VertexBuffer;
  26550. }());
  26551. BABYLON.VertexBuffer = VertexBuffer;
  26552. })(BABYLON || (BABYLON = {}));
  26553. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26554. "use strict";
  26555. var BABYLON;
  26556. (function (BABYLON) {
  26557. /**
  26558. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26559. */
  26560. var DummyInternalTextureTracker = /** @class */ (function () {
  26561. function DummyInternalTextureTracker() {
  26562. /**
  26563. * Gets or set the previous tracker in the list
  26564. */
  26565. this.previous = null;
  26566. /**
  26567. * Gets or set the next tracker in the list
  26568. */
  26569. this.next = null;
  26570. }
  26571. return DummyInternalTextureTracker;
  26572. }());
  26573. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26574. })(BABYLON || (BABYLON = {}));
  26575. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26576. "use strict";
  26577. var BABYLON;
  26578. (function (BABYLON) {
  26579. /**
  26580. * Class used to store data associated with WebGL texture data for the engine
  26581. * This class should not be used directly
  26582. */
  26583. var InternalTexture = /** @class */ (function () {
  26584. /**
  26585. * Creates a new InternalTexture
  26586. * @param engine defines the engine to use
  26587. * @param dataSource defines the type of data that will be used
  26588. */
  26589. function InternalTexture(engine, dataSource) {
  26590. /**
  26591. * Observable called when the texture is loaded
  26592. */
  26593. this.onLoadedObservable = new BABYLON.Observable();
  26594. /**
  26595. * Gets or set the previous tracker in the list
  26596. */
  26597. this.previous = null;
  26598. /**
  26599. * Gets or set the next tracker in the list
  26600. */
  26601. this.next = null;
  26602. // Private
  26603. /** @ignore */
  26604. this._initialSlot = -1;
  26605. /** @ignore */
  26606. this._designatedSlot = -1;
  26607. /** @ignore */
  26608. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26609. /** @ignore */
  26610. this._comparisonFunction = 0;
  26611. /** @ignore */
  26612. this._references = 1;
  26613. this._engine = engine;
  26614. this._dataSource = dataSource;
  26615. this._webGLTexture = engine._createTexture();
  26616. }
  26617. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26618. /**
  26619. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26620. */
  26621. get: function () {
  26622. return this._dataSource;
  26623. },
  26624. enumerable: true,
  26625. configurable: true
  26626. });
  26627. /**
  26628. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26629. */
  26630. InternalTexture.prototype.incrementReferences = function () {
  26631. this._references++;
  26632. };
  26633. /**
  26634. * Change the size of the texture (not the size of the content)
  26635. * @param width defines the new width
  26636. * @param height defines the new height
  26637. * @param depth defines the new depth (1 by default)
  26638. */
  26639. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26640. if (depth === void 0) { depth = 1; }
  26641. this.width = width;
  26642. this.height = height;
  26643. this.depth = depth;
  26644. this.baseWidth = width;
  26645. this.baseHeight = height;
  26646. this.baseDepth = depth;
  26647. this._size = width * height * depth;
  26648. };
  26649. /** @ignore */
  26650. InternalTexture.prototype._rebuild = function () {
  26651. var _this = this;
  26652. var proxy;
  26653. this.isReady = false;
  26654. this._cachedCoordinatesMode = null;
  26655. this._cachedWrapU = null;
  26656. this._cachedWrapV = null;
  26657. this._cachedAnisotropicFilteringLevel = null;
  26658. switch (this._dataSource) {
  26659. case InternalTexture.DATASOURCE_TEMP:
  26660. return;
  26661. case InternalTexture.DATASOURCE_URL:
  26662. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26663. _this.isReady = true;
  26664. }, null, this._buffer, undefined, this.format);
  26665. proxy._swapAndDie(this);
  26666. return;
  26667. case InternalTexture.DATASOURCE_RAW:
  26668. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26669. proxy._swapAndDie(this);
  26670. this.isReady = true;
  26671. return;
  26672. case InternalTexture.DATASOURCE_RAW3D:
  26673. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26674. proxy._swapAndDie(this);
  26675. this.isReady = true;
  26676. return;
  26677. case InternalTexture.DATASOURCE_DYNAMIC:
  26678. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26679. proxy._swapAndDie(this);
  26680. // The engine will make sure to update content so no need to flag it as isReady = true
  26681. return;
  26682. case InternalTexture.DATASOURCE_RENDERTARGET:
  26683. var options = new BABYLON.RenderTargetCreationOptions();
  26684. options.generateDepthBuffer = this._generateDepthBuffer;
  26685. options.generateMipMaps = this.generateMipMaps;
  26686. options.generateStencilBuffer = this._generateStencilBuffer;
  26687. options.samplingMode = this.samplingMode;
  26688. options.type = this.type;
  26689. if (this.isCube) {
  26690. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26691. }
  26692. else {
  26693. var size = {
  26694. width: this.width,
  26695. height: this.height
  26696. };
  26697. proxy = this._engine.createRenderTargetTexture(size, options);
  26698. }
  26699. proxy._swapAndDie(this);
  26700. this.isReady = true;
  26701. return;
  26702. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26703. var depthTextureOptions = {
  26704. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26705. comparisonFunction: this._comparisonFunction,
  26706. generateStencil: this._generateStencilBuffer,
  26707. isCube: this.isCube
  26708. };
  26709. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26710. proxy._swapAndDie(this);
  26711. this.isReady = true;
  26712. return;
  26713. case InternalTexture.DATASOURCE_CUBE:
  26714. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26715. _this.isReady = true;
  26716. }, null, this.format, this._extension);
  26717. proxy._swapAndDie(this);
  26718. return;
  26719. case InternalTexture.DATASOURCE_CUBERAW:
  26720. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26721. proxy._swapAndDie(this);
  26722. this.isReady = true;
  26723. return;
  26724. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26725. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26726. if (proxy) {
  26727. proxy._swapAndDie(_this);
  26728. }
  26729. _this.isReady = true;
  26730. }, null, this.format, this._extension);
  26731. return;
  26732. }
  26733. };
  26734. InternalTexture.prototype._swapAndDie = function (target) {
  26735. target._webGLTexture = this._webGLTexture;
  26736. if (this._framebuffer) {
  26737. target._framebuffer = this._framebuffer;
  26738. }
  26739. if (this._depthStencilBuffer) {
  26740. target._depthStencilBuffer = this._depthStencilBuffer;
  26741. }
  26742. if (this._lodTextureHigh) {
  26743. if (target._lodTextureHigh) {
  26744. target._lodTextureHigh.dispose();
  26745. }
  26746. target._lodTextureHigh = this._lodTextureHigh;
  26747. }
  26748. if (this._lodTextureMid) {
  26749. if (target._lodTextureMid) {
  26750. target._lodTextureMid.dispose();
  26751. }
  26752. target._lodTextureMid = this._lodTextureMid;
  26753. }
  26754. if (this._lodTextureLow) {
  26755. if (target._lodTextureLow) {
  26756. target._lodTextureLow.dispose();
  26757. }
  26758. target._lodTextureLow = this._lodTextureLow;
  26759. }
  26760. var cache = this._engine.getLoadedTexturesCache();
  26761. var index = cache.indexOf(this);
  26762. if (index !== -1) {
  26763. cache.splice(index, 1);
  26764. }
  26765. };
  26766. /**
  26767. * Dispose the current allocated resources
  26768. */
  26769. InternalTexture.prototype.dispose = function () {
  26770. if (!this._webGLTexture) {
  26771. return;
  26772. }
  26773. this._references--;
  26774. if (this._references === 0) {
  26775. this._engine._releaseTexture(this);
  26776. this._webGLTexture = null;
  26777. this.previous = null;
  26778. this.next = null;
  26779. }
  26780. };
  26781. /**
  26782. * The source of the texture data is unknown
  26783. */
  26784. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26785. /**
  26786. * Texture data comes from an URL
  26787. */
  26788. InternalTexture.DATASOURCE_URL = 1;
  26789. /**
  26790. * Texture data is only used for temporary storage
  26791. */
  26792. InternalTexture.DATASOURCE_TEMP = 2;
  26793. /**
  26794. * Texture data comes from raw data (ArrayBuffer)
  26795. */
  26796. InternalTexture.DATASOURCE_RAW = 3;
  26797. /**
  26798. * Texture content is dynamic (video or dynamic texture)
  26799. */
  26800. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26801. /**
  26802. * Texture content is generated by rendering to it
  26803. */
  26804. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26805. /**
  26806. * Texture content is part of a multi render target process
  26807. */
  26808. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26809. /**
  26810. * Texture data comes from a cube data file
  26811. */
  26812. InternalTexture.DATASOURCE_CUBE = 7;
  26813. /**
  26814. * Texture data comes from a raw cube data
  26815. */
  26816. InternalTexture.DATASOURCE_CUBERAW = 8;
  26817. /**
  26818. * Texture data come from a prefiltered cube data file
  26819. */
  26820. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26821. /**
  26822. * Texture content is raw 3D data
  26823. */
  26824. InternalTexture.DATASOURCE_RAW3D = 10;
  26825. /**
  26826. * Texture content is a depth texture
  26827. */
  26828. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26829. return InternalTexture;
  26830. }());
  26831. BABYLON.InternalTexture = InternalTexture;
  26832. })(BABYLON || (BABYLON = {}));
  26833. //# sourceMappingURL=babylon.internalTexture.js.map
  26834. "use strict";
  26835. var BABYLON;
  26836. (function (BABYLON) {
  26837. var BaseTexture = /** @class */ (function () {
  26838. function BaseTexture(scene) {
  26839. this._hasAlpha = false;
  26840. this.getAlphaFromRGB = false;
  26841. this.level = 1;
  26842. this.coordinatesIndex = 0;
  26843. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26844. /**
  26845. * | Value | Type | Description |
  26846. * | ----- | ------------------ | ----------- |
  26847. * | 0 | CLAMP_ADDRESSMODE | |
  26848. * | 1 | WRAP_ADDRESSMODE | |
  26849. * | 2 | MIRROR_ADDRESSMODE | |
  26850. */
  26851. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26852. /**
  26853. * | Value | Type | Description |
  26854. * | ----- | ------------------ | ----------- |
  26855. * | 0 | CLAMP_ADDRESSMODE | |
  26856. * | 1 | WRAP_ADDRESSMODE | |
  26857. * | 2 | MIRROR_ADDRESSMODE | |
  26858. */
  26859. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26860. /**
  26861. * | Value | Type | Description |
  26862. * | ----- | ------------------ | ----------- |
  26863. * | 0 | CLAMP_ADDRESSMODE | |
  26864. * | 1 | WRAP_ADDRESSMODE | |
  26865. * | 2 | MIRROR_ADDRESSMODE | |
  26866. */
  26867. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26868. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26869. this.isCube = false;
  26870. this.is3D = false;
  26871. this.gammaSpace = true;
  26872. this.invertZ = false;
  26873. this.lodLevelInAlpha = false;
  26874. this.lodGenerationOffset = 0.0;
  26875. this.lodGenerationScale = 0.8;
  26876. this.isRenderTarget = false;
  26877. this.animations = new Array();
  26878. /**
  26879. * An event triggered when the texture is disposed.
  26880. * @type {BABYLON.Observable}
  26881. */
  26882. this.onDisposeObservable = new BABYLON.Observable();
  26883. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26884. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26885. if (this._scene) {
  26886. this._scene.textures.push(this);
  26887. }
  26888. this._uid = null;
  26889. }
  26890. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26891. get: function () {
  26892. return this._hasAlpha;
  26893. },
  26894. set: function (value) {
  26895. if (this._hasAlpha === value) {
  26896. return;
  26897. }
  26898. this._hasAlpha = value;
  26899. if (this._scene) {
  26900. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26901. }
  26902. },
  26903. enumerable: true,
  26904. configurable: true
  26905. });
  26906. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26907. get: function () {
  26908. return this._coordinatesMode;
  26909. },
  26910. /**
  26911. * How a texture is mapped.
  26912. *
  26913. * | Value | Type | Description |
  26914. * | ----- | ----------------------------------- | ----------- |
  26915. * | 0 | EXPLICIT_MODE | |
  26916. * | 1 | SPHERICAL_MODE | |
  26917. * | 2 | PLANAR_MODE | |
  26918. * | 3 | CUBIC_MODE | |
  26919. * | 4 | PROJECTION_MODE | |
  26920. * | 5 | SKYBOX_MODE | |
  26921. * | 6 | INVCUBIC_MODE | |
  26922. * | 7 | EQUIRECTANGULAR_MODE | |
  26923. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26924. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26925. */
  26926. set: function (value) {
  26927. if (this._coordinatesMode === value) {
  26928. return;
  26929. }
  26930. this._coordinatesMode = value;
  26931. if (this._scene) {
  26932. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26933. }
  26934. },
  26935. enumerable: true,
  26936. configurable: true
  26937. });
  26938. Object.defineProperty(BaseTexture.prototype, "uid", {
  26939. get: function () {
  26940. if (!this._uid) {
  26941. this._uid = BABYLON.Tools.RandomId();
  26942. }
  26943. return this._uid;
  26944. },
  26945. enumerable: true,
  26946. configurable: true
  26947. });
  26948. BaseTexture.prototype.toString = function () {
  26949. return this.name;
  26950. };
  26951. BaseTexture.prototype.getClassName = function () {
  26952. return "BaseTexture";
  26953. };
  26954. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26955. set: function (callback) {
  26956. if (this._onDisposeObserver) {
  26957. this.onDisposeObservable.remove(this._onDisposeObserver);
  26958. }
  26959. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26960. },
  26961. enumerable: true,
  26962. configurable: true
  26963. });
  26964. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26965. get: function () {
  26966. return true;
  26967. },
  26968. enumerable: true,
  26969. configurable: true
  26970. });
  26971. BaseTexture.prototype.getScene = function () {
  26972. return this._scene;
  26973. };
  26974. BaseTexture.prototype.getTextureMatrix = function () {
  26975. return BABYLON.Matrix.IdentityReadOnly;
  26976. };
  26977. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26978. return BABYLON.Matrix.IdentityReadOnly;
  26979. };
  26980. BaseTexture.prototype.getInternalTexture = function () {
  26981. return this._texture;
  26982. };
  26983. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26984. return !this.isBlocking || this.isReady();
  26985. };
  26986. BaseTexture.prototype.isReady = function () {
  26987. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26988. this.delayLoad();
  26989. return false;
  26990. }
  26991. if (this._texture) {
  26992. return this._texture.isReady;
  26993. }
  26994. return false;
  26995. };
  26996. BaseTexture.prototype.getSize = function () {
  26997. if (this._texture && this._texture.width) {
  26998. return new BABYLON.Size(this._texture.width, this._texture.height);
  26999. }
  27000. if (this._texture && this._texture._size) {
  27001. return new BABYLON.Size(this._texture._size, this._texture._size);
  27002. }
  27003. return BABYLON.Size.Zero();
  27004. };
  27005. BaseTexture.prototype.getBaseSize = function () {
  27006. if (!this.isReady() || !this._texture)
  27007. return BABYLON.Size.Zero();
  27008. if (this._texture._size) {
  27009. return new BABYLON.Size(this._texture._size, this._texture._size);
  27010. }
  27011. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27012. };
  27013. BaseTexture.prototype.scale = function (ratio) {
  27014. };
  27015. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27016. get: function () {
  27017. return false;
  27018. },
  27019. enumerable: true,
  27020. configurable: true
  27021. });
  27022. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27023. if (!this._scene) {
  27024. return null;
  27025. }
  27026. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27027. for (var index = 0; index < texturesCache.length; index++) {
  27028. var texturesCacheEntry = texturesCache[index];
  27029. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27030. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27031. texturesCacheEntry.incrementReferences();
  27032. return texturesCacheEntry;
  27033. }
  27034. }
  27035. }
  27036. return null;
  27037. };
  27038. BaseTexture.prototype._rebuild = function () {
  27039. };
  27040. BaseTexture.prototype.delayLoad = function () {
  27041. };
  27042. BaseTexture.prototype.clone = function () {
  27043. return null;
  27044. };
  27045. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27046. get: function () {
  27047. if (!this._texture) {
  27048. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27049. }
  27050. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27051. },
  27052. enumerable: true,
  27053. configurable: true
  27054. });
  27055. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27056. get: function () {
  27057. if (!this._texture) {
  27058. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27059. }
  27060. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27061. },
  27062. enumerable: true,
  27063. configurable: true
  27064. });
  27065. BaseTexture.prototype.readPixels = function (faceIndex) {
  27066. if (faceIndex === void 0) { faceIndex = 0; }
  27067. if (!this._texture) {
  27068. return null;
  27069. }
  27070. var size = this.getSize();
  27071. var scene = this.getScene();
  27072. if (!scene) {
  27073. return null;
  27074. }
  27075. var engine = scene.getEngine();
  27076. if (this._texture.isCube) {
  27077. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27078. }
  27079. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27080. };
  27081. BaseTexture.prototype.releaseInternalTexture = function () {
  27082. if (this._texture) {
  27083. this._texture.dispose();
  27084. this._texture = null;
  27085. }
  27086. };
  27087. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27088. get: function () {
  27089. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27090. return null;
  27091. }
  27092. if (!this._texture._sphericalPolynomial) {
  27093. this._texture._sphericalPolynomial =
  27094. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27095. }
  27096. return this._texture._sphericalPolynomial;
  27097. },
  27098. set: function (value) {
  27099. if (this._texture) {
  27100. this._texture._sphericalPolynomial = value;
  27101. }
  27102. },
  27103. enumerable: true,
  27104. configurable: true
  27105. });
  27106. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27107. get: function () {
  27108. if (this._texture) {
  27109. return this._texture._lodTextureHigh;
  27110. }
  27111. return null;
  27112. },
  27113. enumerable: true,
  27114. configurable: true
  27115. });
  27116. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27117. get: function () {
  27118. if (this._texture) {
  27119. return this._texture._lodTextureMid;
  27120. }
  27121. return null;
  27122. },
  27123. enumerable: true,
  27124. configurable: true
  27125. });
  27126. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27127. get: function () {
  27128. if (this._texture) {
  27129. return this._texture._lodTextureLow;
  27130. }
  27131. return null;
  27132. },
  27133. enumerable: true,
  27134. configurable: true
  27135. });
  27136. BaseTexture.prototype.dispose = function () {
  27137. if (!this._scene) {
  27138. return;
  27139. }
  27140. // Animations
  27141. this._scene.stopAnimation(this);
  27142. // Remove from scene
  27143. this._scene._removePendingData(this);
  27144. var index = this._scene.textures.indexOf(this);
  27145. if (index >= 0) {
  27146. this._scene.textures.splice(index, 1);
  27147. }
  27148. if (this._texture === undefined) {
  27149. return;
  27150. }
  27151. // Release
  27152. this.releaseInternalTexture();
  27153. // Callback
  27154. this.onDisposeObservable.notifyObservers(this);
  27155. this.onDisposeObservable.clear();
  27156. };
  27157. BaseTexture.prototype.serialize = function () {
  27158. if (!this.name) {
  27159. return null;
  27160. }
  27161. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27162. // Animations
  27163. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27164. return serializationObject;
  27165. };
  27166. BaseTexture.WhenAllReady = function (textures, callback) {
  27167. var numRemaining = textures.length;
  27168. if (numRemaining === 0) {
  27169. callback();
  27170. return;
  27171. }
  27172. var _loop_1 = function () {
  27173. texture = textures[i];
  27174. if (texture.isReady()) {
  27175. if (--numRemaining === 0) {
  27176. callback();
  27177. }
  27178. }
  27179. else {
  27180. onLoadObservable = texture.onLoadObservable;
  27181. var onLoadCallback_1 = function () {
  27182. onLoadObservable.removeCallback(onLoadCallback_1);
  27183. if (--numRemaining === 0) {
  27184. callback();
  27185. }
  27186. };
  27187. onLoadObservable.add(onLoadCallback_1);
  27188. }
  27189. };
  27190. var texture, onLoadObservable;
  27191. for (var i = 0; i < textures.length; i++) {
  27192. _loop_1();
  27193. }
  27194. };
  27195. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27196. __decorate([
  27197. BABYLON.serialize()
  27198. ], BaseTexture.prototype, "name", void 0);
  27199. __decorate([
  27200. BABYLON.serialize("hasAlpha")
  27201. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27202. __decorate([
  27203. BABYLON.serialize()
  27204. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27205. __decorate([
  27206. BABYLON.serialize()
  27207. ], BaseTexture.prototype, "level", void 0);
  27208. __decorate([
  27209. BABYLON.serialize()
  27210. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27211. __decorate([
  27212. BABYLON.serialize("coordinatesMode")
  27213. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27214. __decorate([
  27215. BABYLON.serialize()
  27216. ], BaseTexture.prototype, "wrapU", void 0);
  27217. __decorate([
  27218. BABYLON.serialize()
  27219. ], BaseTexture.prototype, "wrapV", void 0);
  27220. __decorate([
  27221. BABYLON.serialize()
  27222. ], BaseTexture.prototype, "wrapR", void 0);
  27223. __decorate([
  27224. BABYLON.serialize()
  27225. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27226. __decorate([
  27227. BABYLON.serialize()
  27228. ], BaseTexture.prototype, "isCube", void 0);
  27229. __decorate([
  27230. BABYLON.serialize()
  27231. ], BaseTexture.prototype, "is3D", void 0);
  27232. __decorate([
  27233. BABYLON.serialize()
  27234. ], BaseTexture.prototype, "gammaSpace", void 0);
  27235. __decorate([
  27236. BABYLON.serialize()
  27237. ], BaseTexture.prototype, "invertZ", void 0);
  27238. __decorate([
  27239. BABYLON.serialize()
  27240. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27241. __decorate([
  27242. BABYLON.serialize()
  27243. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27244. __decorate([
  27245. BABYLON.serialize()
  27246. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27247. __decorate([
  27248. BABYLON.serialize()
  27249. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27250. return BaseTexture;
  27251. }());
  27252. BABYLON.BaseTexture = BaseTexture;
  27253. })(BABYLON || (BABYLON = {}));
  27254. //# sourceMappingURL=babylon.baseTexture.js.map
  27255. "use strict";
  27256. var BABYLON;
  27257. (function (BABYLON) {
  27258. var Texture = /** @class */ (function (_super) {
  27259. __extends(Texture, _super);
  27260. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27261. if (noMipmap === void 0) { noMipmap = false; }
  27262. if (invertY === void 0) { invertY = true; }
  27263. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27264. if (onLoad === void 0) { onLoad = null; }
  27265. if (onError === void 0) { onError = null; }
  27266. if (buffer === void 0) { buffer = null; }
  27267. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27268. var _this = _super.call(this, scene) || this;
  27269. _this.uOffset = 0;
  27270. _this.vOffset = 0;
  27271. _this.uScale = 1.0;
  27272. _this.vScale = 1.0;
  27273. _this.uAng = 0;
  27274. _this.vAng = 0;
  27275. _this.wAng = 0;
  27276. _this._isBlocking = true;
  27277. _this.name = url || "";
  27278. _this.url = url;
  27279. _this._noMipmap = noMipmap;
  27280. _this._invertY = invertY;
  27281. _this._samplingMode = samplingMode;
  27282. _this._buffer = buffer;
  27283. _this._deleteBuffer = deleteBuffer;
  27284. if (format) {
  27285. _this._format = format;
  27286. }
  27287. scene = _this.getScene();
  27288. if (!scene) {
  27289. return _this;
  27290. }
  27291. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27292. var load = function () {
  27293. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27294. _this.onLoadObservable.notifyObservers(_this);
  27295. }
  27296. if (onLoad) {
  27297. onLoad();
  27298. }
  27299. if (!_this.isBlocking && scene) {
  27300. scene.resetCachedMaterial();
  27301. }
  27302. };
  27303. if (!_this.url) {
  27304. _this._delayedOnLoad = load;
  27305. _this._delayedOnError = onError;
  27306. return _this;
  27307. }
  27308. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27309. if (!_this._texture) {
  27310. if (!scene.useDelayedTextureLoading) {
  27311. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27312. if (deleteBuffer) {
  27313. delete _this._buffer;
  27314. }
  27315. }
  27316. else {
  27317. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27318. _this._delayedOnLoad = load;
  27319. _this._delayedOnError = onError;
  27320. }
  27321. }
  27322. else {
  27323. if (_this._texture.isReady) {
  27324. BABYLON.Tools.SetImmediate(function () { return load(); });
  27325. }
  27326. else {
  27327. _this._texture.onLoadedObservable.add(load);
  27328. }
  27329. }
  27330. return _this;
  27331. }
  27332. Object.defineProperty(Texture.prototype, "noMipmap", {
  27333. get: function () {
  27334. return this._noMipmap;
  27335. },
  27336. enumerable: true,
  27337. configurable: true
  27338. });
  27339. Object.defineProperty(Texture.prototype, "isBlocking", {
  27340. get: function () {
  27341. return this._isBlocking;
  27342. },
  27343. set: function (value) {
  27344. this._isBlocking = value;
  27345. },
  27346. enumerable: true,
  27347. configurable: true
  27348. });
  27349. Object.defineProperty(Texture.prototype, "samplingMode", {
  27350. get: function () {
  27351. return this._samplingMode;
  27352. },
  27353. enumerable: true,
  27354. configurable: true
  27355. });
  27356. Texture.prototype.updateURL = function (url) {
  27357. this.url = url;
  27358. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27359. this.delayLoad();
  27360. };
  27361. Texture.prototype.delayLoad = function () {
  27362. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27363. return;
  27364. }
  27365. var scene = this.getScene();
  27366. if (!scene) {
  27367. return;
  27368. }
  27369. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27370. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27371. if (!this._texture) {
  27372. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27373. if (this._deleteBuffer) {
  27374. delete this._buffer;
  27375. }
  27376. }
  27377. else {
  27378. if (this._delayedOnLoad) {
  27379. if (this._texture.isReady) {
  27380. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27381. }
  27382. else {
  27383. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27384. }
  27385. }
  27386. }
  27387. this._delayedOnLoad = null;
  27388. this._delayedOnError = null;
  27389. };
  27390. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27391. if (!this._texture) {
  27392. return;
  27393. }
  27394. var scene = this.getScene();
  27395. if (!scene) {
  27396. return;
  27397. }
  27398. this._samplingMode = samplingMode;
  27399. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27400. };
  27401. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27402. x *= this.uScale;
  27403. y *= this.vScale;
  27404. x -= 0.5 * this.uScale;
  27405. y -= 0.5 * this.vScale;
  27406. z -= 0.5;
  27407. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27408. t.x += 0.5 * this.uScale + this.uOffset;
  27409. t.y += 0.5 * this.vScale + this.vOffset;
  27410. t.z += 0.5;
  27411. };
  27412. Texture.prototype.getTextureMatrix = function () {
  27413. var _this = this;
  27414. if (this.uOffset === this._cachedUOffset &&
  27415. this.vOffset === this._cachedVOffset &&
  27416. this.uScale === this._cachedUScale &&
  27417. this.vScale === this._cachedVScale &&
  27418. this.uAng === this._cachedUAng &&
  27419. this.vAng === this._cachedVAng &&
  27420. this.wAng === this._cachedWAng) {
  27421. return this._cachedTextureMatrix;
  27422. }
  27423. this._cachedUOffset = this.uOffset;
  27424. this._cachedVOffset = this.vOffset;
  27425. this._cachedUScale = this.uScale;
  27426. this._cachedVScale = this.vScale;
  27427. this._cachedUAng = this.uAng;
  27428. this._cachedVAng = this.vAng;
  27429. this._cachedWAng = this.wAng;
  27430. if (!this._cachedTextureMatrix) {
  27431. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27432. this._rowGenerationMatrix = new BABYLON.Matrix();
  27433. this._t0 = BABYLON.Vector3.Zero();
  27434. this._t1 = BABYLON.Vector3.Zero();
  27435. this._t2 = BABYLON.Vector3.Zero();
  27436. }
  27437. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27438. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27439. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27440. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27441. this._t1.subtractInPlace(this._t0);
  27442. this._t2.subtractInPlace(this._t0);
  27443. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27444. this._cachedTextureMatrix.m[0] = this._t1.x;
  27445. this._cachedTextureMatrix.m[1] = this._t1.y;
  27446. this._cachedTextureMatrix.m[2] = this._t1.z;
  27447. this._cachedTextureMatrix.m[4] = this._t2.x;
  27448. this._cachedTextureMatrix.m[5] = this._t2.y;
  27449. this._cachedTextureMatrix.m[6] = this._t2.z;
  27450. this._cachedTextureMatrix.m[8] = this._t0.x;
  27451. this._cachedTextureMatrix.m[9] = this._t0.y;
  27452. this._cachedTextureMatrix.m[10] = this._t0.z;
  27453. var scene = this.getScene();
  27454. if (!scene) {
  27455. return this._cachedTextureMatrix;
  27456. }
  27457. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27458. return mat.hasTexture(_this);
  27459. });
  27460. return this._cachedTextureMatrix;
  27461. };
  27462. Texture.prototype.getReflectionTextureMatrix = function () {
  27463. var _this = this;
  27464. var scene = this.getScene();
  27465. if (!scene) {
  27466. return this._cachedTextureMatrix;
  27467. }
  27468. if (this.uOffset === this._cachedUOffset &&
  27469. this.vOffset === this._cachedVOffset &&
  27470. this.uScale === this._cachedUScale &&
  27471. this.vScale === this._cachedVScale &&
  27472. this.coordinatesMode === this._cachedCoordinatesMode) {
  27473. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27474. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27475. return this._cachedTextureMatrix;
  27476. }
  27477. }
  27478. else {
  27479. return this._cachedTextureMatrix;
  27480. }
  27481. }
  27482. if (!this._cachedTextureMatrix) {
  27483. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27484. }
  27485. if (!this._projectionModeMatrix) {
  27486. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27487. }
  27488. this._cachedUOffset = this.uOffset;
  27489. this._cachedVOffset = this.vOffset;
  27490. this._cachedUScale = this.uScale;
  27491. this._cachedVScale = this.vScale;
  27492. this._cachedCoordinatesMode = this.coordinatesMode;
  27493. switch (this.coordinatesMode) {
  27494. case Texture.PLANAR_MODE:
  27495. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27496. this._cachedTextureMatrix[0] = this.uScale;
  27497. this._cachedTextureMatrix[5] = this.vScale;
  27498. this._cachedTextureMatrix[12] = this.uOffset;
  27499. this._cachedTextureMatrix[13] = this.vOffset;
  27500. break;
  27501. case Texture.PROJECTION_MODE:
  27502. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27503. this._projectionModeMatrix.m[0] = 0.5;
  27504. this._projectionModeMatrix.m[5] = -0.5;
  27505. this._projectionModeMatrix.m[10] = 0.0;
  27506. this._projectionModeMatrix.m[12] = 0.5;
  27507. this._projectionModeMatrix.m[13] = 0.5;
  27508. this._projectionModeMatrix.m[14] = 1.0;
  27509. this._projectionModeMatrix.m[15] = 1.0;
  27510. var projectionMatrix = scene.getProjectionMatrix();
  27511. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27512. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27513. break;
  27514. default:
  27515. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27516. break;
  27517. }
  27518. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27519. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27520. });
  27521. return this._cachedTextureMatrix;
  27522. };
  27523. Texture.prototype.clone = function () {
  27524. var _this = this;
  27525. return BABYLON.SerializationHelper.Clone(function () {
  27526. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27527. }, this);
  27528. };
  27529. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27530. get: function () {
  27531. if (!this._onLoadObservable) {
  27532. this._onLoadObservable = new BABYLON.Observable();
  27533. }
  27534. return this._onLoadObservable;
  27535. },
  27536. enumerable: true,
  27537. configurable: true
  27538. });
  27539. Texture.prototype.serialize = function () {
  27540. var serializationObject = _super.prototype.serialize.call(this);
  27541. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27542. serializationObject.base64String = this._buffer;
  27543. serializationObject.name = serializationObject.name.replace("data:", "");
  27544. }
  27545. return serializationObject;
  27546. };
  27547. Texture.prototype.getClassName = function () {
  27548. return "Texture";
  27549. };
  27550. Texture.prototype.dispose = function () {
  27551. _super.prototype.dispose.call(this);
  27552. if (this.onLoadObservable) {
  27553. this.onLoadObservable.clear();
  27554. this._onLoadObservable = null;
  27555. }
  27556. this._delayedOnLoad = null;
  27557. this._delayedOnError = null;
  27558. };
  27559. // Statics
  27560. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27561. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27562. if (onLoad === void 0) { onLoad = null; }
  27563. if (onError === void 0) { onError = null; }
  27564. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27565. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27566. };
  27567. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27568. if (parsedTexture.customType) {
  27569. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27570. // Update Sampling Mode
  27571. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27572. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27573. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27574. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27575. }
  27576. }
  27577. return parsedCustomTexture;
  27578. }
  27579. if (parsedTexture.isCube) {
  27580. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27581. }
  27582. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27583. return null;
  27584. }
  27585. var texture = BABYLON.SerializationHelper.Parse(function () {
  27586. var generateMipMaps = true;
  27587. if (parsedTexture.noMipmap) {
  27588. generateMipMaps = false;
  27589. }
  27590. if (parsedTexture.mirrorPlane) {
  27591. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27592. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27593. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27594. return mirrorTexture;
  27595. }
  27596. else if (parsedTexture.isRenderTarget) {
  27597. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27598. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27599. return renderTargetTexture;
  27600. }
  27601. else {
  27602. var texture;
  27603. if (parsedTexture.base64String) {
  27604. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27605. }
  27606. else {
  27607. var url = rootUrl + parsedTexture.name;
  27608. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27609. url = parsedTexture.url;
  27610. }
  27611. texture = new Texture(url, scene, !generateMipMaps);
  27612. }
  27613. return texture;
  27614. }
  27615. }, parsedTexture, scene);
  27616. // Update Sampling Mode
  27617. if (parsedTexture.samplingMode) {
  27618. var sampling = parsedTexture.samplingMode;
  27619. if (texture._samplingMode !== sampling) {
  27620. texture.updateSamplingMode(sampling);
  27621. }
  27622. }
  27623. // Animations
  27624. if (parsedTexture.animations) {
  27625. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27626. var parsedAnimation = parsedTexture.animations[animationIndex];
  27627. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27628. }
  27629. }
  27630. return texture;
  27631. };
  27632. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27633. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27634. if (noMipmap === void 0) { noMipmap = false; }
  27635. if (invertY === void 0) { invertY = true; }
  27636. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27637. if (onLoad === void 0) { onLoad = null; }
  27638. if (onError === void 0) { onError = null; }
  27639. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27640. if (name.substr(0, 5) !== "data:") {
  27641. name = "data:" + name;
  27642. }
  27643. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27644. };
  27645. // Constants
  27646. Texture.NEAREST_SAMPLINGMODE = 1;
  27647. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27648. Texture.BILINEAR_SAMPLINGMODE = 2;
  27649. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27650. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27651. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27652. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27653. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27654. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27655. Texture.NEAREST_LINEAR = 7;
  27656. Texture.NEAREST_NEAREST = 8;
  27657. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27658. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27659. Texture.LINEAR_LINEAR = 11;
  27660. Texture.LINEAR_NEAREST = 12;
  27661. Texture.EXPLICIT_MODE = 0;
  27662. Texture.SPHERICAL_MODE = 1;
  27663. Texture.PLANAR_MODE = 2;
  27664. Texture.CUBIC_MODE = 3;
  27665. Texture.PROJECTION_MODE = 4;
  27666. Texture.SKYBOX_MODE = 5;
  27667. Texture.INVCUBIC_MODE = 6;
  27668. Texture.EQUIRECTANGULAR_MODE = 7;
  27669. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27670. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27671. Texture.CLAMP_ADDRESSMODE = 0;
  27672. Texture.WRAP_ADDRESSMODE = 1;
  27673. Texture.MIRROR_ADDRESSMODE = 2;
  27674. /**
  27675. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  27676. */
  27677. Texture.UseSerializedUrlIfAny = false;
  27678. __decorate([
  27679. BABYLON.serialize()
  27680. ], Texture.prototype, "url", void 0);
  27681. __decorate([
  27682. BABYLON.serialize()
  27683. ], Texture.prototype, "uOffset", void 0);
  27684. __decorate([
  27685. BABYLON.serialize()
  27686. ], Texture.prototype, "vOffset", void 0);
  27687. __decorate([
  27688. BABYLON.serialize()
  27689. ], Texture.prototype, "uScale", void 0);
  27690. __decorate([
  27691. BABYLON.serialize()
  27692. ], Texture.prototype, "vScale", void 0);
  27693. __decorate([
  27694. BABYLON.serialize()
  27695. ], Texture.prototype, "uAng", void 0);
  27696. __decorate([
  27697. BABYLON.serialize()
  27698. ], Texture.prototype, "vAng", void 0);
  27699. __decorate([
  27700. BABYLON.serialize()
  27701. ], Texture.prototype, "wAng", void 0);
  27702. __decorate([
  27703. BABYLON.serialize()
  27704. ], Texture.prototype, "isBlocking", null);
  27705. return Texture;
  27706. }(BABYLON.BaseTexture));
  27707. BABYLON.Texture = Texture;
  27708. })(BABYLON || (BABYLON = {}));
  27709. //# sourceMappingURL=babylon.texture.js.map
  27710. "use strict";
  27711. var BABYLON;
  27712. (function (BABYLON) {
  27713. var _InstancesBatch = /** @class */ (function () {
  27714. function _InstancesBatch() {
  27715. this.mustReturn = false;
  27716. this.visibleInstances = new Array();
  27717. this.renderSelf = new Array();
  27718. }
  27719. return _InstancesBatch;
  27720. }());
  27721. BABYLON._InstancesBatch = _InstancesBatch;
  27722. var Mesh = /** @class */ (function (_super) {
  27723. __extends(Mesh, _super);
  27724. /**
  27725. * @constructor
  27726. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27727. * @param {Scene} scene The scene to add this mesh to.
  27728. * @param {Node} parent The parent of this mesh, if it has one
  27729. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27730. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27731. * When false, achieved by calling a clone(), also passing False.
  27732. * This will make creation of children, recursive.
  27733. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27734. */
  27735. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27736. if (scene === void 0) { scene = null; }
  27737. if (parent === void 0) { parent = null; }
  27738. if (source === void 0) { source = null; }
  27739. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27740. var _this = _super.call(this, name, scene) || this;
  27741. // Events
  27742. /**
  27743. * An event triggered before rendering the mesh
  27744. * @type {BABYLON.Observable}
  27745. */
  27746. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27747. /**
  27748. * An event triggered after rendering the mesh
  27749. * @type {BABYLON.Observable}
  27750. */
  27751. _this.onAfterRenderObservable = new BABYLON.Observable();
  27752. /**
  27753. * An event triggered before drawing the mesh
  27754. * @type {BABYLON.Observable}
  27755. */
  27756. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27757. // Members
  27758. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27759. _this.instances = new Array();
  27760. _this._LODLevels = new Array();
  27761. _this._visibleInstances = {};
  27762. _this._renderIdForInstances = new Array();
  27763. _this._batchCache = new _InstancesBatch();
  27764. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27765. // Use by builder only to know what orientation were the mesh build in.
  27766. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27767. _this.overrideMaterialSideOrientation = null;
  27768. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27769. // Will be used to save a source mesh reference, If any
  27770. _this._source = null;
  27771. scene = _this.getScene();
  27772. if (source) {
  27773. // Source mesh
  27774. _this._source = source;
  27775. // Geometry
  27776. if (source._geometry) {
  27777. source._geometry.applyToMesh(_this);
  27778. }
  27779. // Deep copy
  27780. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  27781. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  27782. // Metadata
  27783. if (source.metadata && source.metadata.clone) {
  27784. _this.metadata = source.metadata.clone();
  27785. }
  27786. else {
  27787. _this.metadata = source.metadata;
  27788. }
  27789. // Tags
  27790. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27791. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27792. }
  27793. // Parent
  27794. _this.parent = source.parent;
  27795. // Pivot
  27796. _this.setPivotMatrix(source.getPivotMatrix());
  27797. _this.id = name + "." + source.id;
  27798. // Material
  27799. _this.material = source.material;
  27800. var index;
  27801. if (!doNotCloneChildren) {
  27802. // Children
  27803. var directDescendants = source.getDescendants(true);
  27804. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27805. var child = directDescendants[index_1];
  27806. if (child.clone) {
  27807. child.clone(name + "." + child.name, _this);
  27808. }
  27809. }
  27810. }
  27811. // Physics clone
  27812. var physicsEngine = _this.getScene().getPhysicsEngine();
  27813. if (clonePhysicsImpostor && physicsEngine) {
  27814. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27815. if (impostor) {
  27816. _this.physicsImpostor = impostor.clone(_this);
  27817. }
  27818. }
  27819. // Particles
  27820. for (index = 0; index < scene.particleSystems.length; index++) {
  27821. var system = scene.particleSystems[index];
  27822. if (system.emitter === source) {
  27823. system.clone(system.name, _this);
  27824. }
  27825. }
  27826. _this.computeWorldMatrix(true);
  27827. }
  27828. // Parent
  27829. if (parent !== null) {
  27830. _this.parent = parent;
  27831. }
  27832. return _this;
  27833. }
  27834. Object.defineProperty(Mesh, "FRONTSIDE", {
  27835. /**
  27836. * Mesh side orientation : usually the external or front surface
  27837. */
  27838. get: function () {
  27839. return Mesh._FRONTSIDE;
  27840. },
  27841. enumerable: true,
  27842. configurable: true
  27843. });
  27844. Object.defineProperty(Mesh, "BACKSIDE", {
  27845. /**
  27846. * Mesh side orientation : usually the internal or back surface
  27847. */
  27848. get: function () {
  27849. return Mesh._BACKSIDE;
  27850. },
  27851. enumerable: true,
  27852. configurable: true
  27853. });
  27854. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27855. /**
  27856. * Mesh side orientation : both internal and external or front and back surfaces
  27857. */
  27858. get: function () {
  27859. return Mesh._DOUBLESIDE;
  27860. },
  27861. enumerable: true,
  27862. configurable: true
  27863. });
  27864. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27865. /**
  27866. * Mesh side orientation : by default, `FRONTSIDE`
  27867. */
  27868. get: function () {
  27869. return Mesh._DEFAULTSIDE;
  27870. },
  27871. enumerable: true,
  27872. configurable: true
  27873. });
  27874. Object.defineProperty(Mesh, "NO_CAP", {
  27875. /**
  27876. * Mesh cap setting : no cap
  27877. */
  27878. get: function () {
  27879. return Mesh._NO_CAP;
  27880. },
  27881. enumerable: true,
  27882. configurable: true
  27883. });
  27884. Object.defineProperty(Mesh, "CAP_START", {
  27885. /**
  27886. * Mesh cap setting : one cap at the beginning of the mesh
  27887. */
  27888. get: function () {
  27889. return Mesh._CAP_START;
  27890. },
  27891. enumerable: true,
  27892. configurable: true
  27893. });
  27894. Object.defineProperty(Mesh, "CAP_END", {
  27895. /**
  27896. * Mesh cap setting : one cap at the end of the mesh
  27897. */
  27898. get: function () {
  27899. return Mesh._CAP_END;
  27900. },
  27901. enumerable: true,
  27902. configurable: true
  27903. });
  27904. Object.defineProperty(Mesh, "CAP_ALL", {
  27905. /**
  27906. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27907. */
  27908. get: function () {
  27909. return Mesh._CAP_ALL;
  27910. },
  27911. enumerable: true,
  27912. configurable: true
  27913. });
  27914. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27915. set: function (callback) {
  27916. if (this._onBeforeDrawObserver) {
  27917. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27918. }
  27919. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27920. },
  27921. enumerable: true,
  27922. configurable: true
  27923. });
  27924. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27925. get: function () {
  27926. return this._morphTargetManager;
  27927. },
  27928. set: function (value) {
  27929. if (this._morphTargetManager === value) {
  27930. return;
  27931. }
  27932. this._morphTargetManager = value;
  27933. this._syncGeometryWithMorphTargetManager();
  27934. },
  27935. enumerable: true,
  27936. configurable: true
  27937. });
  27938. Object.defineProperty(Mesh.prototype, "source", {
  27939. get: function () {
  27940. return this._source;
  27941. },
  27942. enumerable: true,
  27943. configurable: true
  27944. });
  27945. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27946. get: function () {
  27947. return this._unIndexed;
  27948. },
  27949. set: function (value) {
  27950. if (this._unIndexed !== value) {
  27951. this._unIndexed = value;
  27952. this._markSubMeshesAsAttributesDirty();
  27953. }
  27954. },
  27955. enumerable: true,
  27956. configurable: true
  27957. });
  27958. // Methods
  27959. /**
  27960. * Returns the string "Mesh".
  27961. */
  27962. Mesh.prototype.getClassName = function () {
  27963. return "Mesh";
  27964. };
  27965. /**
  27966. * Returns a string.
  27967. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27968. */
  27969. Mesh.prototype.toString = function (fullDetails) {
  27970. var ret = _super.prototype.toString.call(this, fullDetails);
  27971. ret += ", n vertices: " + this.getTotalVertices();
  27972. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27973. if (this.animations) {
  27974. for (var i = 0; i < this.animations.length; i++) {
  27975. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27976. }
  27977. }
  27978. if (fullDetails) {
  27979. if (this._geometry) {
  27980. var ib = this.getIndices();
  27981. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27982. if (vb && ib) {
  27983. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27984. }
  27985. }
  27986. else {
  27987. ret += ", flat shading: UNKNOWN";
  27988. }
  27989. }
  27990. return ret;
  27991. };
  27992. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27993. /**
  27994. * True if the mesh has some Levels Of Details (LOD).
  27995. * Returns a boolean.
  27996. */
  27997. get: function () {
  27998. return this._LODLevels.length > 0;
  27999. },
  28000. enumerable: true,
  28001. configurable: true
  28002. });
  28003. /**
  28004. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28005. * @returns an array of {BABYLON.MeshLODLevel}
  28006. */
  28007. Mesh.prototype.getLODLevels = function () {
  28008. return this._LODLevels;
  28009. };
  28010. Mesh.prototype._sortLODLevels = function () {
  28011. this._LODLevels.sort(function (a, b) {
  28012. if (a.distance < b.distance) {
  28013. return 1;
  28014. }
  28015. if (a.distance > b.distance) {
  28016. return -1;
  28017. }
  28018. return 0;
  28019. });
  28020. };
  28021. /**
  28022. * Add a mesh as LOD level triggered at the given distance.
  28023. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28024. * @param {number} distance The distance from the center of the object to show this level
  28025. * @param {Mesh} mesh The mesh to be added as LOD level
  28026. * @return {Mesh} This mesh (for chaining)
  28027. */
  28028. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28029. if (mesh && mesh._masterMesh) {
  28030. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28031. return this;
  28032. }
  28033. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28034. this._LODLevels.push(level);
  28035. if (mesh) {
  28036. mesh._masterMesh = this;
  28037. }
  28038. this._sortLODLevels();
  28039. return this;
  28040. };
  28041. /**
  28042. * Returns the LOD level mesh at the passed distance or null if not found.
  28043. * It is related to the method `addLODLevel(distance, mesh)`.
  28044. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28045. * Returns an object Mesh or `null`.
  28046. */
  28047. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28048. for (var index = 0; index < this._LODLevels.length; index++) {
  28049. var level = this._LODLevels[index];
  28050. if (level.distance === distance) {
  28051. return level.mesh;
  28052. }
  28053. }
  28054. return null;
  28055. };
  28056. /**
  28057. * Remove a mesh from the LOD array
  28058. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28059. * @param {Mesh} mesh The mesh to be removed.
  28060. * @return {Mesh} This mesh (for chaining)
  28061. */
  28062. Mesh.prototype.removeLODLevel = function (mesh) {
  28063. for (var index = 0; index < this._LODLevels.length; index++) {
  28064. if (this._LODLevels[index].mesh === mesh) {
  28065. this._LODLevels.splice(index, 1);
  28066. if (mesh) {
  28067. mesh._masterMesh = null;
  28068. }
  28069. }
  28070. }
  28071. this._sortLODLevels();
  28072. return this;
  28073. };
  28074. /**
  28075. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28076. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28077. */
  28078. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28079. if (!this._LODLevels || this._LODLevels.length === 0) {
  28080. return this;
  28081. }
  28082. var bSphere;
  28083. if (boundingSphere) {
  28084. bSphere = boundingSphere;
  28085. }
  28086. else {
  28087. var boundingInfo = this.getBoundingInfo();
  28088. bSphere = boundingInfo.boundingSphere;
  28089. }
  28090. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28091. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28092. if (this.onLODLevelSelection) {
  28093. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28094. }
  28095. return this;
  28096. }
  28097. for (var index = 0; index < this._LODLevels.length; index++) {
  28098. var level = this._LODLevels[index];
  28099. if (level.distance < distanceToCamera) {
  28100. if (level.mesh) {
  28101. level.mesh._preActivate();
  28102. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28103. }
  28104. if (this.onLODLevelSelection) {
  28105. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28106. }
  28107. return level.mesh;
  28108. }
  28109. }
  28110. if (this.onLODLevelSelection) {
  28111. this.onLODLevelSelection(distanceToCamera, this, this);
  28112. }
  28113. return this;
  28114. };
  28115. Object.defineProperty(Mesh.prototype, "geometry", {
  28116. /**
  28117. * Returns the mesh internal Geometry object.
  28118. */
  28119. get: function () {
  28120. return this._geometry;
  28121. },
  28122. enumerable: true,
  28123. configurable: true
  28124. });
  28125. /**
  28126. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28127. */
  28128. Mesh.prototype.getTotalVertices = function () {
  28129. if (this._geometry === null || this._geometry === undefined) {
  28130. return 0;
  28131. }
  28132. return this._geometry.getTotalVertices();
  28133. };
  28134. /**
  28135. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28136. * 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.
  28137. * You can force the copy with forceCopy === true
  28138. * Returns null if the mesh has no geometry or no vertex buffer.
  28139. * Possible `kind` values :
  28140. * - BABYLON.VertexBuffer.PositionKind
  28141. * - BABYLON.VertexBuffer.UVKind
  28142. * - BABYLON.VertexBuffer.UV2Kind
  28143. * - BABYLON.VertexBuffer.UV3Kind
  28144. * - BABYLON.VertexBuffer.UV4Kind
  28145. * - BABYLON.VertexBuffer.UV5Kind
  28146. * - BABYLON.VertexBuffer.UV6Kind
  28147. * - BABYLON.VertexBuffer.ColorKind
  28148. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28149. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28150. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28151. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28152. */
  28153. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28154. if (!this._geometry) {
  28155. return null;
  28156. }
  28157. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28158. };
  28159. /**
  28160. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28161. * Returns `null` if the mesh has no geometry.
  28162. * Possible `kind` values :
  28163. * - BABYLON.VertexBuffer.PositionKind
  28164. * - BABYLON.VertexBuffer.UVKind
  28165. * - BABYLON.VertexBuffer.UV2Kind
  28166. * - BABYLON.VertexBuffer.UV3Kind
  28167. * - BABYLON.VertexBuffer.UV4Kind
  28168. * - BABYLON.VertexBuffer.UV5Kind
  28169. * - BABYLON.VertexBuffer.UV6Kind
  28170. * - BABYLON.VertexBuffer.ColorKind
  28171. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28172. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28173. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28174. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28175. */
  28176. Mesh.prototype.getVertexBuffer = function (kind) {
  28177. if (!this._geometry) {
  28178. return null;
  28179. }
  28180. return this._geometry.getVertexBuffer(kind);
  28181. };
  28182. /**
  28183. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28184. * Possible `kind` values :
  28185. * - BABYLON.VertexBuffer.PositionKind
  28186. * - BABYLON.VertexBuffer.UVKind
  28187. * - BABYLON.VertexBuffer.UV2Kind
  28188. * - BABYLON.VertexBuffer.UV3Kind
  28189. * - BABYLON.VertexBuffer.UV4Kind
  28190. * - BABYLON.VertexBuffer.UV5Kind
  28191. * - BABYLON.VertexBuffer.UV6Kind
  28192. * - BABYLON.VertexBuffer.ColorKind
  28193. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28194. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28195. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28196. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28197. */
  28198. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28199. if (!this._geometry) {
  28200. if (this._delayInfo) {
  28201. return this._delayInfo.indexOf(kind) !== -1;
  28202. }
  28203. return false;
  28204. }
  28205. return this._geometry.isVerticesDataPresent(kind);
  28206. };
  28207. /**
  28208. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28209. * Possible `kind` values :
  28210. * - BABYLON.VertexBuffer.PositionKind
  28211. * - BABYLON.VertexBuffer.UVKind
  28212. * - BABYLON.VertexBuffer.UV2Kind
  28213. * - BABYLON.VertexBuffer.UV3Kind
  28214. * - BABYLON.VertexBuffer.UV4Kind
  28215. * - BABYLON.VertexBuffer.UV5Kind
  28216. * - BABYLON.VertexBuffer.UV6Kind
  28217. * - BABYLON.VertexBuffer.ColorKind
  28218. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28219. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28220. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28221. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28222. */
  28223. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28224. if (!this._geometry) {
  28225. if (this._delayInfo) {
  28226. return this._delayInfo.indexOf(kind) !== -1;
  28227. }
  28228. return false;
  28229. }
  28230. return this._geometry.isVertexBufferUpdatable(kind);
  28231. };
  28232. /**
  28233. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28234. * Possible `kind` values :
  28235. * - BABYLON.VertexBuffer.PositionKind
  28236. * - BABYLON.VertexBuffer.UVKind
  28237. * - BABYLON.VertexBuffer.UV2Kind
  28238. * - BABYLON.VertexBuffer.UV3Kind
  28239. * - BABYLON.VertexBuffer.UV4Kind
  28240. * - BABYLON.VertexBuffer.UV5Kind
  28241. * - BABYLON.VertexBuffer.UV6Kind
  28242. * - BABYLON.VertexBuffer.ColorKind
  28243. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28244. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28245. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28246. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28247. */
  28248. Mesh.prototype.getVerticesDataKinds = function () {
  28249. if (!this._geometry) {
  28250. var result = new Array();
  28251. if (this._delayInfo) {
  28252. this._delayInfo.forEach(function (kind, index, array) {
  28253. result.push(kind);
  28254. });
  28255. }
  28256. return result;
  28257. }
  28258. return this._geometry.getVerticesDataKinds();
  28259. };
  28260. /**
  28261. * Returns a positive integer : the total number of indices in this mesh geometry.
  28262. * Returns zero if the mesh has no geometry.
  28263. */
  28264. Mesh.prototype.getTotalIndices = function () {
  28265. if (!this._geometry) {
  28266. return 0;
  28267. }
  28268. return this._geometry.getTotalIndices();
  28269. };
  28270. /**
  28271. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28272. * 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.
  28273. * Returns an empty array if the mesh has no geometry.
  28274. */
  28275. Mesh.prototype.getIndices = function (copyWhenShared) {
  28276. if (!this._geometry) {
  28277. return [];
  28278. }
  28279. return this._geometry.getIndices(copyWhenShared);
  28280. };
  28281. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28282. get: function () {
  28283. return this._masterMesh !== null && this._masterMesh !== undefined;
  28284. },
  28285. enumerable: true,
  28286. configurable: true
  28287. });
  28288. /**
  28289. * Determine if the current mesh is ready to be rendered
  28290. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28291. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28292. * @returns true if all associated assets are ready (material, textures, shaders)
  28293. */
  28294. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28295. if (completeCheck === void 0) { completeCheck = false; }
  28296. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28297. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28298. return false;
  28299. }
  28300. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28301. return false;
  28302. }
  28303. if (!this.subMeshes || this.subMeshes.length === 0) {
  28304. return true;
  28305. }
  28306. if (!completeCheck) {
  28307. return true;
  28308. }
  28309. var engine = this.getEngine();
  28310. var scene = this.getScene();
  28311. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28312. this.computeWorldMatrix();
  28313. var mat = this.material || scene.defaultMaterial;
  28314. if (mat) {
  28315. if (mat.storeEffectOnSubMeshes) {
  28316. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28317. var subMesh = _a[_i];
  28318. var effectiveMaterial = subMesh.getMaterial();
  28319. if (effectiveMaterial) {
  28320. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28321. return false;
  28322. }
  28323. }
  28324. }
  28325. }
  28326. else {
  28327. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28328. return false;
  28329. }
  28330. }
  28331. }
  28332. // Shadows
  28333. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28334. var light = _c[_b];
  28335. var generator = light.getShadowGenerator();
  28336. if (generator) {
  28337. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28338. var subMesh = _e[_d];
  28339. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28340. return false;
  28341. }
  28342. }
  28343. }
  28344. }
  28345. // LOD
  28346. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28347. var lod = _g[_f];
  28348. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28349. return false;
  28350. }
  28351. }
  28352. return true;
  28353. };
  28354. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28355. /**
  28356. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28357. * This property is pertinent only for updatable parametric shapes.
  28358. */
  28359. get: function () {
  28360. return this._areNormalsFrozen;
  28361. },
  28362. enumerable: true,
  28363. configurable: true
  28364. });
  28365. /**
  28366. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28367. * It has no effect at all on other shapes.
  28368. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28369. * Returns the Mesh.
  28370. */
  28371. Mesh.prototype.freezeNormals = function () {
  28372. this._areNormalsFrozen = true;
  28373. return this;
  28374. };
  28375. /**
  28376. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28377. * It has no effect at all on other shapes.
  28378. * It reactivates the mesh normals computation if it was previously frozen.
  28379. * Returns the Mesh.
  28380. */
  28381. Mesh.prototype.unfreezeNormals = function () {
  28382. this._areNormalsFrozen = false;
  28383. return this;
  28384. };
  28385. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28386. /**
  28387. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28388. */
  28389. set: function (count) {
  28390. this._overridenInstanceCount = count;
  28391. },
  28392. enumerable: true,
  28393. configurable: true
  28394. });
  28395. // Methods
  28396. Mesh.prototype._preActivate = function () {
  28397. var sceneRenderId = this.getScene().getRenderId();
  28398. if (this._preActivateId === sceneRenderId) {
  28399. return this;
  28400. }
  28401. this._preActivateId = sceneRenderId;
  28402. this._visibleInstances = null;
  28403. return this;
  28404. };
  28405. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28406. if (this._visibleInstances) {
  28407. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28408. }
  28409. return this;
  28410. };
  28411. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28412. if (!this._visibleInstances) {
  28413. this._visibleInstances = {};
  28414. this._visibleInstances.defaultRenderId = renderId;
  28415. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28416. }
  28417. if (!this._visibleInstances[renderId]) {
  28418. this._visibleInstances[renderId] = new Array();
  28419. }
  28420. this._visibleInstances[renderId].push(instance);
  28421. return this;
  28422. };
  28423. /**
  28424. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28425. * This means the mesh underlying bounding box and sphere are recomputed.
  28426. * Returns the Mesh.
  28427. */
  28428. Mesh.prototype.refreshBoundingInfo = function () {
  28429. return this._refreshBoundingInfo(false);
  28430. };
  28431. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28432. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28433. return this;
  28434. }
  28435. var data = this._getPositionData(applySkeleton);
  28436. if (data) {
  28437. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28438. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28439. }
  28440. if (this.subMeshes) {
  28441. for (var index = 0; index < this.subMeshes.length; index++) {
  28442. this.subMeshes[index].refreshBoundingInfo();
  28443. }
  28444. }
  28445. this._updateBoundingInfo();
  28446. return this;
  28447. };
  28448. Mesh.prototype._getPositionData = function (applySkeleton) {
  28449. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28450. if (data && applySkeleton && this.skeleton) {
  28451. data = BABYLON.Tools.Slice(data);
  28452. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28453. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28454. if (matricesWeightsData && matricesIndicesData) {
  28455. var needExtras = this.numBoneInfluencers > 4;
  28456. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28457. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28458. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28459. var tempVector = BABYLON.Tmp.Vector3[0];
  28460. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28461. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28462. var matWeightIdx = 0;
  28463. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28464. finalMatrix.reset();
  28465. var inf;
  28466. var weight;
  28467. for (inf = 0; inf < 4; inf++) {
  28468. weight = matricesWeightsData[matWeightIdx + inf];
  28469. if (weight <= 0)
  28470. break;
  28471. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28472. finalMatrix.addToSelf(tempMatrix);
  28473. }
  28474. if (needExtras) {
  28475. for (inf = 0; inf < 4; inf++) {
  28476. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28477. if (weight <= 0)
  28478. break;
  28479. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28480. finalMatrix.addToSelf(tempMatrix);
  28481. }
  28482. }
  28483. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28484. tempVector.toArray(data, index);
  28485. }
  28486. }
  28487. }
  28488. return data;
  28489. };
  28490. Mesh.prototype._createGlobalSubMesh = function (force) {
  28491. var totalVertices = this.getTotalVertices();
  28492. if (!totalVertices || !this.getIndices()) {
  28493. return null;
  28494. }
  28495. // Check if we need to recreate the submeshes
  28496. if (this.subMeshes && this.subMeshes.length > 0) {
  28497. var ib = this.getIndices();
  28498. if (!ib) {
  28499. return null;
  28500. }
  28501. var totalIndices = ib.length;
  28502. var needToRecreate = false;
  28503. if (force) {
  28504. needToRecreate = true;
  28505. }
  28506. else {
  28507. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28508. var submesh = _a[_i];
  28509. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28510. needToRecreate = true;
  28511. break;
  28512. }
  28513. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28514. needToRecreate = true;
  28515. break;
  28516. }
  28517. }
  28518. }
  28519. if (!needToRecreate) {
  28520. return this.subMeshes[0];
  28521. }
  28522. }
  28523. this.releaseSubMeshes();
  28524. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28525. };
  28526. Mesh.prototype.subdivide = function (count) {
  28527. if (count < 1) {
  28528. return;
  28529. }
  28530. var totalIndices = this.getTotalIndices();
  28531. var subdivisionSize = (totalIndices / count) | 0;
  28532. var offset = 0;
  28533. // Ensure that subdivisionSize is a multiple of 3
  28534. while (subdivisionSize % 3 !== 0) {
  28535. subdivisionSize++;
  28536. }
  28537. this.releaseSubMeshes();
  28538. for (var index = 0; index < count; index++) {
  28539. if (offset >= totalIndices) {
  28540. break;
  28541. }
  28542. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28543. offset += subdivisionSize;
  28544. }
  28545. this.synchronizeInstances();
  28546. };
  28547. /**
  28548. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28549. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28550. * The `data` are either a numeric array either a Float32Array.
  28551. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28552. * 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).
  28553. * Note that a new underlying VertexBuffer object is created each call.
  28554. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28555. *
  28556. * Possible `kind` values :
  28557. * - BABYLON.VertexBuffer.PositionKind
  28558. * - BABYLON.VertexBuffer.UVKind
  28559. * - BABYLON.VertexBuffer.UV2Kind
  28560. * - BABYLON.VertexBuffer.UV3Kind
  28561. * - BABYLON.VertexBuffer.UV4Kind
  28562. * - BABYLON.VertexBuffer.UV5Kind
  28563. * - BABYLON.VertexBuffer.UV6Kind
  28564. * - BABYLON.VertexBuffer.ColorKind
  28565. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28566. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28567. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28568. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28569. *
  28570. * Returns the Mesh.
  28571. */
  28572. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28573. if (updatable === void 0) { updatable = false; }
  28574. if (!this._geometry) {
  28575. var vertexData = new BABYLON.VertexData();
  28576. vertexData.set(data, kind);
  28577. var scene = this.getScene();
  28578. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28579. }
  28580. else {
  28581. this._geometry.setVerticesData(kind, data, updatable, stride);
  28582. }
  28583. return this;
  28584. };
  28585. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28586. if (updatable === void 0) { updatable = true; }
  28587. var vb = this.getVertexBuffer(kind);
  28588. if (!vb || vb.isUpdatable() === updatable) {
  28589. return;
  28590. }
  28591. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28592. };
  28593. /**
  28594. * Sets the mesh VertexBuffer.
  28595. * Returns the Mesh.
  28596. */
  28597. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28598. if (!this._geometry) {
  28599. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28600. }
  28601. this._geometry.setVerticesBuffer(buffer);
  28602. return this;
  28603. };
  28604. /**
  28605. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28606. * If the mesh has no geometry, it is simply returned as it is.
  28607. * The `data` are either a numeric array either a Float32Array.
  28608. * No new underlying VertexBuffer object is created.
  28609. * 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.
  28610. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28611. *
  28612. * Possible `kind` values :
  28613. * - BABYLON.VertexBuffer.PositionKind
  28614. * - BABYLON.VertexBuffer.UVKind
  28615. * - BABYLON.VertexBuffer.UV2Kind
  28616. * - BABYLON.VertexBuffer.UV3Kind
  28617. * - BABYLON.VertexBuffer.UV4Kind
  28618. * - BABYLON.VertexBuffer.UV5Kind
  28619. * - BABYLON.VertexBuffer.UV6Kind
  28620. * - BABYLON.VertexBuffer.ColorKind
  28621. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28622. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28623. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28624. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28625. *
  28626. * Returns the Mesh.
  28627. */
  28628. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28629. if (!this._geometry) {
  28630. return this;
  28631. }
  28632. if (!makeItUnique) {
  28633. this._geometry.updateVerticesData(kind, data, updateExtends);
  28634. }
  28635. else {
  28636. this.makeGeometryUnique();
  28637. this.updateVerticesData(kind, data, updateExtends, false);
  28638. }
  28639. return this;
  28640. };
  28641. /**
  28642. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28643. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28644. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28645. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28646. * Returns the Mesh.
  28647. */
  28648. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28649. if (computeNormals === void 0) { computeNormals = true; }
  28650. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28651. if (!positions) {
  28652. return this;
  28653. }
  28654. positionFunction(positions);
  28655. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28656. if (computeNormals) {
  28657. var indices = this.getIndices();
  28658. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28659. if (!normals) {
  28660. return this;
  28661. }
  28662. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28663. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28664. }
  28665. return this;
  28666. };
  28667. /**
  28668. * Creates a un-shared specific occurence of the geometry for the mesh.
  28669. * Returns the Mesh.
  28670. */
  28671. Mesh.prototype.makeGeometryUnique = function () {
  28672. if (!this._geometry) {
  28673. return this;
  28674. }
  28675. var oldGeometry = this._geometry;
  28676. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28677. oldGeometry.releaseForMesh(this, true);
  28678. geometry.applyToMesh(this);
  28679. return this;
  28680. };
  28681. /**
  28682. * Sets the mesh indices.
  28683. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28684. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28685. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28686. * This method creates a new index buffer each call.
  28687. * Returns the Mesh.
  28688. */
  28689. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28690. if (totalVertices === void 0) { totalVertices = null; }
  28691. if (updatable === void 0) { updatable = false; }
  28692. if (!this._geometry) {
  28693. var vertexData = new BABYLON.VertexData();
  28694. vertexData.indices = indices;
  28695. var scene = this.getScene();
  28696. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28697. }
  28698. else {
  28699. this._geometry.setIndices(indices, totalVertices, updatable);
  28700. }
  28701. return this;
  28702. };
  28703. /**
  28704. * Update the current index buffer
  28705. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28706. * Returns the Mesh.
  28707. */
  28708. Mesh.prototype.updateIndices = function (indices, offset) {
  28709. if (!this._geometry) {
  28710. return this;
  28711. }
  28712. this._geometry.updateIndices(indices, offset);
  28713. return this;
  28714. };
  28715. /**
  28716. * Invert the geometry to move from a right handed system to a left handed one.
  28717. * Returns the Mesh.
  28718. */
  28719. Mesh.prototype.toLeftHanded = function () {
  28720. if (!this._geometry) {
  28721. return this;
  28722. }
  28723. this._geometry.toLeftHanded();
  28724. return this;
  28725. };
  28726. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28727. if (!this._geometry) {
  28728. return this;
  28729. }
  28730. var engine = this.getScene().getEngine();
  28731. // Wireframe
  28732. var indexToBind;
  28733. if (this._unIndexed) {
  28734. indexToBind = null;
  28735. }
  28736. else {
  28737. switch (fillMode) {
  28738. case BABYLON.Material.PointFillMode:
  28739. indexToBind = null;
  28740. break;
  28741. case BABYLON.Material.WireFrameFillMode:
  28742. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28743. break;
  28744. default:
  28745. case BABYLON.Material.TriangleFillMode:
  28746. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28747. break;
  28748. }
  28749. }
  28750. // VBOs
  28751. this._geometry._bind(effect, indexToBind);
  28752. return this;
  28753. };
  28754. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28755. if (alternate === void 0) { alternate = false; }
  28756. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28757. return this;
  28758. }
  28759. this.onBeforeDrawObservable.notifyObservers(this);
  28760. var scene = this.getScene();
  28761. var engine = scene.getEngine();
  28762. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28763. // or triangles as points
  28764. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28765. }
  28766. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28767. // Triangles as wireframe
  28768. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28769. }
  28770. else {
  28771. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28772. }
  28773. if (scene._isAlternateRenderingEnabled && !alternate) {
  28774. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28775. if (!effect || !scene.activeCamera) {
  28776. return this;
  28777. }
  28778. scene._switchToAlternateCameraConfiguration(true);
  28779. this._effectiveMaterial.bindView(effect);
  28780. this._effectiveMaterial.bindViewProjection(effect);
  28781. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28782. this._draw(subMesh, fillMode, instancesCount, true);
  28783. engine.setViewport(scene.activeCamera.viewport);
  28784. scene._switchToAlternateCameraConfiguration(false);
  28785. this._effectiveMaterial.bindView(effect);
  28786. this._effectiveMaterial.bindViewProjection(effect);
  28787. }
  28788. return this;
  28789. };
  28790. /**
  28791. * Registers for this mesh a javascript function called just before the rendering process.
  28792. * This function is passed the current mesh.
  28793. * Return the Mesh.
  28794. */
  28795. Mesh.prototype.registerBeforeRender = function (func) {
  28796. this.onBeforeRenderObservable.add(func);
  28797. return this;
  28798. };
  28799. /**
  28800. * Disposes a previously registered javascript function called before the rendering.
  28801. * This function is passed the current mesh.
  28802. * Returns the Mesh.
  28803. */
  28804. Mesh.prototype.unregisterBeforeRender = function (func) {
  28805. this.onBeforeRenderObservable.removeCallback(func);
  28806. return this;
  28807. };
  28808. /**
  28809. * Registers for this mesh a javascript function called just after the rendering is complete.
  28810. * This function is passed the current mesh.
  28811. * Returns the Mesh.
  28812. */
  28813. Mesh.prototype.registerAfterRender = function (func) {
  28814. this.onAfterRenderObservable.add(func);
  28815. return this;
  28816. };
  28817. /**
  28818. * Disposes a previously registered javascript function called after the rendering.
  28819. * This function is passed the current mesh.
  28820. * Return the Mesh.
  28821. */
  28822. Mesh.prototype.unregisterAfterRender = function (func) {
  28823. this.onAfterRenderObservable.removeCallback(func);
  28824. return this;
  28825. };
  28826. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28827. var scene = this.getScene();
  28828. this._batchCache.mustReturn = false;
  28829. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28830. this._batchCache.visibleInstances[subMeshId] = null;
  28831. if (this._visibleInstances) {
  28832. var currentRenderId = scene.getRenderId();
  28833. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28834. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28835. var selfRenderId = this._renderId;
  28836. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28837. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28838. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28839. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28840. }
  28841. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28842. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28843. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28844. this._batchCache.mustReturn = true;
  28845. return this._batchCache;
  28846. }
  28847. if (currentRenderId !== selfRenderId) {
  28848. this._batchCache.renderSelf[subMeshId] = false;
  28849. }
  28850. }
  28851. this._renderIdForInstances[subMeshId] = currentRenderId;
  28852. }
  28853. return this._batchCache;
  28854. };
  28855. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28856. var visibleInstances = batch.visibleInstances[subMesh._id];
  28857. if (!visibleInstances) {
  28858. return this;
  28859. }
  28860. var matricesCount = visibleInstances.length + 1;
  28861. var bufferSize = matricesCount * 16 * 4;
  28862. var currentInstancesBufferSize = this._instancesBufferSize;
  28863. var instancesBuffer = this._instancesBuffer;
  28864. while (this._instancesBufferSize < bufferSize) {
  28865. this._instancesBufferSize *= 2;
  28866. }
  28867. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28868. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28869. }
  28870. var offset = 0;
  28871. var instancesCount = 0;
  28872. var world = this.getWorldMatrix();
  28873. if (batch.renderSelf[subMesh._id]) {
  28874. world.copyToArray(this._instancesData, offset);
  28875. offset += 16;
  28876. instancesCount++;
  28877. }
  28878. if (visibleInstances) {
  28879. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28880. var instance = visibleInstances[instanceIndex];
  28881. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28882. offset += 16;
  28883. instancesCount++;
  28884. }
  28885. }
  28886. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28887. if (instancesBuffer) {
  28888. instancesBuffer.dispose();
  28889. }
  28890. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28891. this._instancesBuffer = instancesBuffer;
  28892. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28893. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28894. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28895. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28896. }
  28897. else {
  28898. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28899. }
  28900. this._bind(subMesh, effect, fillMode);
  28901. this._draw(subMesh, fillMode, instancesCount);
  28902. engine.unbindInstanceAttributes();
  28903. return this;
  28904. };
  28905. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28906. var scene = this.getScene();
  28907. var engine = scene.getEngine();
  28908. if (hardwareInstancedRendering) {
  28909. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28910. }
  28911. else {
  28912. if (batch.renderSelf[subMesh._id]) {
  28913. // Draw
  28914. if (onBeforeDraw) {
  28915. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28916. }
  28917. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28918. }
  28919. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28920. if (visibleInstancesForSubMesh) {
  28921. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28922. var instance = visibleInstancesForSubMesh[instanceIndex];
  28923. // World
  28924. var world = instance.getWorldMatrix();
  28925. if (onBeforeDraw) {
  28926. onBeforeDraw(true, world, effectiveMaterial);
  28927. }
  28928. // Draw
  28929. this._draw(subMesh, fillMode);
  28930. }
  28931. }
  28932. }
  28933. return this;
  28934. };
  28935. /**
  28936. * Triggers the draw call for the mesh.
  28937. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28938. * Returns the Mesh.
  28939. */
  28940. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28941. this.checkOcclusionQuery();
  28942. if (this._isOccluded) {
  28943. return this;
  28944. }
  28945. var scene = this.getScene();
  28946. // Managing instances
  28947. var batch = this._getInstancesRenderList(subMesh._id);
  28948. if (batch.mustReturn) {
  28949. return this;
  28950. }
  28951. // Checking geometry state
  28952. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28953. return this;
  28954. }
  28955. this.onBeforeRenderObservable.notifyObservers(this);
  28956. var engine = scene.getEngine();
  28957. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28958. // Material
  28959. var material = subMesh.getMaterial();
  28960. if (!material) {
  28961. return this;
  28962. }
  28963. this._effectiveMaterial = material;
  28964. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28965. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28966. return this;
  28967. }
  28968. }
  28969. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28970. return this;
  28971. }
  28972. // Alpha mode
  28973. if (enableAlphaMode) {
  28974. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28975. }
  28976. // Outline - step 1
  28977. var savedDepthWrite = engine.getDepthWrite();
  28978. if (this.renderOutline) {
  28979. engine.setDepthWrite(false);
  28980. scene.getOutlineRenderer().render(subMesh, batch);
  28981. engine.setDepthWrite(savedDepthWrite);
  28982. }
  28983. var effect;
  28984. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28985. effect = subMesh.effect;
  28986. }
  28987. else {
  28988. effect = this._effectiveMaterial.getEffect();
  28989. }
  28990. if (!effect) {
  28991. return this;
  28992. }
  28993. var sideOrientation = this.overrideMaterialSideOrientation;
  28994. if (sideOrientation == null) {
  28995. sideOrientation = this._effectiveMaterial.sideOrientation;
  28996. if (this._getWorldMatrixDeterminant() < 0) {
  28997. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28998. }
  28999. }
  29000. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29001. if (this._effectiveMaterial.forceDepthWrite) {
  29002. engine.setDepthWrite(true);
  29003. }
  29004. // Bind
  29005. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29006. if (!hardwareInstancedRendering) {
  29007. this._bind(subMesh, effect, fillMode);
  29008. }
  29009. var world = this.getWorldMatrix();
  29010. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29011. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29012. }
  29013. else {
  29014. this._effectiveMaterial.bind(world, this);
  29015. }
  29016. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29017. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29018. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29019. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29020. }
  29021. // Draw
  29022. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29023. // Unbind
  29024. this._effectiveMaterial.unbind();
  29025. // Outline - step 2
  29026. if (this.renderOutline && savedDepthWrite) {
  29027. engine.setDepthWrite(true);
  29028. engine.setColorWrite(false);
  29029. scene.getOutlineRenderer().render(subMesh, batch);
  29030. engine.setColorWrite(true);
  29031. }
  29032. // Overlay
  29033. if (this.renderOverlay) {
  29034. var currentMode = engine.getAlphaMode();
  29035. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29036. scene.getOutlineRenderer().render(subMesh, batch, true);
  29037. engine.setAlphaMode(currentMode);
  29038. }
  29039. this.onAfterRenderObservable.notifyObservers(this);
  29040. return this;
  29041. };
  29042. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29043. if (isInstance && effectiveMaterial) {
  29044. effectiveMaterial.bindOnlyWorldMatrix(world);
  29045. }
  29046. };
  29047. /**
  29048. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29049. */
  29050. Mesh.prototype.getEmittedParticleSystems = function () {
  29051. var results = new Array();
  29052. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29053. var particleSystem = this.getScene().particleSystems[index];
  29054. if (particleSystem.emitter === this) {
  29055. results.push(particleSystem);
  29056. }
  29057. }
  29058. return results;
  29059. };
  29060. /**
  29061. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29062. */
  29063. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29064. var results = new Array();
  29065. var descendants = this.getDescendants();
  29066. descendants.push(this);
  29067. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29068. var particleSystem = this.getScene().particleSystems[index];
  29069. var emitter = particleSystem.emitter;
  29070. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29071. results.push(particleSystem);
  29072. }
  29073. }
  29074. return results;
  29075. };
  29076. Mesh.prototype._checkDelayState = function () {
  29077. var scene = this.getScene();
  29078. if (this._geometry) {
  29079. this._geometry.load(scene);
  29080. }
  29081. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29082. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29083. this._queueLoad(scene);
  29084. }
  29085. return this;
  29086. };
  29087. Mesh.prototype._queueLoad = function (scene) {
  29088. var _this = this;
  29089. scene._addPendingData(this);
  29090. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29091. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29092. if (data instanceof ArrayBuffer) {
  29093. _this._delayLoadingFunction(data, _this);
  29094. }
  29095. else {
  29096. _this._delayLoadingFunction(JSON.parse(data), _this);
  29097. }
  29098. _this.instances.forEach(function (instance) {
  29099. instance._syncSubMeshes();
  29100. });
  29101. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29102. scene._removePendingData(_this);
  29103. }, function () { }, scene.database, getBinaryData);
  29104. return this;
  29105. };
  29106. /**
  29107. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29108. */
  29109. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29110. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29111. return false;
  29112. }
  29113. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29114. return false;
  29115. }
  29116. this._checkDelayState();
  29117. return true;
  29118. };
  29119. /**
  29120. * Sets the mesh material by the material or multiMaterial `id` property.
  29121. * The material `id` is a string identifying the material or the multiMaterial.
  29122. * This method returns the Mesh.
  29123. */
  29124. Mesh.prototype.setMaterialByID = function (id) {
  29125. var materials = this.getScene().materials;
  29126. var index;
  29127. for (index = materials.length - 1; index > -1; index--) {
  29128. if (materials[index].id === id) {
  29129. this.material = materials[index];
  29130. return this;
  29131. }
  29132. }
  29133. // Multi
  29134. var multiMaterials = this.getScene().multiMaterials;
  29135. for (index = multiMaterials.length - 1; index > -1; index--) {
  29136. if (multiMaterials[index].id === id) {
  29137. this.material = multiMaterials[index];
  29138. return this;
  29139. }
  29140. }
  29141. return this;
  29142. };
  29143. /**
  29144. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29145. */
  29146. Mesh.prototype.getAnimatables = function () {
  29147. var results = new Array();
  29148. if (this.material) {
  29149. results.push(this.material);
  29150. }
  29151. if (this.skeleton) {
  29152. results.push(this.skeleton);
  29153. }
  29154. return results;
  29155. };
  29156. /**
  29157. * Modifies the mesh geometry according to the passed transformation matrix.
  29158. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29159. * The mesh normals are modified accordingly the same transformation.
  29160. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29161. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29162. * Returns the Mesh.
  29163. */
  29164. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29165. // Position
  29166. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29167. return this;
  29168. }
  29169. var submeshes = this.subMeshes.splice(0);
  29170. this._resetPointsArrayCache();
  29171. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29172. var temp = new Array();
  29173. var index;
  29174. for (index = 0; index < data.length; index += 3) {
  29175. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29176. }
  29177. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29178. // Normals
  29179. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29180. return this;
  29181. }
  29182. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29183. temp = [];
  29184. for (index = 0; index < data.length; index += 3) {
  29185. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29186. }
  29187. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29188. // flip faces?
  29189. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29190. this.flipFaces();
  29191. }
  29192. // Restore submeshes
  29193. this.releaseSubMeshes();
  29194. this.subMeshes = submeshes;
  29195. return this;
  29196. };
  29197. /**
  29198. * Modifies the mesh geometry according to its own current World Matrix.
  29199. * The mesh World Matrix is then reset.
  29200. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29201. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29202. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29203. * Returns the Mesh.
  29204. */
  29205. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29206. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29207. this.scaling.copyFromFloats(1, 1, 1);
  29208. this.position.copyFromFloats(0, 0, 0);
  29209. this.rotation.copyFromFloats(0, 0, 0);
  29210. //only if quaternion is already set
  29211. if (this.rotationQuaternion) {
  29212. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29213. }
  29214. this._worldMatrix = BABYLON.Matrix.Identity();
  29215. return this;
  29216. };
  29217. Object.defineProperty(Mesh.prototype, "_positions", {
  29218. // Cache
  29219. get: function () {
  29220. if (this._geometry) {
  29221. return this._geometry._positions;
  29222. }
  29223. return null;
  29224. },
  29225. enumerable: true,
  29226. configurable: true
  29227. });
  29228. Mesh.prototype._resetPointsArrayCache = function () {
  29229. if (this._geometry) {
  29230. this._geometry._resetPointsArrayCache();
  29231. }
  29232. return this;
  29233. };
  29234. Mesh.prototype._generatePointsArray = function () {
  29235. if (this._geometry) {
  29236. return this._geometry._generatePointsArray();
  29237. }
  29238. return false;
  29239. };
  29240. /**
  29241. * Returns a new Mesh object generated from the current mesh properties.
  29242. * This method must not get confused with createInstance().
  29243. * The parameter `name` is a string, the name given to the new mesh.
  29244. * The optional parameter `newParent` can be any Node object (default `null`).
  29245. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29246. * 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.
  29247. */
  29248. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29249. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29250. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29251. };
  29252. /**
  29253. * Releases resources associated with this mesh.
  29254. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29255. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29256. */
  29257. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29258. var _this = this;
  29259. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29260. this.morphTargetManager = null;
  29261. if (this._geometry) {
  29262. this._geometry.releaseForMesh(this, true);
  29263. }
  29264. // Sources
  29265. var meshes = this.getScene().meshes;
  29266. meshes.forEach(function (abstractMesh) {
  29267. var mesh = abstractMesh;
  29268. if (mesh._source && mesh._source === _this) {
  29269. mesh._source = null;
  29270. }
  29271. });
  29272. this._source = null;
  29273. // Instances
  29274. if (this._instancesBuffer) {
  29275. this._instancesBuffer.dispose();
  29276. this._instancesBuffer = null;
  29277. }
  29278. while (this.instances.length) {
  29279. this.instances[0].dispose();
  29280. }
  29281. // Effect layers.
  29282. var effectLayers = this.getScene().effectLayers;
  29283. for (var i = 0; i < effectLayers.length; i++) {
  29284. var effectLayer = effectLayers[i];
  29285. if (effectLayer) {
  29286. effectLayer._disposeMesh(this);
  29287. }
  29288. }
  29289. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29290. };
  29291. /**
  29292. * Modifies the mesh geometry according to a displacement map.
  29293. * 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.
  29294. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29295. * This method returns nothing.
  29296. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29297. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29298. * 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.
  29299. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29300. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29301. *
  29302. * Returns the Mesh.
  29303. */
  29304. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29305. var _this = this;
  29306. var scene = this.getScene();
  29307. var onload = function (img) {
  29308. // Getting height map data
  29309. var canvas = document.createElement("canvas");
  29310. var context = canvas.getContext("2d");
  29311. var heightMapWidth = img.width;
  29312. var heightMapHeight = img.height;
  29313. canvas.width = heightMapWidth;
  29314. canvas.height = heightMapHeight;
  29315. context.drawImage(img, 0, 0);
  29316. // Create VertexData from map data
  29317. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29318. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29319. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29320. //execute success callback, if set
  29321. if (onSuccess) {
  29322. onSuccess(_this);
  29323. }
  29324. };
  29325. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29326. return this;
  29327. };
  29328. /**
  29329. * Modifies the mesh geometry according to a displacementMap buffer.
  29330. * 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.
  29331. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29332. * This method returns nothing.
  29333. * 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.
  29334. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29335. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29336. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29337. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29338. *
  29339. * Returns the Mesh.
  29340. */
  29341. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29342. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29343. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29344. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29345. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29346. return this;
  29347. }
  29348. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29349. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29350. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29351. var position = BABYLON.Vector3.Zero();
  29352. var normal = BABYLON.Vector3.Zero();
  29353. var uv = BABYLON.Vector2.Zero();
  29354. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29355. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29356. for (var index = 0; index < positions.length; index += 3) {
  29357. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29358. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29359. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29360. // Compute height
  29361. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29362. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29363. var pos = (u + v * heightMapWidth) * 4;
  29364. var r = buffer[pos] / 255.0;
  29365. var g = buffer[pos + 1] / 255.0;
  29366. var b = buffer[pos + 2] / 255.0;
  29367. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29368. normal.normalize();
  29369. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29370. position = position.add(normal);
  29371. position.toArray(positions, index);
  29372. }
  29373. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29374. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29375. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29376. return this;
  29377. };
  29378. /**
  29379. * Modify the mesh to get a flat shading rendering.
  29380. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29381. * This method returns the Mesh.
  29382. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29383. */
  29384. Mesh.prototype.convertToFlatShadedMesh = function () {
  29385. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29386. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29387. var kinds = this.getVerticesDataKinds();
  29388. var vbs = {};
  29389. var data = {};
  29390. var newdata = {};
  29391. var updatableNormals = false;
  29392. var kindIndex;
  29393. var kind;
  29394. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29395. kind = kinds[kindIndex];
  29396. var vertexBuffer = this.getVertexBuffer(kind);
  29397. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29398. updatableNormals = vertexBuffer.isUpdatable();
  29399. kinds.splice(kindIndex, 1);
  29400. kindIndex--;
  29401. continue;
  29402. }
  29403. vbs[kind] = vertexBuffer;
  29404. data[kind] = vbs[kind].getData();
  29405. newdata[kind] = [];
  29406. }
  29407. // Save previous submeshes
  29408. var previousSubmeshes = this.subMeshes.slice(0);
  29409. var indices = this.getIndices();
  29410. var totalIndices = this.getTotalIndices();
  29411. // Generating unique vertices per face
  29412. var index;
  29413. for (index = 0; index < totalIndices; index++) {
  29414. var vertexIndex = indices[index];
  29415. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29416. kind = kinds[kindIndex];
  29417. var stride = vbs[kind].getStrideSize();
  29418. for (var offset = 0; offset < stride; offset++) {
  29419. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29420. }
  29421. }
  29422. }
  29423. // Updating faces & normal
  29424. var normals = [];
  29425. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29426. for (index = 0; index < totalIndices; index += 3) {
  29427. indices[index] = index;
  29428. indices[index + 1] = index + 1;
  29429. indices[index + 2] = index + 2;
  29430. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29431. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29432. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29433. var p1p2 = p1.subtract(p2);
  29434. var p3p2 = p3.subtract(p2);
  29435. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29436. // Store same normals for every vertex
  29437. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29438. normals.push(normal.x);
  29439. normals.push(normal.y);
  29440. normals.push(normal.z);
  29441. }
  29442. }
  29443. this.setIndices(indices);
  29444. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29445. // Updating vertex buffers
  29446. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29447. kind = kinds[kindIndex];
  29448. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29449. }
  29450. // Updating submeshes
  29451. this.releaseSubMeshes();
  29452. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29453. var previousOne = previousSubmeshes[submeshIndex];
  29454. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29455. }
  29456. this.synchronizeInstances();
  29457. return this;
  29458. };
  29459. /**
  29460. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29461. * In other words, more vertices, no more indices and a single bigger VBO.
  29462. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29463. * Returns the Mesh.
  29464. */
  29465. Mesh.prototype.convertToUnIndexedMesh = function () {
  29466. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29467. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29468. var kinds = this.getVerticesDataKinds();
  29469. var vbs = {};
  29470. var data = {};
  29471. var newdata = {};
  29472. var kindIndex;
  29473. var kind;
  29474. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29475. kind = kinds[kindIndex];
  29476. var vertexBuffer = this.getVertexBuffer(kind);
  29477. vbs[kind] = vertexBuffer;
  29478. data[kind] = vbs[kind].getData();
  29479. newdata[kind] = [];
  29480. }
  29481. // Save previous submeshes
  29482. var previousSubmeshes = this.subMeshes.slice(0);
  29483. var indices = this.getIndices();
  29484. var totalIndices = this.getTotalIndices();
  29485. // Generating unique vertices per face
  29486. var index;
  29487. for (index = 0; index < totalIndices; index++) {
  29488. var vertexIndex = indices[index];
  29489. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29490. kind = kinds[kindIndex];
  29491. var stride = vbs[kind].getStrideSize();
  29492. for (var offset = 0; offset < stride; offset++) {
  29493. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29494. }
  29495. }
  29496. }
  29497. // Updating indices
  29498. for (index = 0; index < totalIndices; index += 3) {
  29499. indices[index] = index;
  29500. indices[index + 1] = index + 1;
  29501. indices[index + 2] = index + 2;
  29502. }
  29503. this.setIndices(indices);
  29504. // Updating vertex buffers
  29505. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29506. kind = kinds[kindIndex];
  29507. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29508. }
  29509. // Updating submeshes
  29510. this.releaseSubMeshes();
  29511. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29512. var previousOne = previousSubmeshes[submeshIndex];
  29513. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29514. }
  29515. this._unIndexed = true;
  29516. this.synchronizeInstances();
  29517. return this;
  29518. };
  29519. /**
  29520. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29521. * This method returns the Mesh.
  29522. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29523. */
  29524. Mesh.prototype.flipFaces = function (flipNormals) {
  29525. if (flipNormals === void 0) { flipNormals = false; }
  29526. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29527. var i;
  29528. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29529. for (i = 0; i < vertex_data.normals.length; i++) {
  29530. vertex_data.normals[i] *= -1;
  29531. }
  29532. }
  29533. if (vertex_data.indices) {
  29534. var temp;
  29535. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29536. // reassign indices
  29537. temp = vertex_data.indices[i + 1];
  29538. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29539. vertex_data.indices[i + 2] = temp;
  29540. }
  29541. }
  29542. vertex_data.applyToMesh(this);
  29543. return this;
  29544. };
  29545. // Instances
  29546. /**
  29547. * Creates a new InstancedMesh object from the mesh model.
  29548. * An instance shares the same properties and the same material than its model.
  29549. * Only these properties of each instance can then be set individually :
  29550. * - position
  29551. * - rotation
  29552. * - rotationQuaternion
  29553. * - setPivotMatrix
  29554. * - scaling
  29555. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29556. * Warning : this method is not supported for Line mesh and LineSystem
  29557. */
  29558. Mesh.prototype.createInstance = function (name) {
  29559. return new BABYLON.InstancedMesh(name, this);
  29560. };
  29561. /**
  29562. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29563. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29564. * This method returns the Mesh.
  29565. */
  29566. Mesh.prototype.synchronizeInstances = function () {
  29567. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29568. var instance = this.instances[instanceIndex];
  29569. instance._syncSubMeshes();
  29570. }
  29571. return this;
  29572. };
  29573. /**
  29574. * Simplify the mesh according to the given array of settings.
  29575. * Function will return immediately and will simplify async. It returns the Mesh.
  29576. * @param settings a collection of simplification settings.
  29577. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29578. * @param type the type of simplification to run.
  29579. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29580. */
  29581. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29582. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29583. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29584. this.getScene().simplificationQueue.addTask({
  29585. settings: settings,
  29586. parallelProcessing: parallelProcessing,
  29587. mesh: this,
  29588. simplificationType: simplificationType,
  29589. successCallback: successCallback
  29590. });
  29591. return this;
  29592. };
  29593. /**
  29594. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29595. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29596. * This should be used together with the simplification to avoid disappearing triangles.
  29597. * Returns the Mesh.
  29598. * @param successCallback an optional success callback to be called after the optimization finished.
  29599. */
  29600. Mesh.prototype.optimizeIndices = function (successCallback) {
  29601. var _this = this;
  29602. var indices = this.getIndices();
  29603. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29604. if (!positions || !indices) {
  29605. return this;
  29606. }
  29607. var vectorPositions = new Array();
  29608. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29609. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29610. }
  29611. var dupes = new Array();
  29612. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29613. var realPos = vectorPositions.length - 1 - iteration;
  29614. var testedPosition = vectorPositions[realPos];
  29615. for (var j = 0; j < realPos; ++j) {
  29616. var againstPosition = vectorPositions[j];
  29617. if (testedPosition.equals(againstPosition)) {
  29618. dupes[realPos] = j;
  29619. break;
  29620. }
  29621. }
  29622. }, function () {
  29623. for (var i = 0; i < indices.length; ++i) {
  29624. indices[i] = dupes[indices[i]] || indices[i];
  29625. }
  29626. //indices are now reordered
  29627. var originalSubMeshes = _this.subMeshes.slice(0);
  29628. _this.setIndices(indices);
  29629. _this.subMeshes = originalSubMeshes;
  29630. if (successCallback) {
  29631. successCallback(_this);
  29632. }
  29633. });
  29634. return this;
  29635. };
  29636. Mesh.prototype.serialize = function (serializationObject) {
  29637. serializationObject.name = this.name;
  29638. serializationObject.id = this.id;
  29639. serializationObject.type = this.getClassName();
  29640. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29641. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29642. }
  29643. serializationObject.position = this.position.asArray();
  29644. if (this.rotationQuaternion) {
  29645. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29646. }
  29647. else if (this.rotation) {
  29648. serializationObject.rotation = this.rotation.asArray();
  29649. }
  29650. serializationObject.scaling = this.scaling.asArray();
  29651. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29652. serializationObject.isEnabled = this.isEnabled(false);
  29653. serializationObject.isVisible = this.isVisible;
  29654. serializationObject.infiniteDistance = this.infiniteDistance;
  29655. serializationObject.pickable = this.isPickable;
  29656. serializationObject.receiveShadows = this.receiveShadows;
  29657. serializationObject.billboardMode = this.billboardMode;
  29658. serializationObject.visibility = this.visibility;
  29659. serializationObject.checkCollisions = this.checkCollisions;
  29660. serializationObject.isBlocker = this.isBlocker;
  29661. // Parent
  29662. if (this.parent) {
  29663. serializationObject.parentId = this.parent.id;
  29664. }
  29665. // Geometry
  29666. serializationObject.isUnIndexed = this.isUnIndexed;
  29667. var geometry = this._geometry;
  29668. if (geometry) {
  29669. var geometryId = geometry.id;
  29670. serializationObject.geometryId = geometryId;
  29671. // SubMeshes
  29672. serializationObject.subMeshes = [];
  29673. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29674. var subMesh = this.subMeshes[subIndex];
  29675. serializationObject.subMeshes.push({
  29676. materialIndex: subMesh.materialIndex,
  29677. verticesStart: subMesh.verticesStart,
  29678. verticesCount: subMesh.verticesCount,
  29679. indexStart: subMesh.indexStart,
  29680. indexCount: subMesh.indexCount
  29681. });
  29682. }
  29683. }
  29684. // Material
  29685. if (this.material) {
  29686. serializationObject.materialId = this.material.id;
  29687. }
  29688. else {
  29689. this.material = null;
  29690. }
  29691. // Morph targets
  29692. if (this.morphTargetManager) {
  29693. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29694. }
  29695. // Skeleton
  29696. if (this.skeleton) {
  29697. serializationObject.skeletonId = this.skeleton.id;
  29698. }
  29699. // Physics
  29700. //TODO implement correct serialization for physics impostors.
  29701. var impostor = this.getPhysicsImpostor();
  29702. if (impostor) {
  29703. serializationObject.physicsMass = impostor.getParam("mass");
  29704. serializationObject.physicsFriction = impostor.getParam("friction");
  29705. serializationObject.physicsRestitution = impostor.getParam("mass");
  29706. serializationObject.physicsImpostor = impostor.type;
  29707. }
  29708. // Metadata
  29709. if (this.metadata) {
  29710. serializationObject.metadata = this.metadata;
  29711. }
  29712. // Instances
  29713. serializationObject.instances = [];
  29714. for (var index = 0; index < this.instances.length; index++) {
  29715. var instance = this.instances[index];
  29716. var serializationInstance = {
  29717. name: instance.name,
  29718. id: instance.id,
  29719. position: instance.position.asArray(),
  29720. scaling: instance.scaling.asArray()
  29721. };
  29722. if (instance.rotationQuaternion) {
  29723. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29724. }
  29725. else if (instance.rotation) {
  29726. serializationInstance.rotation = instance.rotation.asArray();
  29727. }
  29728. serializationObject.instances.push(serializationInstance);
  29729. // Animations
  29730. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29731. serializationInstance.ranges = instance.serializeAnimationRanges();
  29732. }
  29733. //
  29734. // Animations
  29735. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29736. serializationObject.ranges = this.serializeAnimationRanges();
  29737. // Layer mask
  29738. serializationObject.layerMask = this.layerMask;
  29739. // Alpha
  29740. serializationObject.alphaIndex = this.alphaIndex;
  29741. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29742. // Overlay
  29743. serializationObject.overlayAlpha = this.overlayAlpha;
  29744. serializationObject.overlayColor = this.overlayColor.asArray();
  29745. serializationObject.renderOverlay = this.renderOverlay;
  29746. // Fog
  29747. serializationObject.applyFog = this.applyFog;
  29748. // Action Manager
  29749. if (this.actionManager) {
  29750. serializationObject.actions = this.actionManager.serialize(this.name);
  29751. }
  29752. };
  29753. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29754. if (!this.geometry) {
  29755. return;
  29756. }
  29757. this._markSubMeshesAsAttributesDirty();
  29758. var morphTargetManager = this._morphTargetManager;
  29759. if (morphTargetManager && morphTargetManager.vertexCount) {
  29760. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29761. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29762. this.morphTargetManager = null;
  29763. return;
  29764. }
  29765. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29766. var morphTarget = morphTargetManager.getActiveTarget(index);
  29767. var positions = morphTarget.getPositions();
  29768. if (!positions) {
  29769. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29770. return;
  29771. }
  29772. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29773. var normals = morphTarget.getNormals();
  29774. if (normals) {
  29775. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29776. }
  29777. var tangents = morphTarget.getTangents();
  29778. if (tangents) {
  29779. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29780. }
  29781. }
  29782. }
  29783. else {
  29784. var index = 0;
  29785. // Positions
  29786. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29787. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29788. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29789. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29790. }
  29791. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29792. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29793. }
  29794. index++;
  29795. }
  29796. }
  29797. };
  29798. // Statics
  29799. /**
  29800. * Returns a new Mesh object parsed from the source provided.
  29801. * The parameter `parsedMesh` is the source.
  29802. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29803. */
  29804. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29805. var mesh;
  29806. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29807. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29808. }
  29809. else {
  29810. mesh = new Mesh(parsedMesh.name, scene);
  29811. }
  29812. mesh.id = parsedMesh.id;
  29813. if (BABYLON.Tags) {
  29814. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29815. }
  29816. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29817. if (parsedMesh.metadata !== undefined) {
  29818. mesh.metadata = parsedMesh.metadata;
  29819. }
  29820. if (parsedMesh.rotationQuaternion) {
  29821. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29822. }
  29823. else if (parsedMesh.rotation) {
  29824. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29825. }
  29826. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29827. if (parsedMesh.localMatrix) {
  29828. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29829. }
  29830. else if (parsedMesh.pivotMatrix) {
  29831. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29832. }
  29833. mesh.setEnabled(parsedMesh.isEnabled);
  29834. mesh.isVisible = parsedMesh.isVisible;
  29835. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29836. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29837. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29838. if (parsedMesh.applyFog !== undefined) {
  29839. mesh.applyFog = parsedMesh.applyFog;
  29840. }
  29841. if (parsedMesh.pickable !== undefined) {
  29842. mesh.isPickable = parsedMesh.pickable;
  29843. }
  29844. if (parsedMesh.alphaIndex !== undefined) {
  29845. mesh.alphaIndex = parsedMesh.alphaIndex;
  29846. }
  29847. mesh.receiveShadows = parsedMesh.receiveShadows;
  29848. mesh.billboardMode = parsedMesh.billboardMode;
  29849. if (parsedMesh.visibility !== undefined) {
  29850. mesh.visibility = parsedMesh.visibility;
  29851. }
  29852. mesh.checkCollisions = parsedMesh.checkCollisions;
  29853. if (parsedMesh.isBlocker !== undefined) {
  29854. mesh.isBlocker = parsedMesh.isBlocker;
  29855. }
  29856. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29857. // freezeWorldMatrix
  29858. if (parsedMesh.freezeWorldMatrix) {
  29859. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29860. }
  29861. // Parent
  29862. if (parsedMesh.parentId) {
  29863. mesh._waitingParentId = parsedMesh.parentId;
  29864. }
  29865. // Actions
  29866. if (parsedMesh.actions !== undefined) {
  29867. mesh._waitingActions = parsedMesh.actions;
  29868. }
  29869. // Overlay
  29870. if (parsedMesh.overlayAlpha !== undefined) {
  29871. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29872. }
  29873. if (parsedMesh.overlayColor !== undefined) {
  29874. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29875. }
  29876. if (parsedMesh.renderOverlay !== undefined) {
  29877. mesh.renderOverlay = parsedMesh.renderOverlay;
  29878. }
  29879. // Geometry
  29880. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29881. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29882. if (parsedMesh.delayLoadingFile) {
  29883. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29884. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29885. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29886. if (parsedMesh._binaryInfo) {
  29887. mesh._binaryInfo = parsedMesh._binaryInfo;
  29888. }
  29889. mesh._delayInfo = [];
  29890. if (parsedMesh.hasUVs) {
  29891. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29892. }
  29893. if (parsedMesh.hasUVs2) {
  29894. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29895. }
  29896. if (parsedMesh.hasUVs3) {
  29897. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29898. }
  29899. if (parsedMesh.hasUVs4) {
  29900. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29901. }
  29902. if (parsedMesh.hasUVs5) {
  29903. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29904. }
  29905. if (parsedMesh.hasUVs6) {
  29906. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29907. }
  29908. if (parsedMesh.hasColors) {
  29909. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29910. }
  29911. if (parsedMesh.hasMatricesIndices) {
  29912. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29913. }
  29914. if (parsedMesh.hasMatricesWeights) {
  29915. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29916. }
  29917. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29918. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29919. mesh._checkDelayState();
  29920. }
  29921. }
  29922. else {
  29923. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29924. }
  29925. // Material
  29926. if (parsedMesh.materialId) {
  29927. mesh.setMaterialByID(parsedMesh.materialId);
  29928. }
  29929. else {
  29930. mesh.material = null;
  29931. }
  29932. // Morph targets
  29933. if (parsedMesh.morphTargetManagerId > -1) {
  29934. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29935. }
  29936. // Skeleton
  29937. if (parsedMesh.skeletonId > -1) {
  29938. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29939. if (parsedMesh.numBoneInfluencers) {
  29940. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29941. }
  29942. }
  29943. // Animations
  29944. if (parsedMesh.animations) {
  29945. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29946. var parsedAnimation = parsedMesh.animations[animationIndex];
  29947. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29948. }
  29949. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29950. }
  29951. if (parsedMesh.autoAnimate) {
  29952. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29953. }
  29954. // Layer Mask
  29955. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29956. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29957. }
  29958. else {
  29959. mesh.layerMask = 0x0FFFFFFF;
  29960. }
  29961. // Physics
  29962. if (parsedMesh.physicsImpostor) {
  29963. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29964. mass: parsedMesh.physicsMass,
  29965. friction: parsedMesh.physicsFriction,
  29966. restitution: parsedMesh.physicsRestitution
  29967. }, scene);
  29968. }
  29969. // Instances
  29970. if (parsedMesh.instances) {
  29971. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29972. var parsedInstance = parsedMesh.instances[index];
  29973. var instance = mesh.createInstance(parsedInstance.name);
  29974. if (parsedInstance.id) {
  29975. instance.id = parsedInstance.id;
  29976. }
  29977. if (BABYLON.Tags) {
  29978. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29979. }
  29980. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29981. if (parsedInstance.parentId) {
  29982. instance._waitingParentId = parsedInstance.parentId;
  29983. }
  29984. if (parsedInstance.rotationQuaternion) {
  29985. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29986. }
  29987. else if (parsedInstance.rotation) {
  29988. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29989. }
  29990. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29991. instance.checkCollisions = mesh.checkCollisions;
  29992. if (parsedMesh.animations) {
  29993. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29994. parsedAnimation = parsedMesh.animations[animationIndex];
  29995. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29996. }
  29997. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29998. }
  29999. }
  30000. }
  30001. return mesh;
  30002. };
  30003. /**
  30004. * Creates a ribbon mesh.
  30005. * Please consider using the same method from the MeshBuilder class instead.
  30006. * 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.
  30007. *
  30008. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30009. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30010. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30011. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30012. * 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.
  30013. * 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.
  30014. * 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
  30015. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30016. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30018. */
  30019. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30020. if (closeArray === void 0) { closeArray = false; }
  30021. if (updatable === void 0) { updatable = false; }
  30022. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30023. pathArray: pathArray,
  30024. closeArray: closeArray,
  30025. closePath: closePath,
  30026. offset: offset,
  30027. updatable: updatable,
  30028. sideOrientation: sideOrientation,
  30029. instance: instance
  30030. }, scene);
  30031. };
  30032. /**
  30033. * Creates a plane polygonal mesh. By default, this is a disc.
  30034. * Please consider using the same method from the MeshBuilder class instead.
  30035. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30036. * 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.
  30037. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30038. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30039. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30040. */
  30041. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30042. if (scene === void 0) { scene = null; }
  30043. var options = {
  30044. radius: radius,
  30045. tessellation: tessellation,
  30046. sideOrientation: sideOrientation,
  30047. updatable: updatable
  30048. };
  30049. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30050. };
  30051. /**
  30052. * Creates a box mesh.
  30053. * Please consider using the same method from the MeshBuilder class instead.
  30054. * The parameter `size` sets the size (float) of each box side (default 1).
  30055. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30056. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30057. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30058. */
  30059. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30060. if (scene === void 0) { scene = null; }
  30061. var options = {
  30062. size: size,
  30063. sideOrientation: sideOrientation,
  30064. updatable: updatable
  30065. };
  30066. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30067. };
  30068. /**
  30069. * Creates a sphere mesh.
  30070. * Please consider using the same method from the MeshBuilder class instead.
  30071. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30072. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30074. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30076. */
  30077. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30078. var options = {
  30079. segments: segments,
  30080. diameterX: diameter,
  30081. diameterY: diameter,
  30082. diameterZ: diameter,
  30083. sideOrientation: sideOrientation,
  30084. updatable: updatable
  30085. };
  30086. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30087. };
  30088. /**
  30089. * Creates a cylinder or a cone mesh.
  30090. * Please consider using the same method from the MeshBuilder class instead.
  30091. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30092. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30093. * 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.
  30094. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30095. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30096. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30097. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30099. */
  30100. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30101. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30102. if (scene !== undefined) {
  30103. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30104. updatable = scene;
  30105. }
  30106. scene = subdivisions;
  30107. subdivisions = 1;
  30108. }
  30109. var options = {
  30110. height: height,
  30111. diameterTop: diameterTop,
  30112. diameterBottom: diameterBottom,
  30113. tessellation: tessellation,
  30114. subdivisions: subdivisions,
  30115. sideOrientation: sideOrientation,
  30116. updatable: updatable
  30117. };
  30118. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30119. };
  30120. // Torus (Code from SharpDX.org)
  30121. /**
  30122. * Creates a torus mesh.
  30123. * Please consider using the same method from the MeshBuilder class instead.
  30124. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30125. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30126. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30127. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30128. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30129. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30130. */
  30131. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30132. var options = {
  30133. diameter: diameter,
  30134. thickness: thickness,
  30135. tessellation: tessellation,
  30136. sideOrientation: sideOrientation,
  30137. updatable: updatable
  30138. };
  30139. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30140. };
  30141. /**
  30142. * Creates a torus knot mesh.
  30143. * Please consider using the same method from the MeshBuilder class instead.
  30144. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30145. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30146. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30147. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30148. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30149. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30150. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30151. */
  30152. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30153. var options = {
  30154. radius: radius,
  30155. tube: tube,
  30156. radialSegments: radialSegments,
  30157. tubularSegments: tubularSegments,
  30158. p: p,
  30159. q: q,
  30160. sideOrientation: sideOrientation,
  30161. updatable: updatable
  30162. };
  30163. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30164. };
  30165. /**
  30166. * Creates a line mesh.
  30167. * Please consider using the same method from the MeshBuilder class instead.
  30168. * 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.
  30169. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30170. * The parameter `points` is an array successive Vector3.
  30171. * 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
  30172. * When updating an instance, remember that only point positions can change, not the number of points.
  30173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30174. */
  30175. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30176. if (scene === void 0) { scene = null; }
  30177. if (updatable === void 0) { updatable = false; }
  30178. if (instance === void 0) { instance = null; }
  30179. var options = {
  30180. points: points,
  30181. updatable: updatable,
  30182. instance: instance
  30183. };
  30184. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30185. };
  30186. /**
  30187. * Creates a dashed line mesh.
  30188. * Please consider using the same method from the MeshBuilder class instead.
  30189. * 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.
  30190. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30191. * The parameter `points` is an array successive Vector3.
  30192. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30193. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30194. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30195. * 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
  30196. * When updating an instance, remember that only point positions can change, not the number of points.
  30197. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30198. */
  30199. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30200. if (scene === void 0) { scene = null; }
  30201. var options = {
  30202. points: points,
  30203. dashSize: dashSize,
  30204. gapSize: gapSize,
  30205. dashNb: dashNb,
  30206. updatable: updatable,
  30207. instance: instance
  30208. };
  30209. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30210. };
  30211. /**
  30212. * Creates a polygon mesh.
  30213. * Please consider using the same method from the MeshBuilder class instead.
  30214. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30215. * 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.
  30216. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30217. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30218. * Remember you can only change the shape positions, not their number when updating a polygon.
  30219. */
  30220. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30221. var options = {
  30222. shape: shape,
  30223. holes: holes,
  30224. updatable: updatable,
  30225. sideOrientation: sideOrientation
  30226. };
  30227. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30228. };
  30229. /**
  30230. * Creates an extruded polygon mesh, with depth in the Y direction.
  30231. * Please consider using the same method from the MeshBuilder class instead.
  30232. */
  30233. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30234. var options = {
  30235. shape: shape,
  30236. holes: holes,
  30237. depth: depth,
  30238. updatable: updatable,
  30239. sideOrientation: sideOrientation
  30240. };
  30241. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30242. };
  30243. /**
  30244. * Creates an extruded shape mesh.
  30245. * 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.
  30246. * Please consider using the same method from the MeshBuilder class instead.
  30247. *
  30248. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30249. * 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
  30250. * extruded along the Z axis.
  30251. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30252. * 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.
  30253. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30254. * 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
  30255. * 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
  30256. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30257. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30258. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30259. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30260. */
  30261. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30262. if (scene === void 0) { scene = null; }
  30263. var options = {
  30264. shape: shape,
  30265. path: path,
  30266. scale: scale,
  30267. rotation: rotation,
  30268. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30269. sideOrientation: sideOrientation,
  30270. instance: instance,
  30271. updatable: updatable
  30272. };
  30273. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30274. };
  30275. /**
  30276. * Creates an custom extruded shape mesh.
  30277. * 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.
  30278. * Please consider using the same method from the MeshBuilder class instead.
  30279. *
  30280. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30281. * 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
  30282. * extruded along the Z axis.
  30283. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30284. * 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
  30285. * and the distance of this point from the begining of the path :
  30286. * ```javascript
  30287. * var rotationFunction = function(i, distance) {
  30288. * // do things
  30289. * return rotationValue; }
  30290. * ```
  30291. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30292. * 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
  30293. * and the distance of this point from the begining of the path :
  30294. * ```javascript
  30295. * var scaleFunction = function(i, distance) {
  30296. * // do things
  30297. * return scaleValue;}
  30298. * ```
  30299. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30300. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30301. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30302. * 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
  30303. * 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
  30304. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30305. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30306. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30308. */
  30309. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30310. var options = {
  30311. shape: shape,
  30312. path: path,
  30313. scaleFunction: scaleFunction,
  30314. rotationFunction: rotationFunction,
  30315. ribbonCloseArray: ribbonCloseArray,
  30316. ribbonClosePath: ribbonClosePath,
  30317. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30318. sideOrientation: sideOrientation,
  30319. instance: instance,
  30320. updatable: updatable
  30321. };
  30322. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30323. };
  30324. /**
  30325. * Creates lathe mesh.
  30326. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30327. * Please consider using the same method from the MeshBuilder class instead.
  30328. * 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
  30329. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30330. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30331. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30332. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30333. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30334. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30335. */
  30336. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30337. var options = {
  30338. shape: shape,
  30339. radius: radius,
  30340. tessellation: tessellation,
  30341. sideOrientation: sideOrientation,
  30342. updatable: updatable
  30343. };
  30344. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30345. };
  30346. /**
  30347. * Creates a plane mesh.
  30348. * Please consider using the same method from the MeshBuilder class instead.
  30349. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30350. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30351. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30352. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30353. */
  30354. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30355. var options = {
  30356. size: size,
  30357. width: size,
  30358. height: size,
  30359. sideOrientation: sideOrientation,
  30360. updatable: updatable
  30361. };
  30362. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30363. };
  30364. /**
  30365. * Creates a ground mesh.
  30366. * Please consider using the same method from the MeshBuilder class instead.
  30367. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30368. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30369. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30370. */
  30371. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30372. var options = {
  30373. width: width,
  30374. height: height,
  30375. subdivisions: subdivisions,
  30376. updatable: updatable
  30377. };
  30378. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30379. };
  30380. /**
  30381. * Creates a tiled ground mesh.
  30382. * Please consider using the same method from the MeshBuilder class instead.
  30383. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30384. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30385. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30386. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30387. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30388. * numbers of subdivisions on the ground width and height of each tile.
  30389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30390. */
  30391. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30392. var options = {
  30393. xmin: xmin,
  30394. zmin: zmin,
  30395. xmax: xmax,
  30396. zmax: zmax,
  30397. subdivisions: subdivisions,
  30398. precision: precision,
  30399. updatable: updatable
  30400. };
  30401. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30402. };
  30403. /**
  30404. * Creates a ground mesh from a height map.
  30405. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30406. * Please consider using the same method from the MeshBuilder class instead.
  30407. * The parameter `url` sets the URL of the height map image resource.
  30408. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30409. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30410. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30411. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30412. * 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).
  30413. * This function is passed the newly built mesh :
  30414. * ```javascript
  30415. * function(mesh) { // do things
  30416. * return; }
  30417. * ```
  30418. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30419. */
  30420. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30421. var options = {
  30422. width: width,
  30423. height: height,
  30424. subdivisions: subdivisions,
  30425. minHeight: minHeight,
  30426. maxHeight: maxHeight,
  30427. updatable: updatable,
  30428. onReady: onReady
  30429. };
  30430. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30431. };
  30432. /**
  30433. * Creates a tube mesh.
  30434. * 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.
  30435. * Please consider using the same method from the MeshBuilder class instead.
  30436. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30437. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30438. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30439. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30440. * 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.
  30441. * It must return a radius value (positive float) :
  30442. * ```javascript
  30443. * var radiusFunction = function(i, distance) {
  30444. * // do things
  30445. * return radius; }
  30446. * ```
  30447. * 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
  30448. * 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
  30449. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30450. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30452. */
  30453. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30454. var options = {
  30455. path: path,
  30456. radius: radius,
  30457. tessellation: tessellation,
  30458. radiusFunction: radiusFunction,
  30459. arc: 1,
  30460. cap: cap,
  30461. updatable: updatable,
  30462. sideOrientation: sideOrientation,
  30463. instance: instance
  30464. };
  30465. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30466. };
  30467. /**
  30468. * Creates a polyhedron mesh.
  30469. * Please consider using the same method from the MeshBuilder class instead.
  30470. * 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
  30471. * to choose the wanted type.
  30472. * The parameter `size` (positive float, default 1) sets the polygon size.
  30473. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30474. * 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`.
  30475. * 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
  30476. * 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)`).
  30477. * 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
  30478. * 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.
  30479. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30480. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30482. */
  30483. Mesh.CreatePolyhedron = function (name, options, scene) {
  30484. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30485. };
  30486. /**
  30487. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30488. * Please consider using the same method from the MeshBuilder class instead.
  30489. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30490. * 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`).
  30491. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30492. * 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.
  30493. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30494. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30496. */
  30497. Mesh.CreateIcoSphere = function (name, options, scene) {
  30498. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30499. };
  30500. /**
  30501. * Creates a decal mesh.
  30502. * Please consider using the same method from the MeshBuilder class instead.
  30503. * 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.
  30504. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30505. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30506. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30507. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30508. */
  30509. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30510. var options = {
  30511. position: position,
  30512. normal: normal,
  30513. size: size,
  30514. angle: angle
  30515. };
  30516. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30517. };
  30518. // Skeletons
  30519. /**
  30520. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30521. */
  30522. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30523. if (!this._sourcePositions) {
  30524. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30525. if (!source) {
  30526. return this._sourcePositions;
  30527. }
  30528. this._sourcePositions = new Float32Array(source);
  30529. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30530. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30531. }
  30532. }
  30533. return this._sourcePositions;
  30534. };
  30535. /**
  30536. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30537. */
  30538. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30539. if (!this._sourceNormals) {
  30540. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30541. if (!source) {
  30542. return this._sourceNormals;
  30543. }
  30544. this._sourceNormals = new Float32Array(source);
  30545. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30546. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30547. }
  30548. }
  30549. return this._sourceNormals;
  30550. };
  30551. /**
  30552. * Updates the vertex buffer by applying transformation from the bones.
  30553. * Returns the Mesh.
  30554. *
  30555. * @param {skeleton} skeleton to apply
  30556. */
  30557. Mesh.prototype.applySkeleton = function (skeleton) {
  30558. if (!this.geometry) {
  30559. return this;
  30560. }
  30561. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30562. return this;
  30563. }
  30564. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30565. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30566. return this;
  30567. }
  30568. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30569. return this;
  30570. }
  30571. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30572. return this;
  30573. }
  30574. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30575. return this;
  30576. }
  30577. if (!this._sourcePositions) {
  30578. var submeshes = this.subMeshes.slice();
  30579. this.setPositionsForCPUSkinning();
  30580. this.subMeshes = submeshes;
  30581. }
  30582. if (!this._sourceNormals) {
  30583. this.setNormalsForCPUSkinning();
  30584. }
  30585. // positionsData checks for not being Float32Array will only pass at most once
  30586. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30587. if (!positionsData) {
  30588. return this;
  30589. }
  30590. if (!(positionsData instanceof Float32Array)) {
  30591. positionsData = new Float32Array(positionsData);
  30592. }
  30593. // normalsData checks for not being Float32Array will only pass at most once
  30594. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30595. if (!normalsData) {
  30596. return this;
  30597. }
  30598. if (!(normalsData instanceof Float32Array)) {
  30599. normalsData = new Float32Array(normalsData);
  30600. }
  30601. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30602. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30603. if (!matricesWeightsData || !matricesIndicesData) {
  30604. return this;
  30605. }
  30606. var needExtras = this.numBoneInfluencers > 4;
  30607. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30608. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30609. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30610. var tempVector3 = BABYLON.Vector3.Zero();
  30611. var finalMatrix = new BABYLON.Matrix();
  30612. var tempMatrix = new BABYLON.Matrix();
  30613. var matWeightIdx = 0;
  30614. var inf;
  30615. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30616. var weight;
  30617. for (inf = 0; inf < 4; inf++) {
  30618. weight = matricesWeightsData[matWeightIdx + inf];
  30619. if (weight > 0) {
  30620. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30621. finalMatrix.addToSelf(tempMatrix);
  30622. }
  30623. else
  30624. break;
  30625. }
  30626. if (needExtras) {
  30627. for (inf = 0; inf < 4; inf++) {
  30628. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30629. if (weight > 0) {
  30630. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30631. finalMatrix.addToSelf(tempMatrix);
  30632. }
  30633. else
  30634. break;
  30635. }
  30636. }
  30637. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30638. tempVector3.toArray(positionsData, index);
  30639. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30640. tempVector3.toArray(normalsData, index);
  30641. finalMatrix.reset();
  30642. }
  30643. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30644. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30645. return this;
  30646. };
  30647. // Tools
  30648. /**
  30649. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30650. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30651. */
  30652. Mesh.MinMax = function (meshes) {
  30653. var minVector = null;
  30654. var maxVector = null;
  30655. meshes.forEach(function (mesh, index, array) {
  30656. var boundingInfo = mesh.getBoundingInfo();
  30657. var boundingBox = boundingInfo.boundingBox;
  30658. if (!minVector || !maxVector) {
  30659. minVector = boundingBox.minimumWorld;
  30660. maxVector = boundingBox.maximumWorld;
  30661. }
  30662. else {
  30663. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30664. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30665. }
  30666. });
  30667. if (!minVector || !maxVector) {
  30668. return {
  30669. min: BABYLON.Vector3.Zero(),
  30670. max: BABYLON.Vector3.Zero()
  30671. };
  30672. }
  30673. return {
  30674. min: minVector,
  30675. max: maxVector
  30676. };
  30677. };
  30678. /**
  30679. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30680. */
  30681. Mesh.Center = function (meshesOrMinMaxVector) {
  30682. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30683. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30684. };
  30685. /**
  30686. * Merge the array of meshes into a single mesh for performance reasons.
  30687. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30688. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30689. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30690. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30691. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30692. */
  30693. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30694. if (disposeSource === void 0) { disposeSource = true; }
  30695. var index;
  30696. if (!allow32BitsIndices) {
  30697. var totalVertices = 0;
  30698. // Counting vertices
  30699. for (index = 0; index < meshes.length; index++) {
  30700. if (meshes[index]) {
  30701. totalVertices += meshes[index].getTotalVertices();
  30702. if (totalVertices > 65536) {
  30703. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30704. return null;
  30705. }
  30706. }
  30707. }
  30708. }
  30709. // Merge
  30710. var vertexData = null;
  30711. var otherVertexData;
  30712. var indiceArray = new Array();
  30713. var source = null;
  30714. for (index = 0; index < meshes.length; index++) {
  30715. if (meshes[index]) {
  30716. meshes[index].computeWorldMatrix(true);
  30717. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30718. otherVertexData.transform(meshes[index].getWorldMatrix());
  30719. if (vertexData) {
  30720. vertexData.merge(otherVertexData);
  30721. }
  30722. else {
  30723. vertexData = otherVertexData;
  30724. source = meshes[index];
  30725. }
  30726. if (subdivideWithSubMeshes) {
  30727. indiceArray.push(meshes[index].getTotalIndices());
  30728. }
  30729. }
  30730. }
  30731. source = source;
  30732. if (!meshSubclass) {
  30733. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30734. }
  30735. vertexData.applyToMesh(meshSubclass);
  30736. // Setting properties
  30737. meshSubclass.material = source.material;
  30738. meshSubclass.checkCollisions = source.checkCollisions;
  30739. // Cleaning
  30740. if (disposeSource) {
  30741. for (index = 0; index < meshes.length; index++) {
  30742. if (meshes[index]) {
  30743. meshes[index].dispose();
  30744. }
  30745. }
  30746. }
  30747. // Subdivide
  30748. if (subdivideWithSubMeshes) {
  30749. //-- Suppresions du submesh global
  30750. meshSubclass.releaseSubMeshes();
  30751. index = 0;
  30752. var offset = 0;
  30753. //-- aplique la subdivision en fonction du tableau d'indices
  30754. while (index < indiceArray.length) {
  30755. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30756. offset += indiceArray[index];
  30757. index++;
  30758. }
  30759. }
  30760. return meshSubclass;
  30761. };
  30762. // Consts
  30763. Mesh._FRONTSIDE = 0;
  30764. Mesh._BACKSIDE = 1;
  30765. Mesh._DOUBLESIDE = 2;
  30766. Mesh._DEFAULTSIDE = 0;
  30767. Mesh._NO_CAP = 0;
  30768. Mesh._CAP_START = 1;
  30769. Mesh._CAP_END = 2;
  30770. Mesh._CAP_ALL = 3;
  30771. return Mesh;
  30772. }(BABYLON.AbstractMesh));
  30773. BABYLON.Mesh = Mesh;
  30774. })(BABYLON || (BABYLON = {}));
  30775. //# sourceMappingURL=babylon.mesh.js.map
  30776. "use strict";
  30777. var BABYLON;
  30778. (function (BABYLON) {
  30779. var BaseSubMesh = /** @class */ (function () {
  30780. function BaseSubMesh() {
  30781. }
  30782. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30783. get: function () {
  30784. return this._materialEffect;
  30785. },
  30786. enumerable: true,
  30787. configurable: true
  30788. });
  30789. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30790. if (defines === void 0) { defines = null; }
  30791. if (this._materialEffect === effect) {
  30792. if (!effect) {
  30793. this._materialDefines = null;
  30794. }
  30795. return;
  30796. }
  30797. this._materialDefines = defines;
  30798. this._materialEffect = effect;
  30799. };
  30800. return BaseSubMesh;
  30801. }());
  30802. BABYLON.BaseSubMesh = BaseSubMesh;
  30803. var SubMesh = /** @class */ (function (_super) {
  30804. __extends(SubMesh, _super);
  30805. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30806. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30807. var _this = _super.call(this) || this;
  30808. _this.materialIndex = materialIndex;
  30809. _this.verticesStart = verticesStart;
  30810. _this.verticesCount = verticesCount;
  30811. _this.indexStart = indexStart;
  30812. _this.indexCount = indexCount;
  30813. _this._renderId = 0;
  30814. _this._mesh = mesh;
  30815. _this._renderingMesh = renderingMesh || mesh;
  30816. mesh.subMeshes.push(_this);
  30817. _this._trianglePlanes = [];
  30818. _this._id = mesh.subMeshes.length - 1;
  30819. if (createBoundingBox) {
  30820. _this.refreshBoundingInfo();
  30821. mesh.computeWorldMatrix(true);
  30822. }
  30823. return _this;
  30824. }
  30825. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30826. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30827. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30828. };
  30829. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30830. get: function () {
  30831. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30832. },
  30833. enumerable: true,
  30834. configurable: true
  30835. });
  30836. /**
  30837. * Returns the submesh BoudingInfo object.
  30838. */
  30839. SubMesh.prototype.getBoundingInfo = function () {
  30840. if (this.IsGlobal) {
  30841. return this._mesh.getBoundingInfo();
  30842. }
  30843. return this._boundingInfo;
  30844. };
  30845. /**
  30846. * Sets the submesh BoundingInfo.
  30847. * Return the SubMesh.
  30848. */
  30849. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30850. this._boundingInfo = boundingInfo;
  30851. return this;
  30852. };
  30853. /**
  30854. * Returns the mesh of the current submesh.
  30855. */
  30856. SubMesh.prototype.getMesh = function () {
  30857. return this._mesh;
  30858. };
  30859. /**
  30860. * Returns the rendering mesh of the submesh.
  30861. */
  30862. SubMesh.prototype.getRenderingMesh = function () {
  30863. return this._renderingMesh;
  30864. };
  30865. /**
  30866. * Returns the submesh material.
  30867. */
  30868. SubMesh.prototype.getMaterial = function () {
  30869. var rootMaterial = this._renderingMesh.material;
  30870. if (rootMaterial === null || rootMaterial === undefined) {
  30871. return this._mesh.getScene().defaultMaterial;
  30872. }
  30873. else if (rootMaterial.getSubMaterial) {
  30874. var multiMaterial = rootMaterial;
  30875. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30876. if (this._currentMaterial !== effectiveMaterial) {
  30877. this._currentMaterial = effectiveMaterial;
  30878. this._materialDefines = null;
  30879. }
  30880. return effectiveMaterial;
  30881. }
  30882. return rootMaterial;
  30883. };
  30884. // Methods
  30885. /**
  30886. * Sets a new updated BoundingInfo object to the submesh.
  30887. * Returns the SubMesh.
  30888. */
  30889. SubMesh.prototype.refreshBoundingInfo = function () {
  30890. this._lastColliderWorldVertices = null;
  30891. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30892. return this;
  30893. }
  30894. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30895. if (!data) {
  30896. this._boundingInfo = this._mesh.getBoundingInfo();
  30897. return this;
  30898. }
  30899. var indices = this._renderingMesh.getIndices();
  30900. var extend;
  30901. //is this the only submesh?
  30902. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30903. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30904. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30905. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30906. }
  30907. else {
  30908. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30909. }
  30910. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30911. return this;
  30912. };
  30913. SubMesh.prototype._checkCollision = function (collider) {
  30914. var boundingInfo = this.getBoundingInfo();
  30915. return boundingInfo._checkCollision(collider);
  30916. };
  30917. /**
  30918. * Updates the submesh BoundingInfo.
  30919. * Returns the Submesh.
  30920. */
  30921. SubMesh.prototype.updateBoundingInfo = function (world) {
  30922. var boundingInfo = this.getBoundingInfo();
  30923. if (!boundingInfo) {
  30924. this.refreshBoundingInfo();
  30925. boundingInfo = this.getBoundingInfo();
  30926. }
  30927. boundingInfo.update(world);
  30928. return this;
  30929. };
  30930. /**
  30931. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30932. * Boolean returned.
  30933. */
  30934. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30935. var boundingInfo = this.getBoundingInfo();
  30936. if (!boundingInfo) {
  30937. return false;
  30938. }
  30939. return boundingInfo.isInFrustum(frustumPlanes);
  30940. };
  30941. /**
  30942. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30943. * Boolean returned.
  30944. */
  30945. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30946. var boundingInfo = this.getBoundingInfo();
  30947. if (!boundingInfo) {
  30948. return false;
  30949. }
  30950. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30951. };
  30952. /**
  30953. * Renders the submesh.
  30954. * Returns it.
  30955. */
  30956. SubMesh.prototype.render = function (enableAlphaMode) {
  30957. this._renderingMesh.render(this, enableAlphaMode);
  30958. return this;
  30959. };
  30960. /**
  30961. * Returns a new Index Buffer.
  30962. * Type returned : WebGLBuffer.
  30963. */
  30964. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30965. if (!this._linesIndexBuffer) {
  30966. var linesIndices = [];
  30967. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30968. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30969. }
  30970. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30971. this.linesIndexCount = linesIndices.length;
  30972. }
  30973. return this._linesIndexBuffer;
  30974. };
  30975. /**
  30976. * True is the passed Ray intersects the submesh bounding box.
  30977. * Boolean returned.
  30978. */
  30979. SubMesh.prototype.canIntersects = function (ray) {
  30980. var boundingInfo = this.getBoundingInfo();
  30981. if (!boundingInfo) {
  30982. return false;
  30983. }
  30984. return ray.intersectsBox(boundingInfo.boundingBox);
  30985. };
  30986. /**
  30987. * Returns an object IntersectionInfo.
  30988. */
  30989. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30990. var intersectInfo = null;
  30991. var material = this.getMaterial();
  30992. if (!material) {
  30993. return null;
  30994. }
  30995. switch (material.fillMode) {
  30996. case BABYLON.Material.PointListDrawMode:
  30997. case BABYLON.Material.LineListDrawMode:
  30998. case BABYLON.Material.LineLoopDrawMode:
  30999. case BABYLON.Material.LineStripDrawMode:
  31000. case BABYLON.Material.TriangleFanDrawMode:
  31001. case BABYLON.Material.TriangleStripDrawMode:
  31002. return null;
  31003. }
  31004. // LineMesh first as it's also a Mesh...
  31005. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31006. var lineMesh = this._mesh;
  31007. // Line test
  31008. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31009. var p0 = positions[indices[index]];
  31010. var p1 = positions[indices[index + 1]];
  31011. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31012. if (length < 0) {
  31013. continue;
  31014. }
  31015. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31016. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31017. if (fastCheck) {
  31018. break;
  31019. }
  31020. }
  31021. }
  31022. }
  31023. else {
  31024. // Triangles test
  31025. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31026. var p0 = positions[indices[index]];
  31027. var p1 = positions[indices[index + 1]];
  31028. var p2 = positions[indices[index + 2]];
  31029. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31030. if (currentIntersectInfo) {
  31031. if (currentIntersectInfo.distance < 0) {
  31032. continue;
  31033. }
  31034. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31035. intersectInfo = currentIntersectInfo;
  31036. intersectInfo.faceId = index / 3;
  31037. if (fastCheck) {
  31038. break;
  31039. }
  31040. }
  31041. }
  31042. }
  31043. }
  31044. return intersectInfo;
  31045. };
  31046. SubMesh.prototype._rebuild = function () {
  31047. if (this._linesIndexBuffer) {
  31048. this._linesIndexBuffer = null;
  31049. }
  31050. };
  31051. // Clone
  31052. /**
  31053. * Creates a new Submesh from the passed Mesh.
  31054. */
  31055. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31056. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31057. if (!this.IsGlobal) {
  31058. var boundingInfo = this.getBoundingInfo();
  31059. if (!boundingInfo) {
  31060. return result;
  31061. }
  31062. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31063. }
  31064. return result;
  31065. };
  31066. // Dispose
  31067. /**
  31068. * Disposes the Submesh.
  31069. * Returns nothing.
  31070. */
  31071. SubMesh.prototype.dispose = function () {
  31072. if (this._linesIndexBuffer) {
  31073. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31074. this._linesIndexBuffer = null;
  31075. }
  31076. // Remove from mesh
  31077. var index = this._mesh.subMeshes.indexOf(this);
  31078. this._mesh.subMeshes.splice(index, 1);
  31079. };
  31080. // Statics
  31081. /**
  31082. * Creates a new Submesh from the passed parameters :
  31083. * - materialIndex (integer) : the index of the main mesh material.
  31084. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31085. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31086. * - mesh (Mesh) : the main mesh to create the submesh from.
  31087. * - renderingMesh (optional Mesh) : rendering mesh.
  31088. */
  31089. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31090. var minVertexIndex = Number.MAX_VALUE;
  31091. var maxVertexIndex = -Number.MAX_VALUE;
  31092. renderingMesh = (renderingMesh || mesh);
  31093. var indices = renderingMesh.getIndices();
  31094. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31095. var vertexIndex = indices[index];
  31096. if (vertexIndex < minVertexIndex)
  31097. minVertexIndex = vertexIndex;
  31098. if (vertexIndex > maxVertexIndex)
  31099. maxVertexIndex = vertexIndex;
  31100. }
  31101. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31102. };
  31103. return SubMesh;
  31104. }(BaseSubMesh));
  31105. BABYLON.SubMesh = SubMesh;
  31106. })(BABYLON || (BABYLON = {}));
  31107. //# sourceMappingURL=babylon.subMesh.js.map
  31108. "use strict";
  31109. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31110. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31111. s = arguments[i];
  31112. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31113. t[p] = s[p];
  31114. }
  31115. return t;
  31116. };
  31117. var BABYLON;
  31118. (function (BABYLON) {
  31119. /**
  31120. * Manages the defines for the Material.
  31121. */
  31122. var MaterialDefines = /** @class */ (function () {
  31123. function MaterialDefines() {
  31124. this._isDirty = true;
  31125. this._areLightsDirty = true;
  31126. this._areAttributesDirty = true;
  31127. this._areTexturesDirty = true;
  31128. this._areFresnelDirty = true;
  31129. this._areMiscDirty = true;
  31130. this._areImageProcessingDirty = true;
  31131. this._normals = false;
  31132. this._uvs = false;
  31133. this._needNormals = false;
  31134. this._needUVs = false;
  31135. }
  31136. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31137. /**
  31138. * Specifies if the material needs to be re-calculated.
  31139. */
  31140. get: function () {
  31141. return this._isDirty;
  31142. },
  31143. enumerable: true,
  31144. configurable: true
  31145. });
  31146. /**
  31147. * Marks the material to indicate that it has been re-calculated.
  31148. */
  31149. MaterialDefines.prototype.markAsProcessed = function () {
  31150. this._isDirty = false;
  31151. this._areAttributesDirty = false;
  31152. this._areTexturesDirty = false;
  31153. this._areFresnelDirty = false;
  31154. this._areLightsDirty = false;
  31155. this._areMiscDirty = false;
  31156. this._areImageProcessingDirty = false;
  31157. };
  31158. /**
  31159. * Marks the material to indicate that it needs to be re-calculated.
  31160. */
  31161. MaterialDefines.prototype.markAsUnprocessed = function () {
  31162. this._isDirty = true;
  31163. };
  31164. /**
  31165. * Marks the material to indicate all of its defines need to be re-calculated.
  31166. */
  31167. MaterialDefines.prototype.markAllAsDirty = function () {
  31168. this._areTexturesDirty = true;
  31169. this._areAttributesDirty = true;
  31170. this._areLightsDirty = true;
  31171. this._areFresnelDirty = true;
  31172. this._areMiscDirty = true;
  31173. this._areImageProcessingDirty = true;
  31174. this._isDirty = true;
  31175. };
  31176. /**
  31177. * Marks the material to indicate that image processing needs to be re-calculated.
  31178. */
  31179. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31180. this._areImageProcessingDirty = true;
  31181. this._isDirty = true;
  31182. };
  31183. /**
  31184. * Marks the material to indicate the lights need to be re-calculated.
  31185. */
  31186. MaterialDefines.prototype.markAsLightDirty = function () {
  31187. this._areLightsDirty = true;
  31188. this._isDirty = true;
  31189. };
  31190. /**
  31191. * Marks the attribute state as changed.
  31192. */
  31193. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31194. this._areAttributesDirty = true;
  31195. this._isDirty = true;
  31196. };
  31197. /**
  31198. * Marks the texture state as changed.
  31199. */
  31200. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31201. this._areTexturesDirty = true;
  31202. this._isDirty = true;
  31203. };
  31204. /**
  31205. * Marks the fresnel state as changed.
  31206. */
  31207. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31208. this._areFresnelDirty = true;
  31209. this._isDirty = true;
  31210. };
  31211. /**
  31212. * Marks the misc state as changed.
  31213. */
  31214. MaterialDefines.prototype.markAsMiscDirty = function () {
  31215. this._areMiscDirty = true;
  31216. this._isDirty = true;
  31217. };
  31218. /**
  31219. * Rebuilds the material defines.
  31220. */
  31221. MaterialDefines.prototype.rebuild = function () {
  31222. if (this._keys) {
  31223. delete this._keys;
  31224. }
  31225. this._keys = [];
  31226. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31227. var key = _a[_i];
  31228. if (key[0] === "_") {
  31229. continue;
  31230. }
  31231. this._keys.push(key);
  31232. }
  31233. };
  31234. /**
  31235. * Specifies if two material defines are equal.
  31236. * @param other - A material define instance to compare to.
  31237. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31238. */
  31239. MaterialDefines.prototype.isEqual = function (other) {
  31240. if (this._keys.length !== other._keys.length) {
  31241. return false;
  31242. }
  31243. for (var index = 0; index < this._keys.length; index++) {
  31244. var prop = this._keys[index];
  31245. if (this[prop] !== other[prop]) {
  31246. return false;
  31247. }
  31248. }
  31249. return true;
  31250. };
  31251. /**
  31252. * Clones this instance's defines to another instance.
  31253. * @param other - material defines to clone values to.
  31254. */
  31255. MaterialDefines.prototype.cloneTo = function (other) {
  31256. if (this._keys.length !== other._keys.length) {
  31257. other._keys = this._keys.slice(0);
  31258. }
  31259. for (var index = 0; index < this._keys.length; index++) {
  31260. var prop = this._keys[index];
  31261. other[prop] = this[prop];
  31262. }
  31263. };
  31264. /**
  31265. * Resets the material define values.
  31266. */
  31267. MaterialDefines.prototype.reset = function () {
  31268. for (var index = 0; index < this._keys.length; index++) {
  31269. var prop = this._keys[index];
  31270. var type = typeof this[prop];
  31271. switch (type) {
  31272. case "number":
  31273. this[prop] = 0;
  31274. break;
  31275. case "string":
  31276. this[prop] = "";
  31277. break;
  31278. default:
  31279. this[prop] = false;
  31280. break;
  31281. }
  31282. }
  31283. };
  31284. /**
  31285. * Converts the material define values to a string.
  31286. * @returns - String of material define information.
  31287. */
  31288. MaterialDefines.prototype.toString = function () {
  31289. var result = "";
  31290. for (var index = 0; index < this._keys.length; index++) {
  31291. var prop = this._keys[index];
  31292. var value = this[prop];
  31293. var type = typeof value;
  31294. switch (type) {
  31295. case "number":
  31296. case "string":
  31297. result += "#define " + prop + " " + value + "\n";
  31298. break;
  31299. default:
  31300. if (value) {
  31301. result += "#define " + prop + "\n";
  31302. }
  31303. break;
  31304. }
  31305. }
  31306. return result;
  31307. };
  31308. return MaterialDefines;
  31309. }());
  31310. BABYLON.MaterialDefines = MaterialDefines;
  31311. /**
  31312. * This offers the main features of a material in BJS.
  31313. */
  31314. var Material = /** @class */ (function () {
  31315. /**
  31316. * Creates a material instance.
  31317. * @param name - The name of the material.
  31318. * @param scene - The BJS scene to reference.
  31319. * @param doNotAdd - Specifies if the material should be added to the scene.
  31320. */
  31321. function Material(name, scene, doNotAdd) {
  31322. /**
  31323. * Specifies if the ready state should be checked on each call.
  31324. */
  31325. this.checkReadyOnEveryCall = false;
  31326. /**
  31327. * Specifies if the ready state should be checked once.
  31328. */
  31329. this.checkReadyOnlyOnce = false;
  31330. /**
  31331. * The state of the material.
  31332. */
  31333. this.state = "";
  31334. /**
  31335. * The alpha value of the material.
  31336. */
  31337. this._alpha = 1.0;
  31338. /**
  31339. * Specifies if back face culling is enabled.
  31340. */
  31341. this._backFaceCulling = true;
  31342. /**
  31343. * Specifies if the material should be serialized.
  31344. */
  31345. this.doNotSerialize = false;
  31346. /**
  31347. * Specifies if the effect should be stored on sub meshes.
  31348. */
  31349. this.storeEffectOnSubMeshes = false;
  31350. /**
  31351. * An event triggered when the material is disposed.
  31352. * @type {BABYLON.Observable}
  31353. */
  31354. this.onDisposeObservable = new BABYLON.Observable();
  31355. /**
  31356. * An event triggered when the material is bound.
  31357. * @type {BABYLON.Observable}
  31358. */
  31359. this.onBindObservable = new BABYLON.Observable();
  31360. /**
  31361. * An event triggered when the material is unbound.
  31362. * @type {BABYLON.Observable}
  31363. */
  31364. this.onUnBindObservable = new BABYLON.Observable();
  31365. /**
  31366. * Stores the value of the alpha mode.
  31367. */
  31368. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31369. /**
  31370. * Stores the state of the need depth pre-pass value.
  31371. */
  31372. this._needDepthPrePass = false;
  31373. /**
  31374. * Specifies if depth writing should be disabled.
  31375. */
  31376. this.disableDepthWrite = false;
  31377. /**
  31378. * Specifies if depth writing should be forced.
  31379. */
  31380. this.forceDepthWrite = false;
  31381. /**
  31382. * Specifies if there should be a separate pass for culling.
  31383. */
  31384. this.separateCullingPass = false;
  31385. /**
  31386. * Stores the state specifing if fog should be enabled.
  31387. */
  31388. this._fogEnabled = true;
  31389. /**
  31390. * Stores the size of points.
  31391. */
  31392. this.pointSize = 1.0;
  31393. /**
  31394. * Stores the z offset value.
  31395. */
  31396. this.zOffset = 0;
  31397. /**
  31398. * Specifies if the material was previously ready.
  31399. */
  31400. this._wasPreviouslyReady = false;
  31401. /**
  31402. * Stores the fill mode state.
  31403. */
  31404. this._fillMode = Material.TriangleFillMode;
  31405. this.name = name;
  31406. this.id = name || BABYLON.Tools.RandomId();
  31407. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31408. if (this._scene.useRightHandedSystem) {
  31409. this.sideOrientation = Material.ClockWiseSideOrientation;
  31410. }
  31411. else {
  31412. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31413. }
  31414. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31415. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31416. if (!doNotAdd) {
  31417. this._scene.materials.push(this);
  31418. }
  31419. }
  31420. Object.defineProperty(Material, "TriangleFillMode", {
  31421. /**
  31422. * Returns the triangle fill mode.
  31423. */
  31424. get: function () {
  31425. return Material._TriangleFillMode;
  31426. },
  31427. enumerable: true,
  31428. configurable: true
  31429. });
  31430. Object.defineProperty(Material, "WireFrameFillMode", {
  31431. /**
  31432. * Returns the wireframe mode.
  31433. */
  31434. get: function () {
  31435. return Material._WireFrameFillMode;
  31436. },
  31437. enumerable: true,
  31438. configurable: true
  31439. });
  31440. Object.defineProperty(Material, "PointFillMode", {
  31441. /**
  31442. * Returns the point fill mode.
  31443. */
  31444. get: function () {
  31445. return Material._PointFillMode;
  31446. },
  31447. enumerable: true,
  31448. configurable: true
  31449. });
  31450. Object.defineProperty(Material, "PointListDrawMode", {
  31451. /**
  31452. * Returns the point list draw mode.
  31453. */
  31454. get: function () {
  31455. return Material._PointListDrawMode;
  31456. },
  31457. enumerable: true,
  31458. configurable: true
  31459. });
  31460. Object.defineProperty(Material, "LineListDrawMode", {
  31461. /**
  31462. * Returns the line list draw mode.
  31463. */
  31464. get: function () {
  31465. return Material._LineListDrawMode;
  31466. },
  31467. enumerable: true,
  31468. configurable: true
  31469. });
  31470. Object.defineProperty(Material, "LineLoopDrawMode", {
  31471. /**
  31472. * Returns the line loop draw mode.
  31473. */
  31474. get: function () {
  31475. return Material._LineLoopDrawMode;
  31476. },
  31477. enumerable: true,
  31478. configurable: true
  31479. });
  31480. Object.defineProperty(Material, "LineStripDrawMode", {
  31481. /**
  31482. * Returns the line strip draw mode.
  31483. */
  31484. get: function () {
  31485. return Material._LineStripDrawMode;
  31486. },
  31487. enumerable: true,
  31488. configurable: true
  31489. });
  31490. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31491. /**
  31492. * Returns the triangle strip draw mode.
  31493. */
  31494. get: function () {
  31495. return Material._TriangleStripDrawMode;
  31496. },
  31497. enumerable: true,
  31498. configurable: true
  31499. });
  31500. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31501. /**
  31502. * Returns the triangle fan draw mode.
  31503. */
  31504. get: function () {
  31505. return Material._TriangleFanDrawMode;
  31506. },
  31507. enumerable: true,
  31508. configurable: true
  31509. });
  31510. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31511. /**
  31512. * Returns the clock-wise side orientation.
  31513. */
  31514. get: function () {
  31515. return Material._ClockWiseSideOrientation;
  31516. },
  31517. enumerable: true,
  31518. configurable: true
  31519. });
  31520. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31521. /**
  31522. * Returns the counter clock-wise side orientation.
  31523. */
  31524. get: function () {
  31525. return Material._CounterClockWiseSideOrientation;
  31526. },
  31527. enumerable: true,
  31528. configurable: true
  31529. });
  31530. Object.defineProperty(Material, "TextureDirtyFlag", {
  31531. /**
  31532. * Returns the dirty texture flag value.
  31533. */
  31534. get: function () {
  31535. return Material._TextureDirtyFlag;
  31536. },
  31537. enumerable: true,
  31538. configurable: true
  31539. });
  31540. Object.defineProperty(Material, "LightDirtyFlag", {
  31541. /**
  31542. * Returns the dirty light flag value.
  31543. */
  31544. get: function () {
  31545. return Material._LightDirtyFlag;
  31546. },
  31547. enumerable: true,
  31548. configurable: true
  31549. });
  31550. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31551. /**
  31552. * Returns the dirty fresnel flag value.
  31553. */
  31554. get: function () {
  31555. return Material._FresnelDirtyFlag;
  31556. },
  31557. enumerable: true,
  31558. configurable: true
  31559. });
  31560. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31561. /**
  31562. * Returns the dirty attributes flag value.
  31563. */
  31564. get: function () {
  31565. return Material._AttributesDirtyFlag;
  31566. },
  31567. enumerable: true,
  31568. configurable: true
  31569. });
  31570. Object.defineProperty(Material, "MiscDirtyFlag", {
  31571. /**
  31572. * Returns the dirty misc flag value.
  31573. */
  31574. get: function () {
  31575. return Material._MiscDirtyFlag;
  31576. },
  31577. enumerable: true,
  31578. configurable: true
  31579. });
  31580. Object.defineProperty(Material.prototype, "alpha", {
  31581. /**
  31582. * Gets the alpha value of the material.
  31583. */
  31584. get: function () {
  31585. return this._alpha;
  31586. },
  31587. /**
  31588. * Sets the alpha value of the material.
  31589. */
  31590. set: function (value) {
  31591. if (this._alpha === value) {
  31592. return;
  31593. }
  31594. this._alpha = value;
  31595. this.markAsDirty(Material.MiscDirtyFlag);
  31596. },
  31597. enumerable: true,
  31598. configurable: true
  31599. });
  31600. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31601. /**
  31602. * Gets the back-face culling state.
  31603. */
  31604. get: function () {
  31605. return this._backFaceCulling;
  31606. },
  31607. /**
  31608. * Sets the back-face culling state.
  31609. */
  31610. set: function (value) {
  31611. if (this._backFaceCulling === value) {
  31612. return;
  31613. }
  31614. this._backFaceCulling = value;
  31615. this.markAsDirty(Material.TextureDirtyFlag);
  31616. },
  31617. enumerable: true,
  31618. configurable: true
  31619. });
  31620. Object.defineProperty(Material.prototype, "onDispose", {
  31621. /**
  31622. * Called during a dispose event.
  31623. */
  31624. set: function (callback) {
  31625. if (this._onDisposeObserver) {
  31626. this.onDisposeObservable.remove(this._onDisposeObserver);
  31627. }
  31628. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31629. },
  31630. enumerable: true,
  31631. configurable: true
  31632. });
  31633. Object.defineProperty(Material.prototype, "onBind", {
  31634. /**
  31635. * Called during a bind event.
  31636. */
  31637. set: function (callback) {
  31638. if (this._onBindObserver) {
  31639. this.onBindObservable.remove(this._onBindObserver);
  31640. }
  31641. this._onBindObserver = this.onBindObservable.add(callback);
  31642. },
  31643. enumerable: true,
  31644. configurable: true
  31645. });
  31646. Object.defineProperty(Material.prototype, "alphaMode", {
  31647. /**
  31648. * Gets the value of the alpha mode.
  31649. */
  31650. get: function () {
  31651. return this._alphaMode;
  31652. },
  31653. /**
  31654. * Sets the value of the alpha mode.
  31655. *
  31656. * | Value | Type | Description |
  31657. * | --- | --- | --- |
  31658. * | 0 | ALPHA_DISABLE | |
  31659. * | 1 | ALPHA_ADD | |
  31660. * | 2 | ALPHA_COMBINE | |
  31661. * | 3 | ALPHA_SUBTRACT | |
  31662. * | 4 | ALPHA_MULTIPLY | |
  31663. * | 5 | ALPHA_MAXIMIZED | |
  31664. * | 6 | ALPHA_ONEONE | |
  31665. * | 7 | ALPHA_PREMULTIPLIED | |
  31666. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  31667. * | 9 | ALPHA_INTERPOLATE | |
  31668. * | 10 | ALPHA_SCREENMODE | |
  31669. *
  31670. */
  31671. set: function (value) {
  31672. if (this._alphaMode === value) {
  31673. return;
  31674. }
  31675. this._alphaMode = value;
  31676. this.markAsDirty(Material.TextureDirtyFlag);
  31677. },
  31678. enumerable: true,
  31679. configurable: true
  31680. });
  31681. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31682. /**
  31683. * Gets the depth pre-pass value.
  31684. */
  31685. get: function () {
  31686. return this._needDepthPrePass;
  31687. },
  31688. /**
  31689. * Sets the need depth pre-pass value.
  31690. */
  31691. set: function (value) {
  31692. if (this._needDepthPrePass === value) {
  31693. return;
  31694. }
  31695. this._needDepthPrePass = value;
  31696. if (this._needDepthPrePass) {
  31697. this.checkReadyOnEveryCall = true;
  31698. }
  31699. },
  31700. enumerable: true,
  31701. configurable: true
  31702. });
  31703. Object.defineProperty(Material.prototype, "fogEnabled", {
  31704. /**
  31705. * Gets the value of the fog enabled state.
  31706. */
  31707. get: function () {
  31708. return this._fogEnabled;
  31709. },
  31710. /**
  31711. * Sets the state for enabling fog.
  31712. */
  31713. set: function (value) {
  31714. if (this._fogEnabled === value) {
  31715. return;
  31716. }
  31717. this._fogEnabled = value;
  31718. this.markAsDirty(Material.MiscDirtyFlag);
  31719. },
  31720. enumerable: true,
  31721. configurable: true
  31722. });
  31723. Object.defineProperty(Material.prototype, "wireframe", {
  31724. /**
  31725. * Gets a value specifying if wireframe mode is enabled.
  31726. */
  31727. get: function () {
  31728. switch (this._fillMode) {
  31729. case Material.WireFrameFillMode:
  31730. case Material.LineListDrawMode:
  31731. case Material.LineLoopDrawMode:
  31732. case Material.LineStripDrawMode:
  31733. return true;
  31734. }
  31735. return this._scene.forceWireframe;
  31736. },
  31737. /**
  31738. * Sets the state of wireframe mode.
  31739. */
  31740. set: function (value) {
  31741. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31742. },
  31743. enumerable: true,
  31744. configurable: true
  31745. });
  31746. Object.defineProperty(Material.prototype, "pointsCloud", {
  31747. /**
  31748. * Gets the value specifying if point clouds are enabled.
  31749. */
  31750. get: function () {
  31751. switch (this._fillMode) {
  31752. case Material.PointFillMode:
  31753. case Material.PointListDrawMode:
  31754. return true;
  31755. }
  31756. return this._scene.forcePointsCloud;
  31757. },
  31758. /**
  31759. * Sets the state of point cloud mode.
  31760. */
  31761. set: function (value) {
  31762. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31763. },
  31764. enumerable: true,
  31765. configurable: true
  31766. });
  31767. Object.defineProperty(Material.prototype, "fillMode", {
  31768. /**
  31769. * Gets the material fill mode.
  31770. */
  31771. get: function () {
  31772. return this._fillMode;
  31773. },
  31774. /**
  31775. * Sets the material fill mode.
  31776. */
  31777. set: function (value) {
  31778. if (this._fillMode === value) {
  31779. return;
  31780. }
  31781. this._fillMode = value;
  31782. this.markAsDirty(Material.MiscDirtyFlag);
  31783. },
  31784. enumerable: true,
  31785. configurable: true
  31786. });
  31787. /**
  31788. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31789. * subclasses should override adding information pertainent to themselves.
  31790. * @returns - String with material information.
  31791. */
  31792. Material.prototype.toString = function (fullDetails) {
  31793. var ret = "Name: " + this.name;
  31794. if (fullDetails) {
  31795. }
  31796. return ret;
  31797. };
  31798. /**
  31799. * Gets the class name of the material.
  31800. * @returns - String with the class name of the material.
  31801. */
  31802. Material.prototype.getClassName = function () {
  31803. return "Material";
  31804. };
  31805. Object.defineProperty(Material.prototype, "isFrozen", {
  31806. /**
  31807. * Specifies if updates for the material been locked.
  31808. */
  31809. get: function () {
  31810. return this.checkReadyOnlyOnce;
  31811. },
  31812. enumerable: true,
  31813. configurable: true
  31814. });
  31815. /**
  31816. * Locks updates for the material.
  31817. */
  31818. Material.prototype.freeze = function () {
  31819. this.checkReadyOnlyOnce = true;
  31820. };
  31821. /**
  31822. * Unlocks updates for the material.
  31823. */
  31824. Material.prototype.unfreeze = function () {
  31825. this.checkReadyOnlyOnce = false;
  31826. };
  31827. /**
  31828. * Specifies if the material is ready to be used.
  31829. * @param mesh - BJS mesh.
  31830. * @param useInstances - Specifies if instances should be used.
  31831. * @returns - Boolean indicating if the material is ready to be used.
  31832. */
  31833. Material.prototype.isReady = function (mesh, useInstances) {
  31834. return true;
  31835. };
  31836. /**
  31837. * Specifies that the submesh is ready to be used.
  31838. * @param mesh - BJS mesh.
  31839. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31840. * @param useInstances - Specifies that instances should be used.
  31841. * @returns - boolean indicating that the submesh is ready or not.
  31842. */
  31843. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31844. return false;
  31845. };
  31846. /**
  31847. * Returns the material effect.
  31848. * @returns - Nullable material effect.
  31849. */
  31850. Material.prototype.getEffect = function () {
  31851. return this._effect;
  31852. };
  31853. /**
  31854. * Returns the BJS scene.
  31855. * @returns - BJS Scene.
  31856. */
  31857. Material.prototype.getScene = function () {
  31858. return this._scene;
  31859. };
  31860. /**
  31861. * Specifies if the material will require alpha blending
  31862. * @returns - Boolean specifying if alpha blending is needed.
  31863. */
  31864. Material.prototype.needAlphaBlending = function () {
  31865. return (this.alpha < 1.0);
  31866. };
  31867. /**
  31868. * Specifies if the mesh will require alpha blending.
  31869. * @param mesh - BJS mesh.
  31870. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31871. */
  31872. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31873. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31874. };
  31875. /**
  31876. * Specifies if this material should be rendered in alpha test mode.
  31877. * @returns - Boolean specifying if an alpha test is needed.
  31878. */
  31879. Material.prototype.needAlphaTesting = function () {
  31880. return false;
  31881. };
  31882. /**
  31883. * Gets the texture used for the alpha test.
  31884. * @returns - Nullable alpha test texture.
  31885. */
  31886. Material.prototype.getAlphaTestTexture = function () {
  31887. return null;
  31888. };
  31889. /**
  31890. * Marks the material to indicate that it needs to be re-calculated.
  31891. */
  31892. Material.prototype.markDirty = function () {
  31893. this._wasPreviouslyReady = false;
  31894. };
  31895. Material.prototype._preBind = function (effect, overrideOrientation) {
  31896. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31897. var engine = this._scene.getEngine();
  31898. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31899. var reverse = orientation === Material.ClockWiseSideOrientation;
  31900. engine.enableEffect(effect ? effect : this._effect);
  31901. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31902. return reverse;
  31903. };
  31904. /**
  31905. * Binds the material to the mesh.
  31906. * @param world - World transformation matrix.
  31907. * @param mesh - Mesh to bind the material to.
  31908. */
  31909. Material.prototype.bind = function (world, mesh) {
  31910. };
  31911. /**
  31912. * Binds the submesh to the material.
  31913. * @param world - World transformation matrix.
  31914. * @param mesh - Mesh containing the submesh.
  31915. * @param subMesh - Submesh to bind the material to.
  31916. */
  31917. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31918. };
  31919. /**
  31920. * Binds the world matrix to the material.
  31921. * @param world - World transformation matrix.
  31922. */
  31923. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31924. };
  31925. /**
  31926. * Binds the scene's uniform buffer to the effect.
  31927. * @param effect - Effect to bind to the scene uniform buffer.
  31928. * @param sceneUbo - Scene uniform buffer.
  31929. */
  31930. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31931. sceneUbo.bindToEffect(effect, "Scene");
  31932. };
  31933. /**
  31934. * Binds the view matrix to the effect.
  31935. * @param effect - Effect to bind the view matrix to.
  31936. */
  31937. Material.prototype.bindView = function (effect) {
  31938. if (!this._useUBO) {
  31939. effect.setMatrix("view", this.getScene().getViewMatrix());
  31940. }
  31941. else {
  31942. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31943. }
  31944. };
  31945. /**
  31946. * Binds the view projection matrix to the effect.
  31947. * @param effect - Effect to bind the view projection matrix to.
  31948. */
  31949. Material.prototype.bindViewProjection = function (effect) {
  31950. if (!this._useUBO) {
  31951. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31952. }
  31953. else {
  31954. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31955. }
  31956. };
  31957. /**
  31958. * Specifies if material alpha testing should be turned on for the mesh.
  31959. * @param mesh - BJS mesh.
  31960. */
  31961. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31962. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31963. };
  31964. /**
  31965. * Processes to execute after binding the material to a mesh.
  31966. * @param mesh - BJS mesh.
  31967. */
  31968. Material.prototype._afterBind = function (mesh) {
  31969. this._scene._cachedMaterial = this;
  31970. if (mesh) {
  31971. this._scene._cachedVisibility = mesh.visibility;
  31972. }
  31973. else {
  31974. this._scene._cachedVisibility = 1;
  31975. }
  31976. if (mesh) {
  31977. this.onBindObservable.notifyObservers(mesh);
  31978. }
  31979. if (this.disableDepthWrite) {
  31980. var engine = this._scene.getEngine();
  31981. this._cachedDepthWriteState = engine.getDepthWrite();
  31982. engine.setDepthWrite(false);
  31983. }
  31984. };
  31985. /**
  31986. * Unbinds the material from the mesh.
  31987. */
  31988. Material.prototype.unbind = function () {
  31989. this.onUnBindObservable.notifyObservers(this);
  31990. if (this.disableDepthWrite) {
  31991. var engine = this._scene.getEngine();
  31992. engine.setDepthWrite(this._cachedDepthWriteState);
  31993. }
  31994. };
  31995. /**
  31996. * Gets the active textures from the material.
  31997. * @returns - Array of textures.
  31998. */
  31999. Material.prototype.getActiveTextures = function () {
  32000. return [];
  32001. };
  32002. /**
  32003. * Specifies if the material uses a texture.
  32004. * @param texture - Texture to check against the material.
  32005. * @returns - Boolean specifying if the material uses the texture.
  32006. */
  32007. Material.prototype.hasTexture = function (texture) {
  32008. return false;
  32009. };
  32010. /**
  32011. * Makes a duplicate of the material, and gives it a new name.
  32012. * @param name - Name to call the duplicated material.
  32013. * @returns - Nullable cloned material
  32014. */
  32015. Material.prototype.clone = function (name) {
  32016. return null;
  32017. };
  32018. /**
  32019. * Gets the meshes bound to the material.
  32020. * @returns - Array of meshes bound to the material.
  32021. */
  32022. Material.prototype.getBindedMeshes = function () {
  32023. var result = new Array();
  32024. for (var index = 0; index < this._scene.meshes.length; index++) {
  32025. var mesh = this._scene.meshes[index];
  32026. if (mesh.material === this) {
  32027. result.push(mesh);
  32028. }
  32029. }
  32030. return result;
  32031. };
  32032. /**
  32033. * Force shader compilation
  32034. * @param mesh - BJS mesh.
  32035. * @param onCompiled - function to execute once the material is compiled.
  32036. * @param options - options to pass to this function.
  32037. */
  32038. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32039. var _this = this;
  32040. var localOptions = __assign({ clipPlane: false }, options);
  32041. var subMesh = new BABYLON.BaseSubMesh();
  32042. var scene = this.getScene();
  32043. var checkReady = function () {
  32044. if (!_this._scene || !_this._scene.getEngine()) {
  32045. return;
  32046. }
  32047. if (subMesh._materialDefines) {
  32048. subMesh._materialDefines._renderId = -1;
  32049. }
  32050. var clipPlaneState = scene.clipPlane;
  32051. if (localOptions.clipPlane) {
  32052. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32053. }
  32054. if (_this.storeEffectOnSubMeshes) {
  32055. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32056. if (onCompiled) {
  32057. onCompiled(_this);
  32058. }
  32059. }
  32060. else {
  32061. setTimeout(checkReady, 16);
  32062. }
  32063. }
  32064. else {
  32065. if (_this.isReady(mesh)) {
  32066. if (onCompiled) {
  32067. onCompiled(_this);
  32068. }
  32069. }
  32070. else {
  32071. setTimeout(checkReady, 16);
  32072. }
  32073. }
  32074. if (localOptions.clipPlane) {
  32075. scene.clipPlane = clipPlaneState;
  32076. }
  32077. };
  32078. checkReady();
  32079. };
  32080. /**
  32081. * Force shader compilation.
  32082. * @param mesh The mesh that will use this material
  32083. * @param options Additional options for compiling the shaders
  32084. * @returns A promise that resolves when the compilation completes
  32085. */
  32086. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32087. var _this = this;
  32088. return new Promise(function (resolve) {
  32089. _this.forceCompilation(mesh, function () {
  32090. resolve();
  32091. }, options);
  32092. });
  32093. };
  32094. /**
  32095. * Marks a define in the material to indicate that it needs to be re-computed.
  32096. * @param flag - Material define flag.
  32097. */
  32098. Material.prototype.markAsDirty = function (flag) {
  32099. if (flag & Material.TextureDirtyFlag) {
  32100. this._markAllSubMeshesAsTexturesDirty();
  32101. }
  32102. if (flag & Material.LightDirtyFlag) {
  32103. this._markAllSubMeshesAsLightsDirty();
  32104. }
  32105. if (flag & Material.FresnelDirtyFlag) {
  32106. this._markAllSubMeshesAsFresnelDirty();
  32107. }
  32108. if (flag & Material.AttributesDirtyFlag) {
  32109. this._markAllSubMeshesAsAttributesDirty();
  32110. }
  32111. if (flag & Material.MiscDirtyFlag) {
  32112. this._markAllSubMeshesAsMiscDirty();
  32113. }
  32114. this.getScene().resetCachedMaterial();
  32115. };
  32116. /**
  32117. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32118. * @param func - function which checks material defines against the submeshes.
  32119. */
  32120. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32121. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32122. var mesh = _a[_i];
  32123. if (!mesh.subMeshes) {
  32124. continue;
  32125. }
  32126. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32127. var subMesh = _c[_b];
  32128. if (subMesh.getMaterial() !== this) {
  32129. continue;
  32130. }
  32131. if (!subMesh._materialDefines) {
  32132. continue;
  32133. }
  32134. func(subMesh._materialDefines);
  32135. }
  32136. }
  32137. };
  32138. /**
  32139. * Indicates that image processing needs to be re-calculated for all submeshes.
  32140. */
  32141. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32142. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32143. };
  32144. /**
  32145. * Indicates that textures need to be re-calculated for all submeshes.
  32146. */
  32147. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32148. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32149. };
  32150. /**
  32151. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32152. */
  32153. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32154. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32155. };
  32156. /**
  32157. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32158. */
  32159. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32160. this._markAllSubMeshesAsDirty(function (defines) {
  32161. defines.markAsFresnelDirty();
  32162. defines.markAsMiscDirty();
  32163. });
  32164. };
  32165. /**
  32166. * Indicates that lights need to be re-calculated for all submeshes.
  32167. */
  32168. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32169. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32170. };
  32171. /**
  32172. * Indicates that attributes need to be re-calculated for all submeshes.
  32173. */
  32174. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32175. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32176. };
  32177. /**
  32178. * Indicates that misc needs to be re-calculated for all submeshes.
  32179. */
  32180. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32181. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32182. };
  32183. /**
  32184. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32185. */
  32186. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32187. this._markAllSubMeshesAsDirty(function (defines) {
  32188. defines.markAsTexturesDirty();
  32189. defines.markAsMiscDirty();
  32190. });
  32191. };
  32192. /**
  32193. * Disposes the material.
  32194. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32195. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32196. */
  32197. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32198. // Animations
  32199. this.getScene().stopAnimation(this);
  32200. this.getScene().freeProcessedMaterials();
  32201. // Remove from scene
  32202. var index = this._scene.materials.indexOf(this);
  32203. if (index >= 0) {
  32204. this._scene.materials.splice(index, 1);
  32205. }
  32206. // Remove from meshes
  32207. for (index = 0; index < this._scene.meshes.length; index++) {
  32208. var mesh = this._scene.meshes[index];
  32209. if (mesh.material === this) {
  32210. mesh.material = null;
  32211. if (mesh.geometry) {
  32212. var geometry = (mesh.geometry);
  32213. if (this.storeEffectOnSubMeshes) {
  32214. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32215. var subMesh = _a[_i];
  32216. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32217. if (forceDisposeEffect && subMesh._materialEffect) {
  32218. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32219. }
  32220. }
  32221. }
  32222. else {
  32223. geometry._releaseVertexArrayObject(this._effect);
  32224. }
  32225. }
  32226. }
  32227. }
  32228. this._uniformBuffer.dispose();
  32229. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32230. if (forceDisposeEffect && this._effect) {
  32231. if (!this.storeEffectOnSubMeshes) {
  32232. this._scene.getEngine()._releaseEffect(this._effect);
  32233. }
  32234. this._effect = null;
  32235. }
  32236. // Callback
  32237. this.onDisposeObservable.notifyObservers(this);
  32238. this.onDisposeObservable.clear();
  32239. this.onBindObservable.clear();
  32240. this.onUnBindObservable.clear();
  32241. };
  32242. /**
  32243. * Serializes this material.
  32244. * @returns - serialized material object.
  32245. */
  32246. Material.prototype.serialize = function () {
  32247. return BABYLON.SerializationHelper.Serialize(this);
  32248. };
  32249. /**
  32250. * Creates a MultiMaterial from parse MultiMaterial data.
  32251. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32252. * @param scene - BJS scene.
  32253. * @returns - MultiMaterial.
  32254. */
  32255. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32256. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32257. multiMaterial.id = parsedMultiMaterial.id;
  32258. if (BABYLON.Tags) {
  32259. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32260. }
  32261. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32262. var subMatId = parsedMultiMaterial.materials[matIndex];
  32263. if (subMatId) {
  32264. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32265. }
  32266. else {
  32267. multiMaterial.subMaterials.push(null);
  32268. }
  32269. }
  32270. return multiMaterial;
  32271. };
  32272. /**
  32273. * Creates a material from parsed material data.
  32274. * @param parsedMaterial - Parsed material data.
  32275. * @param scene - BJS scene.
  32276. * @param rootUrl - Root URL containing the material information.
  32277. * @returns - Parsed material.
  32278. */
  32279. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32280. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32281. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32282. }
  32283. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32284. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32285. if (!BABYLON.LegacyPBRMaterial) {
  32286. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32287. return;
  32288. }
  32289. }
  32290. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32291. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32292. ;
  32293. };
  32294. // Triangle views
  32295. Material._TriangleFillMode = 0;
  32296. Material._WireFrameFillMode = 1;
  32297. Material._PointFillMode = 2;
  32298. // Draw modes
  32299. Material._PointListDrawMode = 3;
  32300. Material._LineListDrawMode = 4;
  32301. Material._LineLoopDrawMode = 5;
  32302. Material._LineStripDrawMode = 6;
  32303. Material._TriangleStripDrawMode = 7;
  32304. Material._TriangleFanDrawMode = 8;
  32305. /**
  32306. * Stores the clock-wise side orientation.
  32307. */
  32308. Material._ClockWiseSideOrientation = 0;
  32309. /**
  32310. * Stores the counter clock-wise side orientation.
  32311. */
  32312. Material._CounterClockWiseSideOrientation = 1;
  32313. /**
  32314. * The dirty texture flag value.
  32315. */
  32316. Material._TextureDirtyFlag = 1;
  32317. /**
  32318. * The dirty light flag value.
  32319. */
  32320. Material._LightDirtyFlag = 2;
  32321. /**
  32322. * The dirty fresnel flag value.
  32323. */
  32324. Material._FresnelDirtyFlag = 4;
  32325. /**
  32326. * The dirty attribute flag value.
  32327. */
  32328. Material._AttributesDirtyFlag = 8;
  32329. /**
  32330. * The dirty misc flag value.
  32331. */
  32332. Material._MiscDirtyFlag = 16;
  32333. __decorate([
  32334. BABYLON.serialize()
  32335. ], Material.prototype, "id", void 0);
  32336. __decorate([
  32337. BABYLON.serialize()
  32338. ], Material.prototype, "name", void 0);
  32339. __decorate([
  32340. BABYLON.serialize()
  32341. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32342. __decorate([
  32343. BABYLON.serialize()
  32344. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32345. __decorate([
  32346. BABYLON.serialize()
  32347. ], Material.prototype, "state", void 0);
  32348. __decorate([
  32349. BABYLON.serialize("alpha")
  32350. ], Material.prototype, "_alpha", void 0);
  32351. __decorate([
  32352. BABYLON.serialize("backFaceCulling")
  32353. ], Material.prototype, "_backFaceCulling", void 0);
  32354. __decorate([
  32355. BABYLON.serialize()
  32356. ], Material.prototype, "sideOrientation", void 0);
  32357. __decorate([
  32358. BABYLON.serialize("alphaMode")
  32359. ], Material.prototype, "_alphaMode", void 0);
  32360. __decorate([
  32361. BABYLON.serialize()
  32362. ], Material.prototype, "_needDepthPrePass", void 0);
  32363. __decorate([
  32364. BABYLON.serialize()
  32365. ], Material.prototype, "disableDepthWrite", void 0);
  32366. __decorate([
  32367. BABYLON.serialize()
  32368. ], Material.prototype, "forceDepthWrite", void 0);
  32369. __decorate([
  32370. BABYLON.serialize()
  32371. ], Material.prototype, "separateCullingPass", void 0);
  32372. __decorate([
  32373. BABYLON.serialize("fogEnabled")
  32374. ], Material.prototype, "_fogEnabled", void 0);
  32375. __decorate([
  32376. BABYLON.serialize()
  32377. ], Material.prototype, "pointSize", void 0);
  32378. __decorate([
  32379. BABYLON.serialize()
  32380. ], Material.prototype, "zOffset", void 0);
  32381. __decorate([
  32382. BABYLON.serialize()
  32383. ], Material.prototype, "wireframe", null);
  32384. __decorate([
  32385. BABYLON.serialize()
  32386. ], Material.prototype, "pointsCloud", null);
  32387. __decorate([
  32388. BABYLON.serialize()
  32389. ], Material.prototype, "fillMode", null);
  32390. return Material;
  32391. }());
  32392. BABYLON.Material = Material;
  32393. })(BABYLON || (BABYLON = {}));
  32394. //# sourceMappingURL=babylon.material.js.map
  32395. "use strict";
  32396. var BABYLON;
  32397. (function (BABYLON) {
  32398. var UniformBuffer = /** @class */ (function () {
  32399. /**
  32400. * Uniform buffer objects.
  32401. *
  32402. * Handles blocks of uniform on the GPU.
  32403. *
  32404. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32405. *
  32406. * For more information, please refer to :
  32407. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32408. */
  32409. function UniformBuffer(engine, data, dynamic) {
  32410. this._engine = engine;
  32411. this._noUBO = !engine.supportsUniformBuffers;
  32412. this._dynamic = dynamic;
  32413. this._data = data || [];
  32414. this._uniformLocations = {};
  32415. this._uniformSizes = {};
  32416. this._uniformLocationPointer = 0;
  32417. this._needSync = false;
  32418. if (this._noUBO) {
  32419. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32420. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32421. this.updateFloat = this._updateFloatForEffect;
  32422. this.updateFloat2 = this._updateFloat2ForEffect;
  32423. this.updateFloat3 = this._updateFloat3ForEffect;
  32424. this.updateFloat4 = this._updateFloat4ForEffect;
  32425. this.updateMatrix = this._updateMatrixForEffect;
  32426. this.updateVector3 = this._updateVector3ForEffect;
  32427. this.updateVector4 = this._updateVector4ForEffect;
  32428. this.updateColor3 = this._updateColor3ForEffect;
  32429. this.updateColor4 = this._updateColor4ForEffect;
  32430. }
  32431. else {
  32432. this._engine._uniformBuffers.push(this);
  32433. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32434. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32435. this.updateFloat = this._updateFloatForUniform;
  32436. this.updateFloat2 = this._updateFloat2ForUniform;
  32437. this.updateFloat3 = this._updateFloat3ForUniform;
  32438. this.updateFloat4 = this._updateFloat4ForUniform;
  32439. this.updateMatrix = this._updateMatrixForUniform;
  32440. this.updateVector3 = this._updateVector3ForUniform;
  32441. this.updateVector4 = this._updateVector4ForUniform;
  32442. this.updateColor3 = this._updateColor3ForUniform;
  32443. this.updateColor4 = this._updateColor4ForUniform;
  32444. }
  32445. }
  32446. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32447. // Properties
  32448. /**
  32449. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32450. * or just falling back on setUniformXXX calls.
  32451. */
  32452. get: function () {
  32453. return !this._noUBO;
  32454. },
  32455. enumerable: true,
  32456. configurable: true
  32457. });
  32458. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32459. /**
  32460. * Indicates if the WebGL underlying uniform buffer is in sync
  32461. * with the javascript cache data.
  32462. */
  32463. get: function () {
  32464. return !this._needSync;
  32465. },
  32466. enumerable: true,
  32467. configurable: true
  32468. });
  32469. /**
  32470. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32471. * Also, a dynamic UniformBuffer will disable cache verification and always
  32472. * update the underlying WebGL uniform buffer to the GPU.
  32473. */
  32474. UniformBuffer.prototype.isDynamic = function () {
  32475. return this._dynamic !== undefined;
  32476. };
  32477. /**
  32478. * The data cache on JS side.
  32479. */
  32480. UniformBuffer.prototype.getData = function () {
  32481. return this._bufferData;
  32482. };
  32483. /**
  32484. * The underlying WebGL Uniform buffer.
  32485. */
  32486. UniformBuffer.prototype.getBuffer = function () {
  32487. return this._buffer;
  32488. };
  32489. /**
  32490. * std140 layout specifies how to align data within an UBO structure.
  32491. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32492. * for specs.
  32493. */
  32494. UniformBuffer.prototype._fillAlignment = function (size) {
  32495. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32496. // and 4x4 matrices
  32497. // TODO : change if other types are used
  32498. var alignment;
  32499. if (size <= 2) {
  32500. alignment = size;
  32501. }
  32502. else {
  32503. alignment = 4;
  32504. }
  32505. if ((this._uniformLocationPointer % alignment) !== 0) {
  32506. var oldPointer = this._uniformLocationPointer;
  32507. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32508. var diff = this._uniformLocationPointer - oldPointer;
  32509. for (var i = 0; i < diff; i++) {
  32510. this._data.push(0);
  32511. }
  32512. }
  32513. };
  32514. /**
  32515. * Adds an uniform in the buffer.
  32516. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32517. * for the layout to be correct !
  32518. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32519. * @param {number|number[]} size Data size, or data directly.
  32520. */
  32521. UniformBuffer.prototype.addUniform = function (name, size) {
  32522. if (this._noUBO) {
  32523. return;
  32524. }
  32525. if (this._uniformLocations[name] !== undefined) {
  32526. // Already existing uniform
  32527. return;
  32528. }
  32529. // This function must be called in the order of the shader layout !
  32530. // size can be the size of the uniform, or data directly
  32531. var data;
  32532. if (size instanceof Array) {
  32533. data = size;
  32534. size = data.length;
  32535. }
  32536. else {
  32537. size = size;
  32538. data = [];
  32539. // Fill with zeros
  32540. for (var i = 0; i < size; i++) {
  32541. data.push(0);
  32542. }
  32543. }
  32544. this._fillAlignment(size);
  32545. this._uniformSizes[name] = size;
  32546. this._uniformLocations[name] = this._uniformLocationPointer;
  32547. this._uniformLocationPointer += size;
  32548. for (var i = 0; i < size; i++) {
  32549. this._data.push(data[i]);
  32550. }
  32551. this._needSync = true;
  32552. };
  32553. /**
  32554. * Wrapper for addUniform.
  32555. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32556. * @param {Matrix} mat A 4x4 matrix.
  32557. */
  32558. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32559. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32560. };
  32561. /**
  32562. * Wrapper for addUniform.
  32563. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32564. * @param {number} x
  32565. * @param {number} y
  32566. */
  32567. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32568. var temp = [x, y];
  32569. this.addUniform(name, temp);
  32570. };
  32571. /**
  32572. * Wrapper for addUniform.
  32573. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32574. * @param {number} x
  32575. * @param {number} y
  32576. * @param {number} z
  32577. */
  32578. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32579. var temp = [x, y, z];
  32580. this.addUniform(name, temp);
  32581. };
  32582. /**
  32583. * Wrapper for addUniform.
  32584. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32585. * @param {Color3} color
  32586. */
  32587. UniformBuffer.prototype.addColor3 = function (name, color) {
  32588. var temp = new Array();
  32589. color.toArray(temp);
  32590. this.addUniform(name, temp);
  32591. };
  32592. /**
  32593. * Wrapper for addUniform.
  32594. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32595. * @param {Color3} color
  32596. * @param {number} alpha
  32597. */
  32598. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32599. var temp = new Array();
  32600. color.toArray(temp);
  32601. temp.push(alpha);
  32602. this.addUniform(name, temp);
  32603. };
  32604. /**
  32605. * Wrapper for addUniform.
  32606. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32607. * @param {Vector3} vector
  32608. */
  32609. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32610. var temp = new Array();
  32611. vector.toArray(temp);
  32612. this.addUniform(name, temp);
  32613. };
  32614. /**
  32615. * Wrapper for addUniform.
  32616. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32617. */
  32618. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32619. this.addUniform(name, 12);
  32620. };
  32621. /**
  32622. * Wrapper for addUniform.
  32623. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32624. */
  32625. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32626. this.addUniform(name, 8);
  32627. };
  32628. /**
  32629. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32630. */
  32631. UniformBuffer.prototype.create = function () {
  32632. if (this._noUBO) {
  32633. return;
  32634. }
  32635. if (this._buffer) {
  32636. return; // nothing to do
  32637. }
  32638. // See spec, alignment must be filled as a vec4
  32639. this._fillAlignment(4);
  32640. this._bufferData = new Float32Array(this._data);
  32641. this._rebuild();
  32642. this._needSync = true;
  32643. };
  32644. UniformBuffer.prototype._rebuild = function () {
  32645. if (this._noUBO) {
  32646. return;
  32647. }
  32648. if (this._dynamic) {
  32649. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32650. }
  32651. else {
  32652. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32653. }
  32654. };
  32655. /**
  32656. * Updates the WebGL Uniform Buffer on the GPU.
  32657. * If the `dynamic` flag is set to true, no cache comparison is done.
  32658. * Otherwise, the buffer will be updated only if the cache differs.
  32659. */
  32660. UniformBuffer.prototype.update = function () {
  32661. if (!this._buffer) {
  32662. this.create();
  32663. return;
  32664. }
  32665. if (!this._dynamic && !this._needSync) {
  32666. return;
  32667. }
  32668. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32669. this._needSync = false;
  32670. };
  32671. /**
  32672. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32673. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32674. * @param {number[]|Float32Array} data Flattened data
  32675. * @param {number} size Size of the data.
  32676. */
  32677. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32678. var location = this._uniformLocations[uniformName];
  32679. if (location === undefined) {
  32680. if (this._buffer) {
  32681. // Cannot add an uniform if the buffer is already created
  32682. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32683. return;
  32684. }
  32685. this.addUniform(uniformName, size);
  32686. location = this._uniformLocations[uniformName];
  32687. }
  32688. if (!this._buffer) {
  32689. this.create();
  32690. }
  32691. if (!this._dynamic) {
  32692. // Cache for static uniform buffers
  32693. var changed = false;
  32694. for (var i = 0; i < size; i++) {
  32695. if (this._bufferData[location + i] !== data[i]) {
  32696. changed = true;
  32697. this._bufferData[location + i] = data[i];
  32698. }
  32699. }
  32700. this._needSync = this._needSync || changed;
  32701. }
  32702. else {
  32703. // No cache for dynamic
  32704. for (var i = 0; i < size; i++) {
  32705. this._bufferData[location + i] = data[i];
  32706. }
  32707. }
  32708. };
  32709. // Update methods
  32710. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32711. // To match std140, matrix must be realigned
  32712. for (var i = 0; i < 3; i++) {
  32713. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32714. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32715. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32716. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32717. }
  32718. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32719. };
  32720. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32721. this._currentEffect.setMatrix3x3(name, matrix);
  32722. };
  32723. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32724. this._currentEffect.setMatrix2x2(name, matrix);
  32725. };
  32726. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32727. // To match std140, matrix must be realigned
  32728. for (var i = 0; i < 2; i++) {
  32729. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32730. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32731. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32732. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32733. }
  32734. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32735. };
  32736. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32737. this._currentEffect.setFloat(name, x);
  32738. };
  32739. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32740. UniformBuffer._tempBuffer[0] = x;
  32741. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32742. };
  32743. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32744. if (suffix === void 0) { suffix = ""; }
  32745. this._currentEffect.setFloat2(name + suffix, x, y);
  32746. };
  32747. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32748. if (suffix === void 0) { suffix = ""; }
  32749. UniformBuffer._tempBuffer[0] = x;
  32750. UniformBuffer._tempBuffer[1] = y;
  32751. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32752. };
  32753. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32754. if (suffix === void 0) { suffix = ""; }
  32755. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32756. };
  32757. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32758. if (suffix === void 0) { suffix = ""; }
  32759. UniformBuffer._tempBuffer[0] = x;
  32760. UniformBuffer._tempBuffer[1] = y;
  32761. UniformBuffer._tempBuffer[2] = z;
  32762. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32763. };
  32764. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32765. if (suffix === void 0) { suffix = ""; }
  32766. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32767. };
  32768. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32769. if (suffix === void 0) { suffix = ""; }
  32770. UniformBuffer._tempBuffer[0] = x;
  32771. UniformBuffer._tempBuffer[1] = y;
  32772. UniformBuffer._tempBuffer[2] = z;
  32773. UniformBuffer._tempBuffer[3] = w;
  32774. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32775. };
  32776. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32777. this._currentEffect.setMatrix(name, mat);
  32778. };
  32779. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32780. this.updateUniform(name, mat.toArray(), 16);
  32781. };
  32782. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32783. this._currentEffect.setVector3(name, vector);
  32784. };
  32785. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32786. vector.toArray(UniformBuffer._tempBuffer);
  32787. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32788. };
  32789. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32790. this._currentEffect.setVector4(name, vector);
  32791. };
  32792. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32793. vector.toArray(UniformBuffer._tempBuffer);
  32794. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32795. };
  32796. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32797. if (suffix === void 0) { suffix = ""; }
  32798. this._currentEffect.setColor3(name + suffix, color);
  32799. };
  32800. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32801. if (suffix === void 0) { suffix = ""; }
  32802. color.toArray(UniformBuffer._tempBuffer);
  32803. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32804. };
  32805. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32806. if (suffix === void 0) { suffix = ""; }
  32807. this._currentEffect.setColor4(name + suffix, color, alpha);
  32808. };
  32809. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32810. if (suffix === void 0) { suffix = ""; }
  32811. color.toArray(UniformBuffer._tempBuffer);
  32812. UniformBuffer._tempBuffer[3] = alpha;
  32813. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32814. };
  32815. /**
  32816. * Sets a sampler uniform on the effect.
  32817. * @param {string} name Name of the sampler.
  32818. * @param {Texture} texture
  32819. */
  32820. UniformBuffer.prototype.setTexture = function (name, texture) {
  32821. this._currentEffect.setTexture(name, texture);
  32822. };
  32823. /**
  32824. * Directly updates the value of the uniform in the cache AND on the GPU.
  32825. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32826. * @param {number[]|Float32Array} data Flattened data
  32827. */
  32828. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32829. this.updateUniform(uniformName, data, data.length);
  32830. this.update();
  32831. };
  32832. /**
  32833. * Binds this uniform buffer to an effect.
  32834. * @param {Effect} effect
  32835. * @param {string} name Name of the uniform block in the shader.
  32836. */
  32837. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32838. this._currentEffect = effect;
  32839. if (this._noUBO || !this._buffer) {
  32840. return;
  32841. }
  32842. effect.bindUniformBuffer(this._buffer, name);
  32843. };
  32844. /**
  32845. * Disposes the uniform buffer.
  32846. */
  32847. UniformBuffer.prototype.dispose = function () {
  32848. if (this._noUBO) {
  32849. return;
  32850. }
  32851. var index = this._engine._uniformBuffers.indexOf(this);
  32852. if (index !== -1) {
  32853. this._engine._uniformBuffers.splice(index, 1);
  32854. }
  32855. if (!this._buffer) {
  32856. return;
  32857. }
  32858. if (this._engine._releaseBuffer(this._buffer)) {
  32859. this._buffer = null;
  32860. }
  32861. };
  32862. // Pool for avoiding memory leaks
  32863. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32864. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32865. return UniformBuffer;
  32866. }());
  32867. BABYLON.UniformBuffer = UniformBuffer;
  32868. })(BABYLON || (BABYLON = {}));
  32869. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32870. "use strict";
  32871. var BABYLON;
  32872. (function (BABYLON) {
  32873. var VertexData = /** @class */ (function () {
  32874. function VertexData() {
  32875. }
  32876. VertexData.prototype.set = function (data, kind) {
  32877. switch (kind) {
  32878. case BABYLON.VertexBuffer.PositionKind:
  32879. this.positions = data;
  32880. break;
  32881. case BABYLON.VertexBuffer.NormalKind:
  32882. this.normals = data;
  32883. break;
  32884. case BABYLON.VertexBuffer.TangentKind:
  32885. this.tangents = data;
  32886. break;
  32887. case BABYLON.VertexBuffer.UVKind:
  32888. this.uvs = data;
  32889. break;
  32890. case BABYLON.VertexBuffer.UV2Kind:
  32891. this.uvs2 = data;
  32892. break;
  32893. case BABYLON.VertexBuffer.UV3Kind:
  32894. this.uvs3 = data;
  32895. break;
  32896. case BABYLON.VertexBuffer.UV4Kind:
  32897. this.uvs4 = data;
  32898. break;
  32899. case BABYLON.VertexBuffer.UV5Kind:
  32900. this.uvs5 = data;
  32901. break;
  32902. case BABYLON.VertexBuffer.UV6Kind:
  32903. this.uvs6 = data;
  32904. break;
  32905. case BABYLON.VertexBuffer.ColorKind:
  32906. this.colors = data;
  32907. break;
  32908. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32909. this.matricesIndices = data;
  32910. break;
  32911. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32912. this.matricesWeights = data;
  32913. break;
  32914. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32915. this.matricesIndicesExtra = data;
  32916. break;
  32917. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32918. this.matricesWeightsExtra = data;
  32919. break;
  32920. }
  32921. };
  32922. /**
  32923. * Associates the vertexData to the passed Mesh.
  32924. * Sets it as updatable or not (default `false`).
  32925. * Returns the VertexData.
  32926. */
  32927. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32928. this._applyTo(mesh, updatable);
  32929. return this;
  32930. };
  32931. /**
  32932. * Associates the vertexData to the passed Geometry.
  32933. * Sets it as updatable or not (default `false`).
  32934. * Returns the VertexData.
  32935. */
  32936. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32937. this._applyTo(geometry, updatable);
  32938. return this;
  32939. };
  32940. /**
  32941. * Updates the associated mesh.
  32942. * Returns the VertexData.
  32943. */
  32944. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32945. this._update(mesh);
  32946. return this;
  32947. };
  32948. /**
  32949. * Updates the associated geometry.
  32950. * Returns the VertexData.
  32951. */
  32952. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32953. this._update(geometry);
  32954. return this;
  32955. };
  32956. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32957. if (updatable === void 0) { updatable = false; }
  32958. if (this.positions) {
  32959. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32960. }
  32961. if (this.normals) {
  32962. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32963. }
  32964. if (this.tangents) {
  32965. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32966. }
  32967. if (this.uvs) {
  32968. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32969. }
  32970. if (this.uvs2) {
  32971. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32972. }
  32973. if (this.uvs3) {
  32974. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32975. }
  32976. if (this.uvs4) {
  32977. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32978. }
  32979. if (this.uvs5) {
  32980. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32981. }
  32982. if (this.uvs6) {
  32983. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32984. }
  32985. if (this.colors) {
  32986. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32987. }
  32988. if (this.matricesIndices) {
  32989. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32990. }
  32991. if (this.matricesWeights) {
  32992. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32993. }
  32994. if (this.matricesIndicesExtra) {
  32995. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32996. }
  32997. if (this.matricesWeightsExtra) {
  32998. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32999. }
  33000. if (this.indices) {
  33001. meshOrGeometry.setIndices(this.indices, null, updatable);
  33002. }
  33003. return this;
  33004. };
  33005. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33006. if (this.positions) {
  33007. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33008. }
  33009. if (this.normals) {
  33010. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33011. }
  33012. if (this.tangents) {
  33013. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  33014. }
  33015. if (this.uvs) {
  33016. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33017. }
  33018. if (this.uvs2) {
  33019. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33020. }
  33021. if (this.uvs3) {
  33022. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33023. }
  33024. if (this.uvs4) {
  33025. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33026. }
  33027. if (this.uvs5) {
  33028. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33029. }
  33030. if (this.uvs6) {
  33031. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33032. }
  33033. if (this.colors) {
  33034. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33035. }
  33036. if (this.matricesIndices) {
  33037. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33038. }
  33039. if (this.matricesWeights) {
  33040. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33041. }
  33042. if (this.matricesIndicesExtra) {
  33043. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33044. }
  33045. if (this.matricesWeightsExtra) {
  33046. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33047. }
  33048. if (this.indices) {
  33049. meshOrGeometry.setIndices(this.indices, null);
  33050. }
  33051. return this;
  33052. };
  33053. /**
  33054. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33055. * Returns the VertexData.
  33056. */
  33057. VertexData.prototype.transform = function (matrix) {
  33058. var transformed = BABYLON.Vector3.Zero();
  33059. var index;
  33060. if (this.positions) {
  33061. var position = BABYLON.Vector3.Zero();
  33062. for (index = 0; index < this.positions.length; index += 3) {
  33063. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33064. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33065. this.positions[index] = transformed.x;
  33066. this.positions[index + 1] = transformed.y;
  33067. this.positions[index + 2] = transformed.z;
  33068. }
  33069. }
  33070. if (this.normals) {
  33071. var normal = BABYLON.Vector3.Zero();
  33072. for (index = 0; index < this.normals.length; index += 3) {
  33073. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33074. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33075. this.normals[index] = transformed.x;
  33076. this.normals[index + 1] = transformed.y;
  33077. this.normals[index + 2] = transformed.z;
  33078. }
  33079. }
  33080. if (this.tangents) {
  33081. var tangent = BABYLON.Vector4.Zero();
  33082. var tangentTransformed = BABYLON.Vector4.Zero();
  33083. for (index = 0; index < this.tangents.length; index += 4) {
  33084. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33085. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33086. this.tangents[index] = tangentTransformed.x;
  33087. this.tangents[index + 1] = tangentTransformed.y;
  33088. this.tangents[index + 2] = tangentTransformed.z;
  33089. this.tangents[index + 3] = tangentTransformed.w;
  33090. }
  33091. }
  33092. return this;
  33093. };
  33094. /**
  33095. * Merges the passed VertexData into the current one.
  33096. * Returns the modified VertexData.
  33097. */
  33098. VertexData.prototype.merge = function (other) {
  33099. this._validate();
  33100. other._validate();
  33101. if (!this.normals !== !other.normals ||
  33102. !this.tangents !== !other.tangents ||
  33103. !this.uvs !== !other.uvs ||
  33104. !this.uvs2 !== !other.uvs2 ||
  33105. !this.uvs3 !== !other.uvs3 ||
  33106. !this.uvs4 !== !other.uvs4 ||
  33107. !this.uvs5 !== !other.uvs5 ||
  33108. !this.uvs6 !== !other.uvs6 ||
  33109. !this.colors !== !other.colors ||
  33110. !this.matricesIndices !== !other.matricesIndices ||
  33111. !this.matricesWeights !== !other.matricesWeights ||
  33112. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33113. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33114. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33115. }
  33116. if (other.indices) {
  33117. if (!this.indices) {
  33118. this.indices = [];
  33119. }
  33120. var offset = this.positions ? this.positions.length / 3 : 0;
  33121. for (var index = 0; index < other.indices.length; index++) {
  33122. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33123. this.indices.push(other.indices[index] + offset);
  33124. }
  33125. }
  33126. this.positions = this._mergeElement(this.positions, other.positions);
  33127. this.normals = this._mergeElement(this.normals, other.normals);
  33128. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33129. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33130. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33131. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33132. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33133. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33134. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33135. this.colors = this._mergeElement(this.colors, other.colors);
  33136. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33137. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33138. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33139. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33140. return this;
  33141. };
  33142. VertexData.prototype._mergeElement = function (source, other) {
  33143. if (!source) {
  33144. return other;
  33145. }
  33146. if (!other) {
  33147. return source;
  33148. }
  33149. var len = other.length + source.length;
  33150. var isSrcTypedArray = source instanceof Float32Array;
  33151. var isOthTypedArray = other instanceof Float32Array;
  33152. // use non-loop method when the source is Float32Array
  33153. if (isSrcTypedArray) {
  33154. var ret32 = new Float32Array(len);
  33155. ret32.set(source);
  33156. ret32.set(other, source.length);
  33157. return ret32;
  33158. // source is number[], when other is also use concat
  33159. }
  33160. else if (!isOthTypedArray) {
  33161. return source.concat(other);
  33162. // source is a number[], but other is a Float32Array, loop required
  33163. }
  33164. else {
  33165. var ret = source.slice(0); // copy source to a separate array
  33166. for (var i = 0, len = other.length; i < len; i++) {
  33167. ret.push(other[i]);
  33168. }
  33169. return ret;
  33170. }
  33171. };
  33172. VertexData.prototype._validate = function () {
  33173. if (!this.positions) {
  33174. throw new Error("Positions are required");
  33175. }
  33176. var getElementCount = function (kind, values) {
  33177. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33178. if ((values.length % stride) !== 0) {
  33179. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33180. }
  33181. return values.length / stride;
  33182. };
  33183. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33184. var validateElementCount = function (kind, values) {
  33185. var elementCount = getElementCount(kind, values);
  33186. if (elementCount !== positionsElementCount) {
  33187. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33188. }
  33189. };
  33190. if (this.normals)
  33191. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33192. if (this.tangents)
  33193. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33194. if (this.uvs)
  33195. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33196. if (this.uvs2)
  33197. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33198. if (this.uvs3)
  33199. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33200. if (this.uvs4)
  33201. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33202. if (this.uvs5)
  33203. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33204. if (this.uvs6)
  33205. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33206. if (this.colors)
  33207. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33208. if (this.matricesIndices)
  33209. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33210. if (this.matricesWeights)
  33211. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33212. if (this.matricesIndicesExtra)
  33213. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33214. if (this.matricesWeightsExtra)
  33215. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33216. };
  33217. /**
  33218. * Serializes the VertexData.
  33219. * Returns a serialized object.
  33220. */
  33221. VertexData.prototype.serialize = function () {
  33222. var serializationObject = this.serialize();
  33223. if (this.positions) {
  33224. serializationObject.positions = this.positions;
  33225. }
  33226. if (this.normals) {
  33227. serializationObject.normals = this.normals;
  33228. }
  33229. if (this.tangents) {
  33230. serializationObject.tangents = this.tangents;
  33231. }
  33232. if (this.uvs) {
  33233. serializationObject.uvs = this.uvs;
  33234. }
  33235. if (this.uvs2) {
  33236. serializationObject.uvs2 = this.uvs2;
  33237. }
  33238. if (this.uvs3) {
  33239. serializationObject.uvs3 = this.uvs3;
  33240. }
  33241. if (this.uvs4) {
  33242. serializationObject.uvs4 = this.uvs4;
  33243. }
  33244. if (this.uvs5) {
  33245. serializationObject.uvs5 = this.uvs5;
  33246. }
  33247. if (this.uvs6) {
  33248. serializationObject.uvs6 = this.uvs6;
  33249. }
  33250. if (this.colors) {
  33251. serializationObject.colors = this.colors;
  33252. }
  33253. if (this.matricesIndices) {
  33254. serializationObject.matricesIndices = this.matricesIndices;
  33255. serializationObject.matricesIndices._isExpanded = true;
  33256. }
  33257. if (this.matricesWeights) {
  33258. serializationObject.matricesWeights = this.matricesWeights;
  33259. }
  33260. if (this.matricesIndicesExtra) {
  33261. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33262. serializationObject.matricesIndicesExtra._isExpanded = true;
  33263. }
  33264. if (this.matricesWeightsExtra) {
  33265. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33266. }
  33267. serializationObject.indices = this.indices;
  33268. return serializationObject;
  33269. };
  33270. // Statics
  33271. /**
  33272. * Returns the object VertexData associated to the passed mesh.
  33273. */
  33274. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33275. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33276. };
  33277. /**
  33278. * Returns the object VertexData associated to the passed geometry.
  33279. */
  33280. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33281. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33282. };
  33283. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33284. var result = new VertexData();
  33285. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33286. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33287. }
  33288. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33289. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33290. }
  33291. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33292. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33293. }
  33294. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33295. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33296. }
  33297. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33298. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33299. }
  33300. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33301. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33302. }
  33303. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33304. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33305. }
  33306. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33307. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33308. }
  33309. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33310. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33311. }
  33312. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33313. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33314. }
  33315. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33316. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33317. }
  33318. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33319. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33320. }
  33321. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33322. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33323. }
  33324. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33325. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33326. }
  33327. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33328. return result;
  33329. };
  33330. /**
  33331. * Creates the vertexData of the Ribbon.
  33332. */
  33333. VertexData.CreateRibbon = function (options) {
  33334. var pathArray = options.pathArray;
  33335. var closeArray = options.closeArray || false;
  33336. var closePath = options.closePath || false;
  33337. var invertUV = options.invertUV || false;
  33338. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33339. var offset = options.offset || defaultOffset;
  33340. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33341. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33342. var customUV = options.uvs;
  33343. var customColors = options.colors;
  33344. var positions = [];
  33345. var indices = [];
  33346. var normals = [];
  33347. var uvs = [];
  33348. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33349. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33350. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33351. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33352. var minlg; // minimal length among all paths from pathArray
  33353. var lg = []; // array of path lengths : nb of vertex per path
  33354. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33355. var p; // path iterator
  33356. var i; // point iterator
  33357. var j; // point iterator
  33358. // if single path in pathArray
  33359. if (pathArray.length < 2) {
  33360. var ar1 = [];
  33361. var ar2 = [];
  33362. for (i = 0; i < pathArray[0].length - offset; i++) {
  33363. ar1.push(pathArray[0][i]);
  33364. ar2.push(pathArray[0][i + offset]);
  33365. }
  33366. pathArray = [ar1, ar2];
  33367. }
  33368. // positions and horizontal distances (u)
  33369. var idc = 0;
  33370. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33371. var path;
  33372. var l;
  33373. minlg = pathArray[0].length;
  33374. var vectlg;
  33375. var dist;
  33376. for (p = 0; p < pathArray.length; p++) {
  33377. uTotalDistance[p] = 0;
  33378. us[p] = [0];
  33379. path = pathArray[p];
  33380. l = path.length;
  33381. minlg = (minlg < l) ? minlg : l;
  33382. j = 0;
  33383. while (j < l) {
  33384. positions.push(path[j].x, path[j].y, path[j].z);
  33385. if (j > 0) {
  33386. vectlg = path[j].subtract(path[j - 1]).length();
  33387. dist = vectlg + uTotalDistance[p];
  33388. us[p].push(dist);
  33389. uTotalDistance[p] = dist;
  33390. }
  33391. j++;
  33392. }
  33393. if (closePath) {
  33394. j--;
  33395. positions.push(path[0].x, path[0].y, path[0].z);
  33396. vectlg = path[j].subtract(path[0]).length();
  33397. dist = vectlg + uTotalDistance[p];
  33398. us[p].push(dist);
  33399. uTotalDistance[p] = dist;
  33400. }
  33401. lg[p] = l + closePathCorr;
  33402. idx[p] = idc;
  33403. idc += (l + closePathCorr);
  33404. }
  33405. // vertical distances (v)
  33406. var path1;
  33407. var path2;
  33408. var vertex1 = null;
  33409. var vertex2 = null;
  33410. for (i = 0; i < minlg + closePathCorr; i++) {
  33411. vTotalDistance[i] = 0;
  33412. vs[i] = [0];
  33413. for (p = 0; p < pathArray.length - 1; p++) {
  33414. path1 = pathArray[p];
  33415. path2 = pathArray[p + 1];
  33416. if (i === minlg) {
  33417. vertex1 = path1[0];
  33418. vertex2 = path2[0];
  33419. }
  33420. else {
  33421. vertex1 = path1[i];
  33422. vertex2 = path2[i];
  33423. }
  33424. vectlg = vertex2.subtract(vertex1).length();
  33425. dist = vectlg + vTotalDistance[i];
  33426. vs[i].push(dist);
  33427. vTotalDistance[i] = dist;
  33428. }
  33429. if (closeArray && vertex2 && vertex1) {
  33430. path1 = pathArray[p];
  33431. path2 = pathArray[0];
  33432. if (i === minlg) {
  33433. vertex2 = path2[0];
  33434. }
  33435. vectlg = vertex2.subtract(vertex1).length();
  33436. dist = vectlg + vTotalDistance[i];
  33437. vTotalDistance[i] = dist;
  33438. }
  33439. }
  33440. // uvs
  33441. var u;
  33442. var v;
  33443. if (customUV) {
  33444. for (p = 0; p < customUV.length; p++) {
  33445. uvs.push(customUV[p].x, customUV[p].y);
  33446. }
  33447. }
  33448. else {
  33449. for (p = 0; p < pathArray.length; p++) {
  33450. for (i = 0; i < minlg + closePathCorr; i++) {
  33451. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33452. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33453. if (invertUV) {
  33454. uvs.push(v, u);
  33455. }
  33456. else {
  33457. uvs.push(u, v);
  33458. }
  33459. }
  33460. }
  33461. }
  33462. // indices
  33463. p = 0; // path index
  33464. var pi = 0; // positions array index
  33465. var l1 = lg[p] - 1; // path1 length
  33466. var l2 = lg[p + 1] - 1; // path2 length
  33467. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33468. var shft = idx[1] - idx[0]; // shift
  33469. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33470. while (pi <= min && p < path1nb) {
  33471. // 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
  33472. indices.push(pi, pi + shft, pi + 1);
  33473. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33474. pi += 1;
  33475. if (pi === min) {
  33476. p++;
  33477. if (p === lg.length - 1) {
  33478. shft = idx[0] - idx[p];
  33479. l1 = lg[p] - 1;
  33480. l2 = lg[0] - 1;
  33481. }
  33482. else {
  33483. shft = idx[p + 1] - idx[p];
  33484. l1 = lg[p] - 1;
  33485. l2 = lg[p + 1] - 1;
  33486. }
  33487. pi = idx[p];
  33488. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33489. }
  33490. }
  33491. // normals
  33492. VertexData.ComputeNormals(positions, indices, normals);
  33493. if (closePath) {
  33494. var indexFirst = 0;
  33495. var indexLast = 0;
  33496. for (p = 0; p < pathArray.length; p++) {
  33497. indexFirst = idx[p] * 3;
  33498. if (p + 1 < pathArray.length) {
  33499. indexLast = (idx[p + 1] - 1) * 3;
  33500. }
  33501. else {
  33502. indexLast = normals.length - 3;
  33503. }
  33504. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33505. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33506. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33507. normals[indexLast] = normals[indexFirst];
  33508. normals[indexLast + 1] = normals[indexFirst + 1];
  33509. normals[indexLast + 2] = normals[indexFirst + 2];
  33510. }
  33511. }
  33512. // sides
  33513. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33514. // Colors
  33515. var colors = null;
  33516. if (customColors) {
  33517. colors = new Float32Array(customColors.length * 4);
  33518. for (var c = 0; c < customColors.length; c++) {
  33519. colors[c * 4] = customColors[c].r;
  33520. colors[c * 4 + 1] = customColors[c].g;
  33521. colors[c * 4 + 2] = customColors[c].b;
  33522. colors[c * 4 + 3] = customColors[c].a;
  33523. }
  33524. }
  33525. // Result
  33526. var vertexData = new VertexData();
  33527. var positions32 = new Float32Array(positions);
  33528. var normals32 = new Float32Array(normals);
  33529. var uvs32 = new Float32Array(uvs);
  33530. vertexData.indices = indices;
  33531. vertexData.positions = positions32;
  33532. vertexData.normals = normals32;
  33533. vertexData.uvs = uvs32;
  33534. if (colors) {
  33535. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33536. }
  33537. if (closePath) {
  33538. vertexData._idx = idx;
  33539. }
  33540. return vertexData;
  33541. };
  33542. /**
  33543. * Creates the VertexData of the Box.
  33544. */
  33545. VertexData.CreateBox = function (options) {
  33546. var normalsSource = [
  33547. new BABYLON.Vector3(0, 0, 1),
  33548. new BABYLON.Vector3(0, 0, -1),
  33549. new BABYLON.Vector3(1, 0, 0),
  33550. new BABYLON.Vector3(-1, 0, 0),
  33551. new BABYLON.Vector3(0, 1, 0),
  33552. new BABYLON.Vector3(0, -1, 0)
  33553. ];
  33554. var indices = [];
  33555. var positions = [];
  33556. var normals = [];
  33557. var uvs = [];
  33558. var width = options.width || options.size || 1;
  33559. var height = options.height || options.size || 1;
  33560. var depth = options.depth || options.size || 1;
  33561. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33562. var faceUV = options.faceUV || new Array(6);
  33563. var faceColors = options.faceColors;
  33564. var colors = [];
  33565. // default face colors and UV if undefined
  33566. for (var f = 0; f < 6; f++) {
  33567. if (faceUV[f] === undefined) {
  33568. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33569. }
  33570. if (faceColors && faceColors[f] === undefined) {
  33571. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33572. }
  33573. }
  33574. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33575. // Create each face in turn.
  33576. for (var index = 0; index < normalsSource.length; index++) {
  33577. var normal = normalsSource[index];
  33578. // Get two vectors perpendicular to the face normal and to each other.
  33579. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33580. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33581. // Six indices (two triangles) per face.
  33582. var verticesLength = positions.length / 3;
  33583. indices.push(verticesLength);
  33584. indices.push(verticesLength + 1);
  33585. indices.push(verticesLength + 2);
  33586. indices.push(verticesLength);
  33587. indices.push(verticesLength + 2);
  33588. indices.push(verticesLength + 3);
  33589. // Four vertices per face.
  33590. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33591. positions.push(vertex.x, vertex.y, vertex.z);
  33592. normals.push(normal.x, normal.y, normal.z);
  33593. uvs.push(faceUV[index].z, faceUV[index].w);
  33594. if (faceColors) {
  33595. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33596. }
  33597. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33598. positions.push(vertex.x, vertex.y, vertex.z);
  33599. normals.push(normal.x, normal.y, normal.z);
  33600. uvs.push(faceUV[index].x, faceUV[index].w);
  33601. if (faceColors) {
  33602. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33603. }
  33604. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33605. positions.push(vertex.x, vertex.y, vertex.z);
  33606. normals.push(normal.x, normal.y, normal.z);
  33607. uvs.push(faceUV[index].x, faceUV[index].y);
  33608. if (faceColors) {
  33609. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33610. }
  33611. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33612. positions.push(vertex.x, vertex.y, vertex.z);
  33613. normals.push(normal.x, normal.y, normal.z);
  33614. uvs.push(faceUV[index].z, faceUV[index].y);
  33615. if (faceColors) {
  33616. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33617. }
  33618. }
  33619. // sides
  33620. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33621. // Result
  33622. var vertexData = new VertexData();
  33623. vertexData.indices = indices;
  33624. vertexData.positions = positions;
  33625. vertexData.normals = normals;
  33626. vertexData.uvs = uvs;
  33627. if (faceColors) {
  33628. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33629. vertexData.colors = totalColors;
  33630. }
  33631. return vertexData;
  33632. };
  33633. /**
  33634. * Creates the VertexData of the Sphere.
  33635. */
  33636. VertexData.CreateSphere = function (options) {
  33637. var segments = options.segments || 32;
  33638. var diameterX = options.diameterX || options.diameter || 1;
  33639. var diameterY = options.diameterY || options.diameter || 1;
  33640. var diameterZ = options.diameterZ || options.diameter || 1;
  33641. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33642. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33643. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33644. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33645. var totalZRotationSteps = 2 + segments;
  33646. var totalYRotationSteps = 2 * totalZRotationSteps;
  33647. var indices = [];
  33648. var positions = [];
  33649. var normals = [];
  33650. var uvs = [];
  33651. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33652. var normalizedZ = zRotationStep / totalZRotationSteps;
  33653. var angleZ = normalizedZ * Math.PI * slice;
  33654. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33655. var normalizedY = yRotationStep / totalYRotationSteps;
  33656. var angleY = normalizedY * Math.PI * 2 * arc;
  33657. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33658. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33659. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33660. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33661. var vertex = complete.multiply(radius);
  33662. var normal = complete.divide(radius).normalize();
  33663. positions.push(vertex.x, vertex.y, vertex.z);
  33664. normals.push(normal.x, normal.y, normal.z);
  33665. uvs.push(normalizedY, normalizedZ);
  33666. }
  33667. if (zRotationStep > 0) {
  33668. var verticesCount = positions.length / 3;
  33669. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33670. indices.push((firstIndex));
  33671. indices.push((firstIndex + 1));
  33672. indices.push(firstIndex + totalYRotationSteps + 1);
  33673. indices.push((firstIndex + totalYRotationSteps + 1));
  33674. indices.push((firstIndex + 1));
  33675. indices.push((firstIndex + totalYRotationSteps + 2));
  33676. }
  33677. }
  33678. }
  33679. // Sides
  33680. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33681. // Result
  33682. var vertexData = new VertexData();
  33683. vertexData.indices = indices;
  33684. vertexData.positions = positions;
  33685. vertexData.normals = normals;
  33686. vertexData.uvs = uvs;
  33687. return vertexData;
  33688. };
  33689. /**
  33690. * Creates the VertexData of the Cylinder or Cone.
  33691. */
  33692. VertexData.CreateCylinder = function (options) {
  33693. var height = options.height || 2;
  33694. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33695. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33696. var tessellation = options.tessellation || 24;
  33697. var subdivisions = options.subdivisions || 1;
  33698. var hasRings = options.hasRings ? true : false;
  33699. var enclose = options.enclose ? true : false;
  33700. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33701. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33702. var faceUV = options.faceUV || new Array(3);
  33703. var faceColors = options.faceColors;
  33704. // default face colors and UV if undefined
  33705. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33706. var ringNb = (hasRings) ? subdivisions : 1;
  33707. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33708. var f;
  33709. for (f = 0; f < surfaceNb; f++) {
  33710. if (faceColors && faceColors[f] === undefined) {
  33711. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33712. }
  33713. }
  33714. for (f = 0; f < surfaceNb; f++) {
  33715. if (faceUV && faceUV[f] === undefined) {
  33716. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33717. }
  33718. }
  33719. var indices = new Array();
  33720. var positions = new Array();
  33721. var normals = new Array();
  33722. var uvs = new Array();
  33723. var colors = new Array();
  33724. var angle_step = Math.PI * 2 * arc / tessellation;
  33725. var angle;
  33726. var h;
  33727. var radius;
  33728. var tan = (diameterBottom - diameterTop) / 2 / height;
  33729. var ringVertex = BABYLON.Vector3.Zero();
  33730. var ringNormal = BABYLON.Vector3.Zero();
  33731. var ringFirstVertex = BABYLON.Vector3.Zero();
  33732. var ringFirstNormal = BABYLON.Vector3.Zero();
  33733. var quadNormal = BABYLON.Vector3.Zero();
  33734. var Y = BABYLON.Axis.Y;
  33735. // positions, normals, uvs
  33736. var i;
  33737. var j;
  33738. var r;
  33739. var ringIdx = 1;
  33740. var s = 1; // surface index
  33741. var cs = 0;
  33742. var v = 0;
  33743. for (i = 0; i <= subdivisions; i++) {
  33744. h = i / subdivisions;
  33745. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33746. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33747. for (r = 0; r < ringIdx; r++) {
  33748. if (hasRings) {
  33749. s += r;
  33750. }
  33751. if (enclose) {
  33752. s += 2 * r;
  33753. }
  33754. for (j = 0; j <= tessellation; j++) {
  33755. angle = j * angle_step;
  33756. // position
  33757. ringVertex.x = Math.cos(-angle) * radius;
  33758. ringVertex.y = -height / 2 + h * height;
  33759. ringVertex.z = Math.sin(-angle) * radius;
  33760. // normal
  33761. if (diameterTop === 0 && i === subdivisions) {
  33762. // if no top cap, reuse former normals
  33763. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33764. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33765. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33766. }
  33767. else {
  33768. ringNormal.x = ringVertex.x;
  33769. ringNormal.z = ringVertex.z;
  33770. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33771. ringNormal.normalize();
  33772. }
  33773. // keep first ring vertex values for enclose
  33774. if (j === 0) {
  33775. ringFirstVertex.copyFrom(ringVertex);
  33776. ringFirstNormal.copyFrom(ringNormal);
  33777. }
  33778. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33779. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33780. if (hasRings) {
  33781. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33782. }
  33783. else {
  33784. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33785. }
  33786. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33787. if (faceColors) {
  33788. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33789. }
  33790. }
  33791. // if enclose, add four vertices and their dedicated normals
  33792. if (arc !== 1 && enclose) {
  33793. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33794. positions.push(0, ringVertex.y, 0);
  33795. positions.push(0, ringVertex.y, 0);
  33796. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33797. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33798. quadNormal.normalize();
  33799. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33800. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33801. quadNormal.normalize();
  33802. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33803. if (hasRings) {
  33804. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33805. }
  33806. else {
  33807. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33808. }
  33809. uvs.push(faceUV[s + 1].x, v);
  33810. uvs.push(faceUV[s + 1].z, v);
  33811. if (hasRings) {
  33812. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33813. }
  33814. else {
  33815. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33816. }
  33817. uvs.push(faceUV[s + 2].x, v);
  33818. uvs.push(faceUV[s + 2].z, v);
  33819. if (faceColors) {
  33820. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33821. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33822. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33823. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33824. }
  33825. }
  33826. if (cs !== s) {
  33827. cs = s;
  33828. }
  33829. }
  33830. }
  33831. // indices
  33832. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33833. var s;
  33834. i = 0;
  33835. for (s = 0; s < subdivisions; s++) {
  33836. var i0 = 0;
  33837. var i1 = 0;
  33838. var i2 = 0;
  33839. var i3 = 0;
  33840. for (j = 0; j < tessellation; j++) {
  33841. i0 = i * (e + 1) + j;
  33842. i1 = (i + 1) * (e + 1) + j;
  33843. i2 = i * (e + 1) + (j + 1);
  33844. i3 = (i + 1) * (e + 1) + (j + 1);
  33845. indices.push(i0, i1, i2);
  33846. indices.push(i3, i2, i1);
  33847. }
  33848. if (arc !== 1 && enclose) {
  33849. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33850. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33851. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33852. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33853. }
  33854. i = (hasRings) ? (i + 2) : (i + 1);
  33855. }
  33856. // Caps
  33857. var createCylinderCap = function (isTop) {
  33858. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33859. if (radius === 0) {
  33860. return;
  33861. }
  33862. // Cap positions, normals & uvs
  33863. var angle;
  33864. var circleVector;
  33865. var i;
  33866. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33867. var c = null;
  33868. if (faceColors) {
  33869. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33870. }
  33871. // cap center
  33872. var vbase = positions.length / 3;
  33873. var offset = isTop ? height / 2 : -height / 2;
  33874. var center = new BABYLON.Vector3(0, offset, 0);
  33875. positions.push(center.x, center.y, center.z);
  33876. normals.push(0, isTop ? 1 : -1, 0);
  33877. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33878. if (c) {
  33879. colors.push(c.r, c.g, c.b, c.a);
  33880. }
  33881. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33882. for (i = 0; i <= tessellation; i++) {
  33883. angle = Math.PI * 2 * i * arc / tessellation;
  33884. var cos = Math.cos(-angle);
  33885. var sin = Math.sin(-angle);
  33886. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33887. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33888. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33889. normals.push(0, isTop ? 1 : -1, 0);
  33890. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33891. if (c) {
  33892. colors.push(c.r, c.g, c.b, c.a);
  33893. }
  33894. }
  33895. // Cap indices
  33896. for (i = 0; i < tessellation; i++) {
  33897. if (!isTop) {
  33898. indices.push(vbase);
  33899. indices.push(vbase + (i + 1));
  33900. indices.push(vbase + (i + 2));
  33901. }
  33902. else {
  33903. indices.push(vbase);
  33904. indices.push(vbase + (i + 2));
  33905. indices.push(vbase + (i + 1));
  33906. }
  33907. }
  33908. };
  33909. // add caps to geometry
  33910. createCylinderCap(false);
  33911. createCylinderCap(true);
  33912. // Sides
  33913. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33914. var vertexData = new VertexData();
  33915. vertexData.indices = indices;
  33916. vertexData.positions = positions;
  33917. vertexData.normals = normals;
  33918. vertexData.uvs = uvs;
  33919. if (faceColors) {
  33920. vertexData.colors = colors;
  33921. }
  33922. return vertexData;
  33923. };
  33924. /**
  33925. * Creates the VertexData of the Torus.
  33926. */
  33927. VertexData.CreateTorus = function (options) {
  33928. var indices = [];
  33929. var positions = [];
  33930. var normals = [];
  33931. var uvs = [];
  33932. var diameter = options.diameter || 1;
  33933. var thickness = options.thickness || 0.5;
  33934. var tessellation = options.tessellation || 16;
  33935. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33936. var stride = tessellation + 1;
  33937. for (var i = 0; i <= tessellation; i++) {
  33938. var u = i / tessellation;
  33939. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33940. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33941. for (var j = 0; j <= tessellation; j++) {
  33942. var v = 1 - j / tessellation;
  33943. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33944. var dx = Math.cos(innerAngle);
  33945. var dy = Math.sin(innerAngle);
  33946. // Create a vertex.
  33947. var normal = new BABYLON.Vector3(dx, dy, 0);
  33948. var position = normal.scale(thickness / 2);
  33949. var textureCoordinate = new BABYLON.Vector2(u, v);
  33950. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33951. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33952. positions.push(position.x, position.y, position.z);
  33953. normals.push(normal.x, normal.y, normal.z);
  33954. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33955. // And create indices for two triangles.
  33956. var nextI = (i + 1) % stride;
  33957. var nextJ = (j + 1) % stride;
  33958. indices.push(i * stride + j);
  33959. indices.push(i * stride + nextJ);
  33960. indices.push(nextI * stride + j);
  33961. indices.push(i * stride + nextJ);
  33962. indices.push(nextI * stride + nextJ);
  33963. indices.push(nextI * stride + j);
  33964. }
  33965. }
  33966. // Sides
  33967. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33968. // Result
  33969. var vertexData = new VertexData();
  33970. vertexData.indices = indices;
  33971. vertexData.positions = positions;
  33972. vertexData.normals = normals;
  33973. vertexData.uvs = uvs;
  33974. return vertexData;
  33975. };
  33976. /**
  33977. * Creates the VertexData of the LineSystem.
  33978. */
  33979. VertexData.CreateLineSystem = function (options) {
  33980. var indices = [];
  33981. var positions = [];
  33982. var lines = options.lines;
  33983. var colors = options.colors;
  33984. var vertexColors = [];
  33985. var idx = 0;
  33986. for (var l = 0; l < lines.length; l++) {
  33987. var points = lines[l];
  33988. for (var index = 0; index < points.length; index++) {
  33989. positions.push(points[index].x, points[index].y, points[index].z);
  33990. if (colors) {
  33991. var color = colors[l];
  33992. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33993. }
  33994. if (index > 0) {
  33995. indices.push(idx - 1);
  33996. indices.push(idx);
  33997. }
  33998. idx++;
  33999. }
  34000. }
  34001. var vertexData = new VertexData();
  34002. vertexData.indices = indices;
  34003. vertexData.positions = positions;
  34004. if (colors) {
  34005. vertexData.colors = vertexColors;
  34006. }
  34007. return vertexData;
  34008. };
  34009. /**
  34010. * Create the VertexData of the DashedLines.
  34011. */
  34012. VertexData.CreateDashedLines = function (options) {
  34013. var dashSize = options.dashSize || 3;
  34014. var gapSize = options.gapSize || 1;
  34015. var dashNb = options.dashNb || 200;
  34016. var points = options.points;
  34017. var positions = new Array();
  34018. var indices = new Array();
  34019. var curvect = BABYLON.Vector3.Zero();
  34020. var lg = 0;
  34021. var nb = 0;
  34022. var shft = 0;
  34023. var dashshft = 0;
  34024. var curshft = 0;
  34025. var idx = 0;
  34026. var i = 0;
  34027. for (i = 0; i < points.length - 1; i++) {
  34028. points[i + 1].subtractToRef(points[i], curvect);
  34029. lg += curvect.length();
  34030. }
  34031. shft = lg / dashNb;
  34032. dashshft = dashSize * shft / (dashSize + gapSize);
  34033. for (i = 0; i < points.length - 1; i++) {
  34034. points[i + 1].subtractToRef(points[i], curvect);
  34035. nb = Math.floor(curvect.length() / shft);
  34036. curvect.normalize();
  34037. for (var j = 0; j < nb; j++) {
  34038. curshft = shft * j;
  34039. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34040. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34041. indices.push(idx, idx + 1);
  34042. idx += 2;
  34043. }
  34044. }
  34045. // Result
  34046. var vertexData = new VertexData();
  34047. vertexData.positions = positions;
  34048. vertexData.indices = indices;
  34049. return vertexData;
  34050. };
  34051. /**
  34052. * Creates the VertexData of the Ground.
  34053. */
  34054. VertexData.CreateGround = function (options) {
  34055. var indices = [];
  34056. var positions = [];
  34057. var normals = [];
  34058. var uvs = [];
  34059. var row, col;
  34060. var width = options.width || 1;
  34061. var height = options.height || 1;
  34062. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34063. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34064. for (row = 0; row <= subdivisionsY; row++) {
  34065. for (col = 0; col <= subdivisionsX; col++) {
  34066. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34067. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34068. positions.push(position.x, position.y, position.z);
  34069. normals.push(normal.x, normal.y, normal.z);
  34070. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34071. }
  34072. }
  34073. for (row = 0; row < subdivisionsY; row++) {
  34074. for (col = 0; col < subdivisionsX; col++) {
  34075. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34076. indices.push(col + 1 + row * (subdivisionsX + 1));
  34077. indices.push(col + row * (subdivisionsX + 1));
  34078. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34079. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34080. indices.push(col + row * (subdivisionsX + 1));
  34081. }
  34082. }
  34083. // Result
  34084. var vertexData = new VertexData();
  34085. vertexData.indices = indices;
  34086. vertexData.positions = positions;
  34087. vertexData.normals = normals;
  34088. vertexData.uvs = uvs;
  34089. return vertexData;
  34090. };
  34091. /**
  34092. * Creates the VertexData of the TiledGround.
  34093. */
  34094. VertexData.CreateTiledGround = function (options) {
  34095. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34096. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34097. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34098. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34099. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34100. var precision = options.precision || { w: 1, h: 1 };
  34101. var indices = new Array();
  34102. var positions = new Array();
  34103. var normals = new Array();
  34104. var uvs = new Array();
  34105. var row, col, tileRow, tileCol;
  34106. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34107. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34108. precision.w = (precision.w < 1) ? 1 : precision.w;
  34109. precision.h = (precision.h < 1) ? 1 : precision.h;
  34110. var tileSize = {
  34111. 'w': (xmax - xmin) / subdivisions.w,
  34112. 'h': (zmax - zmin) / subdivisions.h
  34113. };
  34114. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34115. // Indices
  34116. var base = positions.length / 3;
  34117. var rowLength = precision.w + 1;
  34118. for (row = 0; row < precision.h; row++) {
  34119. for (col = 0; col < precision.w; col++) {
  34120. var square = [
  34121. base + col + row * rowLength,
  34122. base + (col + 1) + row * rowLength,
  34123. base + (col + 1) + (row + 1) * rowLength,
  34124. base + col + (row + 1) * rowLength
  34125. ];
  34126. indices.push(square[1]);
  34127. indices.push(square[2]);
  34128. indices.push(square[3]);
  34129. indices.push(square[0]);
  34130. indices.push(square[1]);
  34131. indices.push(square[3]);
  34132. }
  34133. }
  34134. // Position, normals and uvs
  34135. var position = BABYLON.Vector3.Zero();
  34136. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34137. for (row = 0; row <= precision.h; row++) {
  34138. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34139. for (col = 0; col <= precision.w; col++) {
  34140. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34141. position.y = 0;
  34142. positions.push(position.x, position.y, position.z);
  34143. normals.push(normal.x, normal.y, normal.z);
  34144. uvs.push(col / precision.w, row / precision.h);
  34145. }
  34146. }
  34147. }
  34148. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34149. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34150. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34151. }
  34152. }
  34153. // Result
  34154. var vertexData = new VertexData();
  34155. vertexData.indices = indices;
  34156. vertexData.positions = positions;
  34157. vertexData.normals = normals;
  34158. vertexData.uvs = uvs;
  34159. return vertexData;
  34160. };
  34161. /**
  34162. * Creates the VertexData of the Ground designed from a heightmap.
  34163. */
  34164. VertexData.CreateGroundFromHeightMap = function (options) {
  34165. var indices = [];
  34166. var positions = [];
  34167. var normals = [];
  34168. var uvs = [];
  34169. var row, col;
  34170. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34171. // Vertices
  34172. for (row = 0; row <= options.subdivisions; row++) {
  34173. for (col = 0; col <= options.subdivisions; col++) {
  34174. 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));
  34175. // Compute height
  34176. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34177. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34178. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34179. var r = options.buffer[pos] / 255.0;
  34180. var g = options.buffer[pos + 1] / 255.0;
  34181. var b = options.buffer[pos + 2] / 255.0;
  34182. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34183. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34184. // Add vertex
  34185. positions.push(position.x, position.y, position.z);
  34186. normals.push(0, 0, 0);
  34187. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34188. }
  34189. }
  34190. // Indices
  34191. for (row = 0; row < options.subdivisions; row++) {
  34192. for (col = 0; col < options.subdivisions; col++) {
  34193. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34194. indices.push(col + 1 + row * (options.subdivisions + 1));
  34195. indices.push(col + row * (options.subdivisions + 1));
  34196. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34197. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34198. indices.push(col + row * (options.subdivisions + 1));
  34199. }
  34200. }
  34201. // Normals
  34202. VertexData.ComputeNormals(positions, indices, normals);
  34203. // Result
  34204. var vertexData = new VertexData();
  34205. vertexData.indices = indices;
  34206. vertexData.positions = positions;
  34207. vertexData.normals = normals;
  34208. vertexData.uvs = uvs;
  34209. return vertexData;
  34210. };
  34211. /**
  34212. * Creates the VertexData of the Plane.
  34213. */
  34214. VertexData.CreatePlane = function (options) {
  34215. var indices = [];
  34216. var positions = [];
  34217. var normals = [];
  34218. var uvs = [];
  34219. var width = options.width || options.size || 1;
  34220. var height = options.height || options.size || 1;
  34221. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34222. // Vertices
  34223. var halfWidth = width / 2.0;
  34224. var halfHeight = height / 2.0;
  34225. positions.push(-halfWidth, -halfHeight, 0);
  34226. normals.push(0, 0, -1.0);
  34227. uvs.push(0.0, 0.0);
  34228. positions.push(halfWidth, -halfHeight, 0);
  34229. normals.push(0, 0, -1.0);
  34230. uvs.push(1.0, 0.0);
  34231. positions.push(halfWidth, halfHeight, 0);
  34232. normals.push(0, 0, -1.0);
  34233. uvs.push(1.0, 1.0);
  34234. positions.push(-halfWidth, halfHeight, 0);
  34235. normals.push(0, 0, -1.0);
  34236. uvs.push(0.0, 1.0);
  34237. // Indices
  34238. indices.push(0);
  34239. indices.push(1);
  34240. indices.push(2);
  34241. indices.push(0);
  34242. indices.push(2);
  34243. indices.push(3);
  34244. // Sides
  34245. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34246. // Result
  34247. var vertexData = new VertexData();
  34248. vertexData.indices = indices;
  34249. vertexData.positions = positions;
  34250. vertexData.normals = normals;
  34251. vertexData.uvs = uvs;
  34252. return vertexData;
  34253. };
  34254. /**
  34255. * Creates the VertexData of the Disc or regular Polygon.
  34256. */
  34257. VertexData.CreateDisc = function (options) {
  34258. var positions = new Array();
  34259. var indices = new Array();
  34260. var normals = new Array();
  34261. var uvs = new Array();
  34262. var radius = options.radius || 0.5;
  34263. var tessellation = options.tessellation || 64;
  34264. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34265. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34266. // positions and uvs
  34267. positions.push(0, 0, 0); // disc center first
  34268. uvs.push(0.5, 0.5);
  34269. var theta = Math.PI * 2 * arc;
  34270. var step = theta / tessellation;
  34271. for (var a = 0; a < theta; a += step) {
  34272. var x = Math.cos(a);
  34273. var y = Math.sin(a);
  34274. var u = (x + 1) / 2;
  34275. var v = (1 - y) / 2;
  34276. positions.push(radius * x, radius * y, 0);
  34277. uvs.push(u, v);
  34278. }
  34279. if (arc === 1) {
  34280. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34281. uvs.push(uvs[2], uvs[3]);
  34282. }
  34283. //indices
  34284. var vertexNb = positions.length / 3;
  34285. for (var i = 1; i < vertexNb - 1; i++) {
  34286. indices.push(i + 1, 0, i);
  34287. }
  34288. // result
  34289. VertexData.ComputeNormals(positions, indices, normals);
  34290. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34291. var vertexData = new VertexData();
  34292. vertexData.indices = indices;
  34293. vertexData.positions = positions;
  34294. vertexData.normals = normals;
  34295. vertexData.uvs = uvs;
  34296. return vertexData;
  34297. };
  34298. /**
  34299. * Re-creates the VertexData of the Polygon for sideOrientation.
  34300. */
  34301. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34302. var faceUV = fUV || new Array(3);
  34303. var faceColors = fColors;
  34304. var colors = [];
  34305. // default face colors and UV if undefined
  34306. for (var f = 0; f < 3; f++) {
  34307. if (faceUV[f] === undefined) {
  34308. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34309. }
  34310. if (faceColors && faceColors[f] === undefined) {
  34311. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34312. }
  34313. }
  34314. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34315. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34316. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34317. var indices = polygon.getIndices();
  34318. // set face colours and textures
  34319. var idx = 0;
  34320. var face = 0;
  34321. for (var index = 0; index < normals.length; index += 3) {
  34322. //Edge Face no. 1
  34323. if (Math.abs(normals[index + 1]) < 0.001) {
  34324. face = 1;
  34325. }
  34326. //Top Face no. 0
  34327. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34328. face = 0;
  34329. }
  34330. //Bottom Face no. 2
  34331. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34332. face = 2;
  34333. }
  34334. idx = index / 3;
  34335. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34336. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34337. if (faceColors) {
  34338. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34339. }
  34340. }
  34341. // sides
  34342. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34343. // Result
  34344. var vertexData = new VertexData();
  34345. vertexData.indices = indices;
  34346. vertexData.positions = positions;
  34347. vertexData.normals = normals;
  34348. vertexData.uvs = uvs;
  34349. if (faceColors) {
  34350. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34351. vertexData.colors = totalColors;
  34352. }
  34353. return vertexData;
  34354. };
  34355. /**
  34356. * Creates the VertexData of the IcoSphere.
  34357. */
  34358. VertexData.CreateIcoSphere = function (options) {
  34359. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34360. var radius = options.radius || 1;
  34361. var flat = (options.flat === undefined) ? true : options.flat;
  34362. var subdivisions = options.subdivisions || 4;
  34363. var radiusX = options.radiusX || radius;
  34364. var radiusY = options.radiusY || radius;
  34365. var radiusZ = options.radiusZ || radius;
  34366. var t = (1 + Math.sqrt(5)) / 2;
  34367. // 12 vertex x,y,z
  34368. var ico_vertices = [
  34369. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34370. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34371. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34372. ];
  34373. // index of 3 vertex makes a face of icopshere
  34374. var ico_indices = [
  34375. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34376. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34377. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34378. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34379. ];
  34380. // vertex for uv have aliased position, not for UV
  34381. var vertices_unalias_id = [
  34382. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34383. // vertex alias
  34384. 0,
  34385. 2,
  34386. 3,
  34387. 3,
  34388. 3,
  34389. 4,
  34390. 7,
  34391. 8,
  34392. 9,
  34393. 9,
  34394. 10,
  34395. 11 // 23: B + 12
  34396. ];
  34397. // uv as integer step (not pixels !)
  34398. var ico_vertexuv = [
  34399. 5, 1, 3, 1, 6, 4, 0, 0,
  34400. 5, 3, 4, 2, 2, 2, 4, 0,
  34401. 2, 0, 1, 1, 6, 0, 6, 2,
  34402. // vertex alias (for same vertex on different faces)
  34403. 0, 4,
  34404. 3, 3,
  34405. 4, 4,
  34406. 3, 1,
  34407. 4, 2,
  34408. 4, 4,
  34409. 0, 2,
  34410. 1, 1,
  34411. 2, 2,
  34412. 3, 3,
  34413. 1, 3,
  34414. 2, 4 // 23: B + 12
  34415. ];
  34416. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34417. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34418. // First island of uv mapping
  34419. // v = 4h 3+ 2
  34420. // v = 3h 9+ 4
  34421. // v = 2h 9+ 5 B
  34422. // v = 1h 9 1 0
  34423. // v = 0h 3 8 7 A
  34424. // u = 0 1 2 3 4 5 6 *a
  34425. // Second island of uv mapping
  34426. // v = 4h 0+ B+ 4+
  34427. // v = 3h A+ 2+
  34428. // v = 2h 7+ 6 3+
  34429. // v = 1h 8+ 3+
  34430. // v = 0h
  34431. // u = 0 1 2 3 4 5 6 *a
  34432. // Face layout on texture UV mapping
  34433. // ============
  34434. // \ 4 /\ 16 / ======
  34435. // \ / \ / /\ 11 /
  34436. // \/ 7 \/ / \ /
  34437. // ======= / 10 \/
  34438. // /\ 17 /\ =======
  34439. // / \ / \ \ 15 /\
  34440. // / 8 \/ 12 \ \ / \
  34441. // ============ \/ 6 \
  34442. // \ 18 /\ ============
  34443. // \ / \ \ 5 /\ 0 /
  34444. // \/ 13 \ \ / \ /
  34445. // ======= \/ 1 \/
  34446. // =============
  34447. // /\ 19 /\ 2 /\
  34448. // / \ / \ / \
  34449. // / 14 \/ 9 \/ 3 \
  34450. // ===================
  34451. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34452. var ustep = 138 / 1024;
  34453. var vstep = 239 / 1024;
  34454. var uoffset = 60 / 1024;
  34455. var voffset = 26 / 1024;
  34456. // Second island should have margin, not to touch the first island
  34457. // avoid any borderline artefact in pixel rounding
  34458. var island_u_offset = -40 / 1024;
  34459. var island_v_offset = +20 / 1024;
  34460. // face is either island 0 or 1 :
  34461. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34462. var island = [
  34463. 0, 0, 0, 0, 1,
  34464. 0, 0, 1, 1, 0,
  34465. 0, 0, 1, 1, 0,
  34466. 0, 1, 1, 1, 0 // 15 - 19
  34467. ];
  34468. var indices = new Array();
  34469. var positions = new Array();
  34470. var normals = new Array();
  34471. var uvs = new Array();
  34472. var current_indice = 0;
  34473. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34474. var face_vertex_pos = new Array(3);
  34475. var face_vertex_uv = new Array(3);
  34476. var v012;
  34477. for (v012 = 0; v012 < 3; v012++) {
  34478. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34479. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34480. }
  34481. // create all with normals
  34482. for (var face = 0; face < 20; face++) {
  34483. // 3 vertex per face
  34484. for (v012 = 0; v012 < 3; v012++) {
  34485. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34486. var v_id = ico_indices[3 * face + v012];
  34487. // vertex have 3D position (x,y,z)
  34488. 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]);
  34489. // Normalize to get normal, then scale to radius
  34490. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34491. // uv Coordinates from vertex ID
  34492. 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);
  34493. }
  34494. // Subdivide the face (interpolate pos, norm, uv)
  34495. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34496. // - norm is linear interpolation of vertex corner normal
  34497. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34498. // - uv is linear interpolation
  34499. //
  34500. // Topology is as below for sub-divide by 2
  34501. // vertex shown as v0,v1,v2
  34502. // interp index is i1 to progress in range [v0,v1[
  34503. // interp index is i2 to progress in range [v0,v2[
  34504. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34505. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34506. //
  34507. //
  34508. // i2 v2
  34509. // ^ ^
  34510. // / / \
  34511. // / / \
  34512. // / / \
  34513. // / / (0,1) \
  34514. // / #---------\
  34515. // / / \ (0,0)'/ \
  34516. // / / \ / \
  34517. // / / \ / \
  34518. // / / (0,0) \ / (1,0) \
  34519. // / #---------#---------\
  34520. // v0 v1
  34521. //
  34522. // --------------------> i1
  34523. //
  34524. // interp of (i1,i2):
  34525. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34526. // along i1 : lerp(x0,x1, i1/(S-i2))
  34527. //
  34528. // centroid of triangle is needed to get help normal computation
  34529. // (c1,c2) are used for centroid location
  34530. var interp_vertex = function (i1, i2, c1, c2) {
  34531. // vertex is interpolated from
  34532. // - face_vertex_pos[0..2]
  34533. // - face_vertex_uv[0..2]
  34534. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34535. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34536. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34537. pos_interp.normalize();
  34538. var vertex_normal;
  34539. if (flat) {
  34540. // in flat mode, recalculate normal as face centroid normal
  34541. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34542. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34543. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34544. }
  34545. else {
  34546. // in smooth mode, recalculate normal from each single vertex position
  34547. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34548. }
  34549. // Vertex normal need correction due to X,Y,Z radius scaling
  34550. vertex_normal.x /= radiusX;
  34551. vertex_normal.y /= radiusY;
  34552. vertex_normal.z /= radiusZ;
  34553. vertex_normal.normalize();
  34554. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34555. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34556. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34557. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34558. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34559. uvs.push(uv_interp.x, uv_interp.y);
  34560. // push each vertex has member of a face
  34561. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34562. indices.push(current_indice);
  34563. current_indice++;
  34564. };
  34565. for (var i2 = 0; i2 < subdivisions; i2++) {
  34566. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34567. // face : (i1,i2) for /\ :
  34568. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34569. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34570. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34571. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34572. if (i1 + i2 + 1 < subdivisions) {
  34573. // face : (i1,i2)' for \/ :
  34574. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34575. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34576. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34577. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34578. }
  34579. }
  34580. }
  34581. }
  34582. // Sides
  34583. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34584. // Result
  34585. var vertexData = new VertexData();
  34586. vertexData.indices = indices;
  34587. vertexData.positions = positions;
  34588. vertexData.normals = normals;
  34589. vertexData.uvs = uvs;
  34590. return vertexData;
  34591. };
  34592. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34593. /**
  34594. * Creates the VertexData of the Polyhedron.
  34595. */
  34596. VertexData.CreatePolyhedron = function (options) {
  34597. // provided polyhedron types :
  34598. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34599. // 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)
  34600. var polyhedra = [];
  34601. 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]] };
  34602. 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]] };
  34603. polyhedra[2] = {
  34604. 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]],
  34605. 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]]
  34606. };
  34607. polyhedra[3] = {
  34608. 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]],
  34609. 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]]
  34610. };
  34611. polyhedra[4] = {
  34612. 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]],
  34613. 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]]
  34614. };
  34615. 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]] };
  34616. 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]] };
  34617. 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]] };
  34618. 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]] };
  34619. 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]] };
  34620. 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]] };
  34621. 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]] };
  34622. 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]] };
  34623. 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]] };
  34624. polyhedra[14] = {
  34625. 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]],
  34626. 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]]
  34627. };
  34628. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34629. var size = options.size;
  34630. var sizeX = options.sizeX || size || 1;
  34631. var sizeY = options.sizeY || size || 1;
  34632. var sizeZ = options.sizeZ || size || 1;
  34633. var data = options.custom || polyhedra[type];
  34634. var nbfaces = data.face.length;
  34635. var faceUV = options.faceUV || new Array(nbfaces);
  34636. var faceColors = options.faceColors;
  34637. var flat = (options.flat === undefined) ? true : options.flat;
  34638. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34639. var positions = new Array();
  34640. var indices = new Array();
  34641. var normals = new Array();
  34642. var uvs = new Array();
  34643. var colors = new Array();
  34644. var index = 0;
  34645. var faceIdx = 0; // face cursor in the array "indexes"
  34646. var indexes = new Array();
  34647. var i = 0;
  34648. var f = 0;
  34649. var u, v, ang, x, y, tmp;
  34650. // default face colors and UV if undefined
  34651. if (flat) {
  34652. for (f = 0; f < nbfaces; f++) {
  34653. if (faceColors && faceColors[f] === undefined) {
  34654. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34655. }
  34656. if (faceUV && faceUV[f] === undefined) {
  34657. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34658. }
  34659. }
  34660. }
  34661. if (!flat) {
  34662. for (i = 0; i < data.vertex.length; i++) {
  34663. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34664. uvs.push(0, 0);
  34665. }
  34666. for (f = 0; f < nbfaces; f++) {
  34667. for (i = 0; i < data.face[f].length - 2; i++) {
  34668. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34669. }
  34670. }
  34671. }
  34672. else {
  34673. for (f = 0; f < nbfaces; f++) {
  34674. var fl = data.face[f].length; // number of vertices of the current face
  34675. ang = 2 * Math.PI / fl;
  34676. x = 0.5 * Math.tan(ang / 2);
  34677. y = 0.5;
  34678. // positions, uvs, colors
  34679. for (i = 0; i < fl; i++) {
  34680. // positions
  34681. 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);
  34682. indexes.push(index);
  34683. index++;
  34684. // uvs
  34685. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34686. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34687. uvs.push(u, v);
  34688. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34689. y = x * Math.sin(ang) + y * Math.cos(ang);
  34690. x = tmp;
  34691. // colors
  34692. if (faceColors) {
  34693. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34694. }
  34695. }
  34696. // indices from indexes
  34697. for (i = 0; i < fl - 2; i++) {
  34698. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34699. }
  34700. faceIdx += fl;
  34701. }
  34702. }
  34703. VertexData.ComputeNormals(positions, indices, normals);
  34704. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34705. var vertexData = new VertexData();
  34706. vertexData.positions = positions;
  34707. vertexData.indices = indices;
  34708. vertexData.normals = normals;
  34709. vertexData.uvs = uvs;
  34710. if (faceColors && flat) {
  34711. vertexData.colors = colors;
  34712. }
  34713. return vertexData;
  34714. };
  34715. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34716. /**
  34717. * Creates the VertexData of the Torus Knot.
  34718. */
  34719. VertexData.CreateTorusKnot = function (options) {
  34720. var indices = new Array();
  34721. var positions = new Array();
  34722. var normals = new Array();
  34723. var uvs = new Array();
  34724. var radius = options.radius || 2;
  34725. var tube = options.tube || 0.5;
  34726. var radialSegments = options.radialSegments || 32;
  34727. var tubularSegments = options.tubularSegments || 32;
  34728. var p = options.p || 2;
  34729. var q = options.q || 3;
  34730. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34731. // Helper
  34732. var getPos = function (angle) {
  34733. var cu = Math.cos(angle);
  34734. var su = Math.sin(angle);
  34735. var quOverP = q / p * angle;
  34736. var cs = Math.cos(quOverP);
  34737. var tx = radius * (2 + cs) * 0.5 * cu;
  34738. var ty = radius * (2 + cs) * su * 0.5;
  34739. var tz = radius * Math.sin(quOverP) * 0.5;
  34740. return new BABYLON.Vector3(tx, ty, tz);
  34741. };
  34742. // Vertices
  34743. var i;
  34744. var j;
  34745. for (i = 0; i <= radialSegments; i++) {
  34746. var modI = i % radialSegments;
  34747. var u = modI / radialSegments * 2 * p * Math.PI;
  34748. var p1 = getPos(u);
  34749. var p2 = getPos(u + 0.01);
  34750. var tang = p2.subtract(p1);
  34751. var n = p2.add(p1);
  34752. var bitan = BABYLON.Vector3.Cross(tang, n);
  34753. n = BABYLON.Vector3.Cross(bitan, tang);
  34754. bitan.normalize();
  34755. n.normalize();
  34756. for (j = 0; j < tubularSegments; j++) {
  34757. var modJ = j % tubularSegments;
  34758. var v = modJ / tubularSegments * 2 * Math.PI;
  34759. var cx = -tube * Math.cos(v);
  34760. var cy = tube * Math.sin(v);
  34761. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34762. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34763. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34764. uvs.push(i / radialSegments);
  34765. uvs.push(j / tubularSegments);
  34766. }
  34767. }
  34768. for (i = 0; i < radialSegments; i++) {
  34769. for (j = 0; j < tubularSegments; j++) {
  34770. var jNext = (j + 1) % tubularSegments;
  34771. var a = i * tubularSegments + j;
  34772. var b = (i + 1) * tubularSegments + j;
  34773. var c = (i + 1) * tubularSegments + jNext;
  34774. var d = i * tubularSegments + jNext;
  34775. indices.push(d);
  34776. indices.push(b);
  34777. indices.push(a);
  34778. indices.push(d);
  34779. indices.push(c);
  34780. indices.push(b);
  34781. }
  34782. }
  34783. // Normals
  34784. VertexData.ComputeNormals(positions, indices, normals);
  34785. // Sides
  34786. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34787. // Result
  34788. var vertexData = new VertexData();
  34789. vertexData.indices = indices;
  34790. vertexData.positions = positions;
  34791. vertexData.normals = normals;
  34792. vertexData.uvs = uvs;
  34793. return vertexData;
  34794. };
  34795. // Tools
  34796. /**
  34797. * @param {any} - positions (number[] or Float32Array)
  34798. * @param {any} - indices (number[] or Uint16Array)
  34799. * @param {any} - normals (number[] or Float32Array)
  34800. * options (optional) :
  34801. * facetPositions : optional array of facet positions (vector3)
  34802. * facetNormals : optional array of facet normals (vector3)
  34803. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34804. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34805. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34806. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34807. * bInfo : optional bounding info, required for facetPartitioning computation
  34808. * useRightHandedSystem: optional boolean to for right handed system computation
  34809. * depthSort : optional boolean to enable the facet depth sort computation
  34810. * distanceTo : optional Vector3 to compute the facet depth from this location
  34811. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34812. */
  34813. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34814. // temporary scalar variables
  34815. var index = 0; // facet index
  34816. var p1p2x = 0.0; // p1p2 vector x coordinate
  34817. var p1p2y = 0.0; // p1p2 vector y coordinate
  34818. var p1p2z = 0.0; // p1p2 vector z coordinate
  34819. var p3p2x = 0.0; // p3p2 vector x coordinate
  34820. var p3p2y = 0.0; // p3p2 vector y coordinate
  34821. var p3p2z = 0.0; // p3p2 vector z coordinate
  34822. var faceNormalx = 0.0; // facet normal x coordinate
  34823. var faceNormaly = 0.0; // facet normal y coordinate
  34824. var faceNormalz = 0.0; // facet normal z coordinate
  34825. var length = 0.0; // facet normal length before normalization
  34826. var v1x = 0; // vector1 x index in the positions array
  34827. var v1y = 0; // vector1 y index in the positions array
  34828. var v1z = 0; // vector1 z index in the positions array
  34829. var v2x = 0; // vector2 x index in the positions array
  34830. var v2y = 0; // vector2 y index in the positions array
  34831. var v2z = 0; // vector2 z index in the positions array
  34832. var v3x = 0; // vector3 x index in the positions array
  34833. var v3y = 0; // vector3 y index in the positions array
  34834. var v3z = 0; // vector3 z index in the positions array
  34835. var computeFacetNormals = false;
  34836. var computeFacetPositions = false;
  34837. var computeFacetPartitioning = false;
  34838. var computeDepthSort = false;
  34839. var faceNormalSign = 1;
  34840. var ratio = 0;
  34841. var distanceTo = null;
  34842. if (options) {
  34843. computeFacetNormals = (options.facetNormals) ? true : false;
  34844. computeFacetPositions = (options.facetPositions) ? true : false;
  34845. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34846. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34847. ratio = options.ratio || 0;
  34848. computeDepthSort = (options.depthSort) ? true : false;
  34849. distanceTo = (options.distanceTo);
  34850. if (computeDepthSort) {
  34851. if (distanceTo === undefined) {
  34852. distanceTo = BABYLON.Vector3.Zero();
  34853. }
  34854. var depthSortedFacets = options.depthSortedFacets;
  34855. }
  34856. }
  34857. // facetPartitioning reinit if needed
  34858. var xSubRatio = 0;
  34859. var ySubRatio = 0;
  34860. var zSubRatio = 0;
  34861. var subSq = 0;
  34862. if (computeFacetPartitioning && options && options.bbSize) {
  34863. var ox = 0; // X partitioning index for facet position
  34864. var oy = 0; // Y partinioning index for facet position
  34865. var oz = 0; // Z partinioning index for facet position
  34866. var b1x = 0; // X partitioning index for facet v1 vertex
  34867. var b1y = 0; // Y partitioning index for facet v1 vertex
  34868. var b1z = 0; // z partitioning index for facet v1 vertex
  34869. var b2x = 0; // X partitioning index for facet v2 vertex
  34870. var b2y = 0; // Y partitioning index for facet v2 vertex
  34871. var b2z = 0; // Z partitioning index for facet v2 vertex
  34872. var b3x = 0; // X partitioning index for facet v3 vertex
  34873. var b3y = 0; // Y partitioning index for facet v3 vertex
  34874. var b3z = 0; // Z partitioning index for facet v3 vertex
  34875. var block_idx_o = 0; // facet barycenter block index
  34876. var block_idx_v1 = 0; // v1 vertex block index
  34877. var block_idx_v2 = 0; // v2 vertex block index
  34878. var block_idx_v3 = 0; // v3 vertex block index
  34879. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34880. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34881. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34882. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34883. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34884. subSq = options.subDiv.max * options.subDiv.max;
  34885. options.facetPartitioning.length = 0;
  34886. }
  34887. // reset the normals
  34888. for (index = 0; index < positions.length; index++) {
  34889. normals[index] = 0.0;
  34890. }
  34891. // Loop : 1 indice triplet = 1 facet
  34892. var nbFaces = (indices.length / 3) | 0;
  34893. for (index = 0; index < nbFaces; index++) {
  34894. // get the indexes of the coordinates of each vertex of the facet
  34895. v1x = indices[index * 3] * 3;
  34896. v1y = v1x + 1;
  34897. v1z = v1x + 2;
  34898. v2x = indices[index * 3 + 1] * 3;
  34899. v2y = v2x + 1;
  34900. v2z = v2x + 2;
  34901. v3x = indices[index * 3 + 2] * 3;
  34902. v3y = v3x + 1;
  34903. v3z = v3x + 2;
  34904. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34905. p1p2y = positions[v1y] - positions[v2y];
  34906. p1p2z = positions[v1z] - positions[v2z];
  34907. p3p2x = positions[v3x] - positions[v2x];
  34908. p3p2y = positions[v3y] - positions[v2y];
  34909. p3p2z = positions[v3z] - positions[v2z];
  34910. // compute the face normal with the cross product
  34911. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34912. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34913. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34914. // normalize this normal and store it in the array facetData
  34915. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34916. length = (length === 0) ? 1.0 : length;
  34917. faceNormalx /= length;
  34918. faceNormaly /= length;
  34919. faceNormalz /= length;
  34920. if (computeFacetNormals && options) {
  34921. options.facetNormals[index].x = faceNormalx;
  34922. options.facetNormals[index].y = faceNormaly;
  34923. options.facetNormals[index].z = faceNormalz;
  34924. }
  34925. if (computeFacetPositions && options) {
  34926. // compute and the facet barycenter coordinates in the array facetPositions
  34927. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34928. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34929. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34930. }
  34931. if (computeFacetPartitioning && options) {
  34932. // store the facet indexes in arrays in the main facetPartitioning array :
  34933. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34934. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34935. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34936. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34937. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34938. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34939. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34940. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34941. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34942. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34943. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34944. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34945. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34946. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34947. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34948. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34949. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34950. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34951. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34952. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34953. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34954. // push each facet index in each block containing the vertex
  34955. options.facetPartitioning[block_idx_v1].push(index);
  34956. if (block_idx_v2 != block_idx_v1) {
  34957. options.facetPartitioning[block_idx_v2].push(index);
  34958. }
  34959. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34960. options.facetPartitioning[block_idx_v3].push(index);
  34961. }
  34962. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34963. options.facetPartitioning[block_idx_o].push(index);
  34964. }
  34965. }
  34966. if (computeDepthSort && options && options.facetPositions) {
  34967. var dsf = depthSortedFacets[index];
  34968. dsf.ind = index * 3;
  34969. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34970. }
  34971. // compute the normals anyway
  34972. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34973. normals[v1y] += faceNormaly;
  34974. normals[v1z] += faceNormalz;
  34975. normals[v2x] += faceNormalx;
  34976. normals[v2y] += faceNormaly;
  34977. normals[v2z] += faceNormalz;
  34978. normals[v3x] += faceNormalx;
  34979. normals[v3y] += faceNormaly;
  34980. normals[v3z] += faceNormalz;
  34981. }
  34982. // last normalization of each normal
  34983. for (index = 0; index < normals.length / 3; index++) {
  34984. faceNormalx = normals[index * 3];
  34985. faceNormaly = normals[index * 3 + 1];
  34986. faceNormalz = normals[index * 3 + 2];
  34987. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34988. length = (length === 0) ? 1.0 : length;
  34989. faceNormalx /= length;
  34990. faceNormaly /= length;
  34991. faceNormalz /= length;
  34992. normals[index * 3] = faceNormalx;
  34993. normals[index * 3 + 1] = faceNormaly;
  34994. normals[index * 3 + 2] = faceNormalz;
  34995. }
  34996. };
  34997. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34998. var li = indices.length;
  34999. var ln = normals.length;
  35000. var i;
  35001. var n;
  35002. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35003. switch (sideOrientation) {
  35004. case BABYLON.Mesh.FRONTSIDE:
  35005. // nothing changed
  35006. break;
  35007. case BABYLON.Mesh.BACKSIDE:
  35008. var tmp;
  35009. // indices
  35010. for (i = 0; i < li; i += 3) {
  35011. tmp = indices[i];
  35012. indices[i] = indices[i + 2];
  35013. indices[i + 2] = tmp;
  35014. }
  35015. // normals
  35016. for (n = 0; n < ln; n++) {
  35017. normals[n] = -normals[n];
  35018. }
  35019. break;
  35020. case BABYLON.Mesh.DOUBLESIDE:
  35021. // positions
  35022. var lp = positions.length;
  35023. var l = lp / 3;
  35024. for (var p = 0; p < lp; p++) {
  35025. positions[lp + p] = positions[p];
  35026. }
  35027. // indices
  35028. for (i = 0; i < li; i += 3) {
  35029. indices[i + li] = indices[i + 2] + l;
  35030. indices[i + 1 + li] = indices[i + 1] + l;
  35031. indices[i + 2 + li] = indices[i] + l;
  35032. }
  35033. // normals
  35034. for (n = 0; n < ln; n++) {
  35035. normals[ln + n] = -normals[n];
  35036. }
  35037. // uvs
  35038. var lu = uvs.length;
  35039. var u = 0;
  35040. for (u = 0; u < lu; u++) {
  35041. uvs[u + lu] = uvs[u];
  35042. }
  35043. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35044. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35045. u = 0;
  35046. for (i = 0; i < lu / 2; i++) {
  35047. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35048. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35049. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35050. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35051. u += 2;
  35052. }
  35053. break;
  35054. }
  35055. };
  35056. /**
  35057. * Creates a new VertexData from the imported parameters.
  35058. */
  35059. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35060. var vertexData = new VertexData();
  35061. // positions
  35062. var positions = parsedVertexData.positions;
  35063. if (positions) {
  35064. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35065. }
  35066. // normals
  35067. var normals = parsedVertexData.normals;
  35068. if (normals) {
  35069. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35070. }
  35071. // tangents
  35072. var tangents = parsedVertexData.tangents;
  35073. if (tangents) {
  35074. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35075. }
  35076. // uvs
  35077. var uvs = parsedVertexData.uvs;
  35078. if (uvs) {
  35079. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35080. }
  35081. // uv2s
  35082. var uv2s = parsedVertexData.uv2s;
  35083. if (uv2s) {
  35084. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35085. }
  35086. // uv3s
  35087. var uv3s = parsedVertexData.uv3s;
  35088. if (uv3s) {
  35089. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35090. }
  35091. // uv4s
  35092. var uv4s = parsedVertexData.uv4s;
  35093. if (uv4s) {
  35094. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35095. }
  35096. // uv5s
  35097. var uv5s = parsedVertexData.uv5s;
  35098. if (uv5s) {
  35099. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35100. }
  35101. // uv6s
  35102. var uv6s = parsedVertexData.uv6s;
  35103. if (uv6s) {
  35104. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35105. }
  35106. // colors
  35107. var colors = parsedVertexData.colors;
  35108. if (colors) {
  35109. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35110. }
  35111. // matricesIndices
  35112. var matricesIndices = parsedVertexData.matricesIndices;
  35113. if (matricesIndices) {
  35114. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35115. }
  35116. // matricesWeights
  35117. var matricesWeights = parsedVertexData.matricesWeights;
  35118. if (matricesWeights) {
  35119. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35120. }
  35121. // indices
  35122. var indices = parsedVertexData.indices;
  35123. if (indices) {
  35124. vertexData.indices = indices;
  35125. }
  35126. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35127. };
  35128. return VertexData;
  35129. }());
  35130. BABYLON.VertexData = VertexData;
  35131. })(BABYLON || (BABYLON = {}));
  35132. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35133. "use strict";
  35134. var BABYLON;
  35135. (function (BABYLON) {
  35136. /**
  35137. * Class used to store geometry data (vertex buffers + index buffer)
  35138. */
  35139. var Geometry = /** @class */ (function () {
  35140. /**
  35141. * Creates a new geometry
  35142. * @param id defines the unique ID
  35143. * @param scene defines the hosting scene
  35144. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35145. * @param updatable defines if geometry must be updatable (false by default)
  35146. * @param mesh defines the mesh that will be associated with the geometry
  35147. */
  35148. function Geometry(id, scene, vertexData, updatable, mesh) {
  35149. if (updatable === void 0) { updatable = false; }
  35150. if (mesh === void 0) { mesh = null; }
  35151. /**
  35152. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35153. */
  35154. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35155. this._totalVertices = 0;
  35156. this._isDisposed = false;
  35157. this._indexBufferIsUpdatable = false;
  35158. this.id = id;
  35159. this._engine = scene.getEngine();
  35160. this._meshes = [];
  35161. this._scene = scene;
  35162. //Init vertex buffer cache
  35163. this._vertexBuffers = {};
  35164. this._indices = [];
  35165. this._updatable = updatable;
  35166. // vertexData
  35167. if (vertexData) {
  35168. this.setAllVerticesData(vertexData, updatable);
  35169. }
  35170. else {
  35171. this._totalVertices = 0;
  35172. this._indices = [];
  35173. }
  35174. if (this._engine.getCaps().vertexArrayObject) {
  35175. this._vertexArrayObjects = {};
  35176. }
  35177. // applyToMesh
  35178. if (mesh) {
  35179. if (mesh.getClassName() === "LinesMesh") {
  35180. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35181. this.updateExtend();
  35182. }
  35183. this.applyToMesh(mesh);
  35184. mesh.computeWorldMatrix(true);
  35185. }
  35186. }
  35187. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35188. /**
  35189. * 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
  35190. */
  35191. get: function () {
  35192. return this._boundingBias;
  35193. },
  35194. /**
  35195. * 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
  35196. */
  35197. set: function (value) {
  35198. if (this._boundingBias && this._boundingBias.equals(value)) {
  35199. return;
  35200. }
  35201. this._boundingBias = value.clone();
  35202. this.updateBoundingInfo(true, null);
  35203. },
  35204. enumerable: true,
  35205. configurable: true
  35206. });
  35207. /**
  35208. * Static function used to attach a new empty geometry to a mesh
  35209. * @param mesh defines the mesh to attach the geometry to
  35210. * @returns the new {BABYLON.Geometry}
  35211. */
  35212. Geometry.CreateGeometryForMesh = function (mesh) {
  35213. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35214. geometry.applyToMesh(mesh);
  35215. return geometry;
  35216. };
  35217. Object.defineProperty(Geometry.prototype, "extend", {
  35218. /**
  35219. * Gets the current extend of the geometry
  35220. */
  35221. get: function () {
  35222. return this._extend;
  35223. },
  35224. enumerable: true,
  35225. configurable: true
  35226. });
  35227. /**
  35228. * Gets the hosting scene
  35229. * @returns the hosting {BABYLON.Scene}
  35230. */
  35231. Geometry.prototype.getScene = function () {
  35232. return this._scene;
  35233. };
  35234. /**
  35235. * Gets the hosting engine
  35236. * @returns the hosting {BABYLON.Engine}
  35237. */
  35238. Geometry.prototype.getEngine = function () {
  35239. return this._engine;
  35240. };
  35241. /**
  35242. * Defines if the geometry is ready to use
  35243. * @returns true if the geometry is ready to be used
  35244. */
  35245. Geometry.prototype.isReady = function () {
  35246. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35247. };
  35248. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35249. /**
  35250. * Gets a value indicating that the geometry should not be serialized
  35251. */
  35252. get: function () {
  35253. for (var index = 0; index < this._meshes.length; index++) {
  35254. if (!this._meshes[index].doNotSerialize) {
  35255. return false;
  35256. }
  35257. }
  35258. return true;
  35259. },
  35260. enumerable: true,
  35261. configurable: true
  35262. });
  35263. /** @ignore */
  35264. Geometry.prototype._rebuild = function () {
  35265. if (this._vertexArrayObjects) {
  35266. this._vertexArrayObjects = {};
  35267. }
  35268. // Index buffer
  35269. if (this._meshes.length !== 0 && this._indices) {
  35270. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35271. }
  35272. // Vertex buffers
  35273. for (var key in this._vertexBuffers) {
  35274. var vertexBuffer = this._vertexBuffers[key];
  35275. vertexBuffer._rebuild();
  35276. }
  35277. };
  35278. /**
  35279. * Affects all gemetry data in one call
  35280. * @param vertexData defines the geometry data
  35281. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35282. */
  35283. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35284. vertexData.applyToGeometry(this, updatable);
  35285. this.notifyUpdate();
  35286. };
  35287. /**
  35288. * Set specific vertex data
  35289. * @param kind defines the data kind (Position, normal, etc...)
  35290. * @param data defines the vertex data to use
  35291. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35292. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35293. */
  35294. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35295. if (updatable === void 0) { updatable = false; }
  35296. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35297. this.setVerticesBuffer(buffer);
  35298. };
  35299. /**
  35300. * Removes a specific vertex data
  35301. * @param kind defines the data kind (Position, normal, etc...)
  35302. */
  35303. Geometry.prototype.removeVerticesData = function (kind) {
  35304. if (this._vertexBuffers[kind]) {
  35305. this._vertexBuffers[kind].dispose();
  35306. delete this._vertexBuffers[kind];
  35307. }
  35308. };
  35309. /**
  35310. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35311. * @param buffer defines the vertex buffer to use
  35312. */
  35313. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35314. var kind = buffer.getKind();
  35315. if (this._vertexBuffers[kind]) {
  35316. this._vertexBuffers[kind].dispose();
  35317. }
  35318. this._vertexBuffers[kind] = buffer;
  35319. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35320. var data = buffer.getData();
  35321. var stride = buffer.getStrideSize();
  35322. this._totalVertices = data.length / stride;
  35323. this.updateExtend(data, stride);
  35324. this._resetPointsArrayCache();
  35325. var meshes = this._meshes;
  35326. var numOfMeshes = meshes.length;
  35327. for (var index = 0; index < numOfMeshes; index++) {
  35328. var mesh = meshes[index];
  35329. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35330. mesh._createGlobalSubMesh(false);
  35331. mesh.computeWorldMatrix(true);
  35332. }
  35333. }
  35334. this.notifyUpdate(kind);
  35335. if (this._vertexArrayObjects) {
  35336. this._disposeVertexArrayObjects();
  35337. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35338. }
  35339. };
  35340. /**
  35341. * Update a specific vertex buffer
  35342. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35343. * It will do nothing if the buffer is not updatable
  35344. * @param kind defines the data kind (Position, normal, etc...)
  35345. * @param data defines the data to use
  35346. * @param offset defines the offset in the target buffer where to store the data
  35347. */
  35348. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35349. var vertexBuffer = this.getVertexBuffer(kind);
  35350. if (!vertexBuffer) {
  35351. return;
  35352. }
  35353. vertexBuffer.updateDirectly(data, offset);
  35354. this.notifyUpdate(kind);
  35355. };
  35356. /**
  35357. * Update a specific vertex buffer
  35358. * This function will create a new buffer if the current one is not updatable
  35359. * @param kind defines the data kind (Position, normal, etc...)
  35360. * @param data defines the data to use
  35361. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35362. */
  35363. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35364. if (updateExtends === void 0) { updateExtends = false; }
  35365. var vertexBuffer = this.getVertexBuffer(kind);
  35366. if (!vertexBuffer) {
  35367. return;
  35368. }
  35369. vertexBuffer.update(data);
  35370. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35371. var stride = vertexBuffer.getStrideSize();
  35372. this._totalVertices = data.length / stride;
  35373. this.updateBoundingInfo(updateExtends, data);
  35374. }
  35375. this.notifyUpdate(kind);
  35376. };
  35377. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35378. if (updateExtends) {
  35379. this.updateExtend(data);
  35380. }
  35381. var meshes = this._meshes;
  35382. var numOfMeshes = meshes.length;
  35383. this._resetPointsArrayCache();
  35384. for (var index = 0; index < numOfMeshes; index++) {
  35385. var mesh = meshes[index];
  35386. if (updateExtends) {
  35387. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35388. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35389. var subMesh = mesh.subMeshes[subIndex];
  35390. subMesh.refreshBoundingInfo();
  35391. }
  35392. }
  35393. }
  35394. };
  35395. /** @ignore */
  35396. Geometry.prototype._bind = function (effect, indexToBind) {
  35397. if (!effect) {
  35398. return;
  35399. }
  35400. if (indexToBind === undefined) {
  35401. indexToBind = this._indexBuffer;
  35402. }
  35403. var vbs = this.getVertexBuffers();
  35404. if (!vbs) {
  35405. return;
  35406. }
  35407. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35408. this._engine.bindBuffers(vbs, indexToBind, effect);
  35409. return;
  35410. }
  35411. // Using VAO
  35412. if (!this._vertexArrayObjects[effect.key]) {
  35413. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35414. }
  35415. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35416. };
  35417. /**
  35418. * Gets total number of vertices
  35419. * @returns the total number of vertices
  35420. */
  35421. Geometry.prototype.getTotalVertices = function () {
  35422. if (!this.isReady()) {
  35423. return 0;
  35424. }
  35425. return this._totalVertices;
  35426. };
  35427. /**
  35428. * Gets a specific vertex data attached to this geometry
  35429. * @param kind defines the data kind (Position, normal, etc...)
  35430. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35431. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35432. * @returns a float array containing vertex data
  35433. */
  35434. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35435. var vertexBuffer = this.getVertexBuffer(kind);
  35436. if (!vertexBuffer) {
  35437. return null;
  35438. }
  35439. var orig = vertexBuffer.getData();
  35440. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35441. return orig;
  35442. }
  35443. else {
  35444. var len = orig.length;
  35445. var copy = [];
  35446. for (var i = 0; i < len; i++) {
  35447. copy.push(orig[i]);
  35448. }
  35449. return copy;
  35450. }
  35451. };
  35452. /**
  35453. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35454. * @param kind defines the data kind (Position, normal, etc...)
  35455. * @returns true if the vertex buffer with the specified kind is updatable
  35456. */
  35457. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35458. var vb = this._vertexBuffers[kind];
  35459. if (!vb) {
  35460. return false;
  35461. }
  35462. return vb.isUpdatable();
  35463. };
  35464. /**
  35465. * Gets a specific vertex buffer
  35466. * @param kind defines the data kind (Position, normal, etc...)
  35467. * @returns a {BABYLON.VertexBuffer}
  35468. */
  35469. Geometry.prototype.getVertexBuffer = function (kind) {
  35470. if (!this.isReady()) {
  35471. return null;
  35472. }
  35473. return this._vertexBuffers[kind];
  35474. };
  35475. /**
  35476. * Returns all vertex buffers
  35477. * @return an object holding all vertex buffers indexed by kind
  35478. */
  35479. Geometry.prototype.getVertexBuffers = function () {
  35480. if (!this.isReady()) {
  35481. return null;
  35482. }
  35483. return this._vertexBuffers;
  35484. };
  35485. /**
  35486. * Gets a boolean indicating if specific vertex buffer is present
  35487. * @param kind defines the data kind (Position, normal, etc...)
  35488. * @returns true if data is present
  35489. */
  35490. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35491. if (!this._vertexBuffers) {
  35492. if (this._delayInfo) {
  35493. return this._delayInfo.indexOf(kind) !== -1;
  35494. }
  35495. return false;
  35496. }
  35497. return this._vertexBuffers[kind] !== undefined;
  35498. };
  35499. /**
  35500. * Gets a list of all attached data kinds (Position, normal, etc...)
  35501. * @returns a list of string containing all kinds
  35502. */
  35503. Geometry.prototype.getVerticesDataKinds = function () {
  35504. var result = [];
  35505. var kind;
  35506. if (!this._vertexBuffers && this._delayInfo) {
  35507. for (kind in this._delayInfo) {
  35508. result.push(kind);
  35509. }
  35510. }
  35511. else {
  35512. for (kind in this._vertexBuffers) {
  35513. result.push(kind);
  35514. }
  35515. }
  35516. return result;
  35517. };
  35518. /**
  35519. * Update index buffer
  35520. * @param indices defines the indices to store in the index buffer
  35521. * @param offset defines the offset in the target buffer where to store the data
  35522. */
  35523. Geometry.prototype.updateIndices = function (indices, offset) {
  35524. if (!this._indexBuffer) {
  35525. return;
  35526. }
  35527. if (!this._indexBufferIsUpdatable) {
  35528. this.setIndices(indices, null, true);
  35529. }
  35530. else {
  35531. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35532. }
  35533. };
  35534. /**
  35535. * Creates a new index buffer
  35536. * @param indices defines the indices to store in the index buffer
  35537. * @param totalVertices defines the total number of vertices (could be null)
  35538. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35539. */
  35540. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35541. if (totalVertices === void 0) { totalVertices = null; }
  35542. if (updatable === void 0) { updatable = false; }
  35543. if (this._indexBuffer) {
  35544. this._engine._releaseBuffer(this._indexBuffer);
  35545. }
  35546. this._disposeVertexArrayObjects();
  35547. this._indices = indices;
  35548. this._indexBufferIsUpdatable = updatable;
  35549. if (this._meshes.length !== 0 && this._indices) {
  35550. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35551. }
  35552. if (totalVertices != undefined) {
  35553. this._totalVertices = totalVertices;
  35554. }
  35555. var meshes = this._meshes;
  35556. var numOfMeshes = meshes.length;
  35557. for (var index = 0; index < numOfMeshes; index++) {
  35558. meshes[index]._createGlobalSubMesh(true);
  35559. }
  35560. this.notifyUpdate();
  35561. };
  35562. /**
  35563. * Return the total number of indices
  35564. * @returns the total number of indices
  35565. */
  35566. Geometry.prototype.getTotalIndices = function () {
  35567. if (!this.isReady()) {
  35568. return 0;
  35569. }
  35570. return this._indices.length;
  35571. };
  35572. /**
  35573. * Gets the index buffer array
  35574. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35575. * @returns the index buffer array
  35576. */
  35577. Geometry.prototype.getIndices = function (copyWhenShared) {
  35578. if (!this.isReady()) {
  35579. return null;
  35580. }
  35581. var orig = this._indices;
  35582. if (!copyWhenShared || this._meshes.length === 1) {
  35583. return orig;
  35584. }
  35585. else {
  35586. var len = orig.length;
  35587. var copy = [];
  35588. for (var i = 0; i < len; i++) {
  35589. copy.push(orig[i]);
  35590. }
  35591. return copy;
  35592. }
  35593. };
  35594. /**
  35595. * Gets the index buffer
  35596. * @return the index buffer
  35597. */
  35598. Geometry.prototype.getIndexBuffer = function () {
  35599. if (!this.isReady()) {
  35600. return null;
  35601. }
  35602. return this._indexBuffer;
  35603. };
  35604. /** @ignore */
  35605. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35606. if (effect === void 0) { effect = null; }
  35607. if (!effect || !this._vertexArrayObjects) {
  35608. return;
  35609. }
  35610. if (this._vertexArrayObjects[effect.key]) {
  35611. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35612. delete this._vertexArrayObjects[effect.key];
  35613. }
  35614. };
  35615. /**
  35616. * Release the associated resources for a specific mesh
  35617. * @param mesh defines the source mesh
  35618. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35619. */
  35620. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35621. var meshes = this._meshes;
  35622. var index = meshes.indexOf(mesh);
  35623. if (index === -1) {
  35624. return;
  35625. }
  35626. meshes.splice(index, 1);
  35627. mesh._geometry = null;
  35628. if (meshes.length === 0 && shouldDispose) {
  35629. this.dispose();
  35630. }
  35631. };
  35632. /**
  35633. * Apply current geometry to a given mesh
  35634. * @param mesh defines the mesh to apply geometry to
  35635. */
  35636. Geometry.prototype.applyToMesh = function (mesh) {
  35637. if (mesh._geometry === this) {
  35638. return;
  35639. }
  35640. var previousGeometry = mesh._geometry;
  35641. if (previousGeometry) {
  35642. previousGeometry.releaseForMesh(mesh);
  35643. }
  35644. var meshes = this._meshes;
  35645. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35646. mesh._geometry = this;
  35647. this._scene.pushGeometry(this);
  35648. meshes.push(mesh);
  35649. if (this.isReady()) {
  35650. this._applyToMesh(mesh);
  35651. }
  35652. else {
  35653. mesh._boundingInfo = this._boundingInfo;
  35654. }
  35655. };
  35656. Geometry.prototype.updateExtend = function (data, stride) {
  35657. if (data === void 0) { data = null; }
  35658. if (!data) {
  35659. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35660. }
  35661. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35662. };
  35663. Geometry.prototype._applyToMesh = function (mesh) {
  35664. var numOfMeshes = this._meshes.length;
  35665. // vertexBuffers
  35666. for (var kind in this._vertexBuffers) {
  35667. if (numOfMeshes === 1) {
  35668. this._vertexBuffers[kind].create();
  35669. }
  35670. var buffer = this._vertexBuffers[kind].getBuffer();
  35671. if (buffer)
  35672. buffer.references = numOfMeshes;
  35673. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35674. if (!this._extend) {
  35675. this.updateExtend(this._vertexBuffers[kind].getData());
  35676. }
  35677. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35678. mesh._createGlobalSubMesh(false);
  35679. //bounding info was just created again, world matrix should be applied again.
  35680. mesh._updateBoundingInfo();
  35681. }
  35682. }
  35683. // indexBuffer
  35684. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35685. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35686. }
  35687. if (this._indexBuffer) {
  35688. this._indexBuffer.references = numOfMeshes;
  35689. }
  35690. };
  35691. Geometry.prototype.notifyUpdate = function (kind) {
  35692. if (this.onGeometryUpdated) {
  35693. this.onGeometryUpdated(this, kind);
  35694. }
  35695. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35696. var mesh = _a[_i];
  35697. mesh._markSubMeshesAsAttributesDirty();
  35698. }
  35699. };
  35700. /**
  35701. * Load the geometry if it was flagged as delay loaded
  35702. * @param scene defines the hosting scene
  35703. * @param onLoaded defines a callback called when the geometry is loaded
  35704. */
  35705. Geometry.prototype.load = function (scene, onLoaded) {
  35706. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35707. return;
  35708. }
  35709. if (this.isReady()) {
  35710. if (onLoaded) {
  35711. onLoaded();
  35712. }
  35713. return;
  35714. }
  35715. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35716. this._queueLoad(scene, onLoaded);
  35717. };
  35718. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35719. var _this = this;
  35720. if (!this.delayLoadingFile) {
  35721. return;
  35722. }
  35723. scene._addPendingData(this);
  35724. scene._loadFile(this.delayLoadingFile, function (data) {
  35725. if (!_this._delayLoadingFunction) {
  35726. return;
  35727. }
  35728. _this._delayLoadingFunction(JSON.parse(data), _this);
  35729. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35730. _this._delayInfo = [];
  35731. scene._removePendingData(_this);
  35732. var meshes = _this._meshes;
  35733. var numOfMeshes = meshes.length;
  35734. for (var index = 0; index < numOfMeshes; index++) {
  35735. _this._applyToMesh(meshes[index]);
  35736. }
  35737. if (onLoaded) {
  35738. onLoaded();
  35739. }
  35740. }, undefined, true);
  35741. };
  35742. /**
  35743. * Invert the geometry to move from a right handed system to a left handed one.
  35744. */
  35745. Geometry.prototype.toLeftHanded = function () {
  35746. // Flip faces
  35747. var tIndices = this.getIndices(false);
  35748. if (tIndices != null && tIndices.length > 0) {
  35749. for (var i = 0; i < tIndices.length; i += 3) {
  35750. var tTemp = tIndices[i + 0];
  35751. tIndices[i + 0] = tIndices[i + 2];
  35752. tIndices[i + 2] = tTemp;
  35753. }
  35754. this.setIndices(tIndices);
  35755. }
  35756. // Negate position.z
  35757. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35758. if (tPositions != null && tPositions.length > 0) {
  35759. for (var i = 0; i < tPositions.length; i += 3) {
  35760. tPositions[i + 2] = -tPositions[i + 2];
  35761. }
  35762. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35763. }
  35764. // Negate normal.z
  35765. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35766. if (tNormals != null && tNormals.length > 0) {
  35767. for (var i = 0; i < tNormals.length; i += 3) {
  35768. tNormals[i + 2] = -tNormals[i + 2];
  35769. }
  35770. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35771. }
  35772. };
  35773. // Cache
  35774. /** @ignore */
  35775. Geometry.prototype._resetPointsArrayCache = function () {
  35776. this._positions = null;
  35777. };
  35778. /** @ignore */
  35779. Geometry.prototype._generatePointsArray = function () {
  35780. if (this._positions)
  35781. return true;
  35782. this._positions = [];
  35783. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35784. if (!data) {
  35785. return false;
  35786. }
  35787. for (var index = 0; index < data.length; index += 3) {
  35788. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35789. }
  35790. return true;
  35791. };
  35792. /**
  35793. * Gets a value indicating if the geometry is disposed
  35794. * @returns true if the geometry was disposed
  35795. */
  35796. Geometry.prototype.isDisposed = function () {
  35797. return this._isDisposed;
  35798. };
  35799. Geometry.prototype._disposeVertexArrayObjects = function () {
  35800. if (this._vertexArrayObjects) {
  35801. for (var kind in this._vertexArrayObjects) {
  35802. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35803. }
  35804. this._vertexArrayObjects = {};
  35805. }
  35806. };
  35807. /**
  35808. * Free all associated resources
  35809. */
  35810. Geometry.prototype.dispose = function () {
  35811. var meshes = this._meshes;
  35812. var numOfMeshes = meshes.length;
  35813. var index;
  35814. for (index = 0; index < numOfMeshes; index++) {
  35815. this.releaseForMesh(meshes[index]);
  35816. }
  35817. this._meshes = [];
  35818. this._disposeVertexArrayObjects();
  35819. for (var kind in this._vertexBuffers) {
  35820. this._vertexBuffers[kind].dispose();
  35821. }
  35822. this._vertexBuffers = {};
  35823. this._totalVertices = 0;
  35824. if (this._indexBuffer) {
  35825. this._engine._releaseBuffer(this._indexBuffer);
  35826. }
  35827. this._indexBuffer = null;
  35828. this._indices = [];
  35829. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35830. this.delayLoadingFile = null;
  35831. this._delayLoadingFunction = null;
  35832. this._delayInfo = [];
  35833. this._boundingInfo = null;
  35834. this._scene.removeGeometry(this);
  35835. this._isDisposed = true;
  35836. };
  35837. /**
  35838. * Clone the current geometry into a new geometry
  35839. * @param id defines the unique ID of the new geometry
  35840. * @returns a new geometry object
  35841. */
  35842. Geometry.prototype.copy = function (id) {
  35843. var vertexData = new BABYLON.VertexData();
  35844. vertexData.indices = [];
  35845. var indices = this.getIndices();
  35846. if (indices) {
  35847. for (var index = 0; index < indices.length; index++) {
  35848. vertexData.indices.push(indices[index]);
  35849. }
  35850. }
  35851. var updatable = false;
  35852. var stopChecking = false;
  35853. var kind;
  35854. for (kind in this._vertexBuffers) {
  35855. // using slice() to make a copy of the array and not just reference it
  35856. var data = this.getVerticesData(kind);
  35857. if (data instanceof Float32Array) {
  35858. vertexData.set(new Float32Array(data), kind);
  35859. }
  35860. else {
  35861. vertexData.set(data.slice(0), kind);
  35862. }
  35863. if (!stopChecking) {
  35864. var vb = this.getVertexBuffer(kind);
  35865. if (vb) {
  35866. updatable = vb.isUpdatable();
  35867. stopChecking = !updatable;
  35868. }
  35869. }
  35870. }
  35871. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35872. geometry.delayLoadState = this.delayLoadState;
  35873. geometry.delayLoadingFile = this.delayLoadingFile;
  35874. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35875. for (kind in this._delayInfo) {
  35876. geometry._delayInfo = geometry._delayInfo || [];
  35877. geometry._delayInfo.push(kind);
  35878. }
  35879. // Bounding info
  35880. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35881. return geometry;
  35882. };
  35883. /**
  35884. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35885. * @return a JSON representation of the current geometry data (without the vertices data)
  35886. */
  35887. Geometry.prototype.serialize = function () {
  35888. var serializationObject = {};
  35889. serializationObject.id = this.id;
  35890. serializationObject.updatable = this._updatable;
  35891. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35892. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35893. }
  35894. return serializationObject;
  35895. };
  35896. Geometry.prototype.toNumberArray = function (origin) {
  35897. if (Array.isArray(origin)) {
  35898. return origin;
  35899. }
  35900. else {
  35901. return Array.prototype.slice.call(origin);
  35902. }
  35903. };
  35904. /**
  35905. * Serialize all vertices data into a JSON oject
  35906. * @returns a JSON representation of the current geometry data
  35907. */
  35908. Geometry.prototype.serializeVerticeData = function () {
  35909. var serializationObject = this.serialize();
  35910. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35911. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35912. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35913. serializationObject.positions._updatable = true;
  35914. }
  35915. }
  35916. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35917. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35918. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35919. serializationObject.normals._updatable = true;
  35920. }
  35921. }
  35922. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35923. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35924. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35925. serializationObject.tangets._updatable = true;
  35926. }
  35927. }
  35928. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35929. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35930. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35931. serializationObject.uvs._updatable = true;
  35932. }
  35933. }
  35934. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35935. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35936. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35937. serializationObject.uv2s._updatable = true;
  35938. }
  35939. }
  35940. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35941. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35942. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35943. serializationObject.uv3s._updatable = true;
  35944. }
  35945. }
  35946. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35947. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35948. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35949. serializationObject.uv4s._updatable = true;
  35950. }
  35951. }
  35952. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35953. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35954. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35955. serializationObject.uv5s._updatable = true;
  35956. }
  35957. }
  35958. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35959. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35960. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35961. serializationObject.uv6s._updatable = true;
  35962. }
  35963. }
  35964. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35965. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35966. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35967. serializationObject.colors._updatable = true;
  35968. }
  35969. }
  35970. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35971. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35972. serializationObject.matricesIndices._isExpanded = true;
  35973. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35974. serializationObject.matricesIndices._updatable = true;
  35975. }
  35976. }
  35977. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35978. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35979. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35980. serializationObject.matricesWeights._updatable = true;
  35981. }
  35982. }
  35983. serializationObject.indices = this.toNumberArray(this.getIndices());
  35984. return serializationObject;
  35985. };
  35986. // Statics
  35987. /**
  35988. * Extracts a clone of a mesh geometry
  35989. * @param mesh defines the source mesh
  35990. * @param id defines the unique ID of the new geometry object
  35991. * @returns the new geometry object
  35992. */
  35993. Geometry.ExtractFromMesh = function (mesh, id) {
  35994. var geometry = mesh._geometry;
  35995. if (!geometry) {
  35996. return null;
  35997. }
  35998. return geometry.copy(id);
  35999. };
  36000. /**
  36001. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36002. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36003. * Be aware Math.random() could cause collisions, but:
  36004. * "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"
  36005. * @returns a string containing a new GUID
  36006. */
  36007. Geometry.RandomId = function () {
  36008. return BABYLON.Tools.RandomId();
  36009. };
  36010. /** @ignore */
  36011. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  36012. var scene = mesh.getScene();
  36013. // Geometry
  36014. var geometryId = parsedGeometry.geometryId;
  36015. if (geometryId) {
  36016. var geometry = scene.getGeometryByID(geometryId);
  36017. if (geometry) {
  36018. geometry.applyToMesh(mesh);
  36019. }
  36020. }
  36021. else if (parsedGeometry instanceof ArrayBuffer) {
  36022. var binaryInfo = mesh._binaryInfo;
  36023. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36024. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36025. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36026. }
  36027. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36028. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36029. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36030. }
  36031. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36032. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36033. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36034. }
  36035. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36036. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36037. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36038. }
  36039. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36040. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36041. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36042. }
  36043. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36044. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36045. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36046. }
  36047. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36048. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36049. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36050. }
  36051. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36052. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36053. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36054. }
  36055. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36056. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36057. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36058. }
  36059. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36060. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36061. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36062. }
  36063. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36064. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36065. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36066. }
  36067. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36068. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36069. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36070. }
  36071. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36072. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36073. mesh.setIndices(indicesData, null);
  36074. }
  36075. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36076. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36077. mesh.subMeshes = [];
  36078. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36079. var materialIndex = subMeshesData[(i * 5) + 0];
  36080. var verticesStart = subMeshesData[(i * 5) + 1];
  36081. var verticesCount = subMeshesData[(i * 5) + 2];
  36082. var indexStart = subMeshesData[(i * 5) + 3];
  36083. var indexCount = subMeshesData[(i * 5) + 4];
  36084. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36085. }
  36086. }
  36087. }
  36088. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36089. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36090. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36091. if (parsedGeometry.tangents) {
  36092. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36093. }
  36094. if (parsedGeometry.uvs) {
  36095. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36096. }
  36097. if (parsedGeometry.uvs2) {
  36098. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36099. }
  36100. if (parsedGeometry.uvs3) {
  36101. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36102. }
  36103. if (parsedGeometry.uvs4) {
  36104. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36105. }
  36106. if (parsedGeometry.uvs5) {
  36107. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36108. }
  36109. if (parsedGeometry.uvs6) {
  36110. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36111. }
  36112. if (parsedGeometry.colors) {
  36113. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36114. }
  36115. if (parsedGeometry.matricesIndices) {
  36116. if (!parsedGeometry.matricesIndices._isExpanded) {
  36117. var floatIndices = [];
  36118. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36119. var matricesIndex = parsedGeometry.matricesIndices[i];
  36120. floatIndices.push(matricesIndex & 0x000000FF);
  36121. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36122. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36123. floatIndices.push(matricesIndex >> 24);
  36124. }
  36125. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36126. }
  36127. else {
  36128. delete parsedGeometry.matricesIndices._isExpanded;
  36129. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36130. }
  36131. }
  36132. if (parsedGeometry.matricesIndicesExtra) {
  36133. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36134. var floatIndices = [];
  36135. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36136. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36137. floatIndices.push(matricesIndex & 0x000000FF);
  36138. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36139. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36140. floatIndices.push(matricesIndex >> 24);
  36141. }
  36142. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36143. }
  36144. else {
  36145. delete parsedGeometry.matricesIndices._isExpanded;
  36146. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36147. }
  36148. }
  36149. if (parsedGeometry.matricesWeights) {
  36150. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36151. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36152. }
  36153. if (parsedGeometry.matricesWeightsExtra) {
  36154. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36155. }
  36156. mesh.setIndices(parsedGeometry.indices, null);
  36157. }
  36158. // SubMeshes
  36159. if (parsedGeometry.subMeshes) {
  36160. mesh.subMeshes = [];
  36161. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36162. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36163. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36164. }
  36165. }
  36166. // Flat shading
  36167. if (mesh._shouldGenerateFlatShading) {
  36168. mesh.convertToFlatShadedMesh();
  36169. delete mesh._shouldGenerateFlatShading;
  36170. }
  36171. // Update
  36172. mesh.computeWorldMatrix(true);
  36173. // Octree
  36174. var sceneOctree = scene.selectionOctree;
  36175. if (sceneOctree !== undefined && sceneOctree !== null) {
  36176. sceneOctree.addMesh(mesh);
  36177. }
  36178. };
  36179. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36180. var epsilon = 1e-3;
  36181. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36182. return;
  36183. }
  36184. var noInfluenceBoneIndex = 0.0;
  36185. if (parsedGeometry.skeletonId > -1) {
  36186. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36187. if (!skeleton) {
  36188. return;
  36189. }
  36190. noInfluenceBoneIndex = skeleton.bones.length;
  36191. }
  36192. else {
  36193. return;
  36194. }
  36195. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36196. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36197. var matricesWeights = parsedGeometry.matricesWeights;
  36198. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36199. var influencers = parsedGeometry.numBoneInfluencer;
  36200. var size = matricesWeights.length;
  36201. for (var i = 0; i < size; i += 4) {
  36202. var weight = 0.0;
  36203. var firstZeroWeight = -1;
  36204. for (var j = 0; j < 4; j++) {
  36205. var w = matricesWeights[i + j];
  36206. weight += w;
  36207. if (w < epsilon && firstZeroWeight < 0) {
  36208. firstZeroWeight = j;
  36209. }
  36210. }
  36211. if (matricesWeightsExtra) {
  36212. for (var j = 0; j < 4; j++) {
  36213. var w = matricesWeightsExtra[i + j];
  36214. weight += w;
  36215. if (w < epsilon && firstZeroWeight < 0) {
  36216. firstZeroWeight = j + 4;
  36217. }
  36218. }
  36219. }
  36220. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36221. firstZeroWeight = influencers - 1;
  36222. }
  36223. if (weight > epsilon) {
  36224. var mweight = 1.0 / weight;
  36225. for (var j = 0; j < 4; j++) {
  36226. matricesWeights[i + j] *= mweight;
  36227. }
  36228. if (matricesWeightsExtra) {
  36229. for (var j = 0; j < 4; j++) {
  36230. matricesWeightsExtra[i + j] *= mweight;
  36231. }
  36232. }
  36233. }
  36234. else {
  36235. if (firstZeroWeight >= 4) {
  36236. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36237. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36238. }
  36239. else {
  36240. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36241. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36242. }
  36243. }
  36244. }
  36245. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36246. if (parsedGeometry.matricesWeightsExtra) {
  36247. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36248. }
  36249. };
  36250. /**
  36251. * Create a new geometry from persisted data (Using .babylon file format)
  36252. * @param parsedVertexData defines the persisted data
  36253. * @param scene defines the hosting scene
  36254. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36255. * @returns the new geometry object
  36256. */
  36257. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36258. if (scene.getGeometryByID(parsedVertexData.id)) {
  36259. return null; // null since geometry could be something else than a box...
  36260. }
  36261. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36262. if (BABYLON.Tags) {
  36263. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36264. }
  36265. if (parsedVertexData.delayLoadingFile) {
  36266. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36267. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36268. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36269. geometry._delayInfo = [];
  36270. if (parsedVertexData.hasUVs) {
  36271. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36272. }
  36273. if (parsedVertexData.hasUVs2) {
  36274. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36275. }
  36276. if (parsedVertexData.hasUVs3) {
  36277. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36278. }
  36279. if (parsedVertexData.hasUVs4) {
  36280. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36281. }
  36282. if (parsedVertexData.hasUVs5) {
  36283. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36284. }
  36285. if (parsedVertexData.hasUVs6) {
  36286. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36287. }
  36288. if (parsedVertexData.hasColors) {
  36289. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36290. }
  36291. if (parsedVertexData.hasMatricesIndices) {
  36292. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36293. }
  36294. if (parsedVertexData.hasMatricesWeights) {
  36295. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36296. }
  36297. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36298. }
  36299. else {
  36300. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36301. }
  36302. scene.pushGeometry(geometry, true);
  36303. return geometry;
  36304. };
  36305. return Geometry;
  36306. }());
  36307. BABYLON.Geometry = Geometry;
  36308. // Primitives
  36309. /// Abstract class
  36310. /**
  36311. * Abstract class used to provide common services for all typed geometries
  36312. */
  36313. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36314. __extends(_PrimitiveGeometry, _super);
  36315. /**
  36316. * Creates a new typed geometry
  36317. * @param id defines the unique ID of the geometry
  36318. * @param scene defines the hosting scene
  36319. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36320. * @param mesh defines the hosting mesh (can be null)
  36321. */
  36322. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36323. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36324. if (mesh === void 0) { mesh = null; }
  36325. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36326. _this._canBeRegenerated = _canBeRegenerated;
  36327. _this._beingRegenerated = true;
  36328. _this.regenerate();
  36329. _this._beingRegenerated = false;
  36330. return _this;
  36331. }
  36332. /**
  36333. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36334. * @returns true if the geometry can be regenerated
  36335. */
  36336. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36337. return this._canBeRegenerated;
  36338. };
  36339. /**
  36340. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36341. */
  36342. _PrimitiveGeometry.prototype.regenerate = function () {
  36343. if (!this._canBeRegenerated) {
  36344. return;
  36345. }
  36346. this._beingRegenerated = true;
  36347. this.setAllVerticesData(this._regenerateVertexData(), false);
  36348. this._beingRegenerated = false;
  36349. };
  36350. /**
  36351. * Clone the geometry
  36352. * @param id defines the unique ID of the new geometry
  36353. * @returns the new geometry
  36354. */
  36355. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36356. return _super.prototype.copy.call(this, id);
  36357. };
  36358. // overrides
  36359. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36360. if (!this._beingRegenerated) {
  36361. return;
  36362. }
  36363. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36364. };
  36365. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36366. if (!this._beingRegenerated) {
  36367. return;
  36368. }
  36369. _super.prototype.setVerticesData.call(this, kind, data, false);
  36370. };
  36371. // to override
  36372. /** @ignore */
  36373. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36374. throw new Error("Abstract method");
  36375. };
  36376. _PrimitiveGeometry.prototype.copy = function (id) {
  36377. throw new Error("Must be overriden in sub-classes.");
  36378. };
  36379. _PrimitiveGeometry.prototype.serialize = function () {
  36380. var serializationObject = _super.prototype.serialize.call(this);
  36381. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36382. return serializationObject;
  36383. };
  36384. return _PrimitiveGeometry;
  36385. }(Geometry));
  36386. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36387. /**
  36388. * Creates a ribbon geometry
  36389. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36390. */
  36391. var RibbonGeometry = /** @class */ (function (_super) {
  36392. __extends(RibbonGeometry, _super);
  36393. /**
  36394. * Creates a ribbon geometry
  36395. * @param id defines the unique ID of the geometry
  36396. * @param scene defines the hosting scene
  36397. * @param pathArray defines the array of paths to use
  36398. * @param closeArray defines if the last path and the first path must be joined
  36399. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36400. * @param offset defines the offset between points
  36401. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36402. * @param mesh defines the hosting mesh (can be null)
  36403. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36404. */
  36405. function RibbonGeometry(id, scene,
  36406. /**
  36407. * Defines the array of paths to use
  36408. */
  36409. pathArray,
  36410. /**
  36411. * Defines if the last and first points of each path in your pathArray must be joined
  36412. */
  36413. closeArray,
  36414. /**
  36415. * Defines if the last and first points of each path in your pathArray must be joined
  36416. */
  36417. closePath,
  36418. /**
  36419. * Defines the offset between points
  36420. */
  36421. offset, canBeRegenerated, mesh,
  36422. /**
  36423. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36424. */
  36425. side) {
  36426. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36427. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36428. _this.pathArray = pathArray;
  36429. _this.closeArray = closeArray;
  36430. _this.closePath = closePath;
  36431. _this.offset = offset;
  36432. _this.side = side;
  36433. return _this;
  36434. }
  36435. /** @ignore */
  36436. RibbonGeometry.prototype._regenerateVertexData = function () {
  36437. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36438. };
  36439. RibbonGeometry.prototype.copy = function (id) {
  36440. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36441. };
  36442. return RibbonGeometry;
  36443. }(_PrimitiveGeometry));
  36444. BABYLON.RibbonGeometry = RibbonGeometry;
  36445. /**
  36446. * Creates a box geometry
  36447. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36448. */
  36449. var BoxGeometry = /** @class */ (function (_super) {
  36450. __extends(BoxGeometry, _super);
  36451. /**
  36452. * Creates a box geometry
  36453. * @param id defines the unique ID of the geometry
  36454. * @param scene defines the hosting scene
  36455. * @param size defines the zise of the box (width, height and depth are the same)
  36456. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36457. * @param mesh defines the hosting mesh (can be null)
  36458. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36459. */
  36460. function BoxGeometry(id, scene,
  36461. /**
  36462. * Defines the zise of the box (width, height and depth are the same)
  36463. */
  36464. size, canBeRegenerated, mesh,
  36465. /**
  36466. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36467. */
  36468. side) {
  36469. if (mesh === void 0) { mesh = null; }
  36470. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36471. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36472. _this.size = size;
  36473. _this.side = side;
  36474. return _this;
  36475. }
  36476. BoxGeometry.prototype._regenerateVertexData = function () {
  36477. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36478. };
  36479. BoxGeometry.prototype.copy = function (id) {
  36480. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36481. };
  36482. BoxGeometry.prototype.serialize = function () {
  36483. var serializationObject = _super.prototype.serialize.call(this);
  36484. serializationObject.size = this.size;
  36485. return serializationObject;
  36486. };
  36487. BoxGeometry.Parse = function (parsedBox, scene) {
  36488. if (scene.getGeometryByID(parsedBox.id)) {
  36489. return null; // null since geometry could be something else than a box...
  36490. }
  36491. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36492. if (BABYLON.Tags) {
  36493. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36494. }
  36495. scene.pushGeometry(box, true);
  36496. return box;
  36497. };
  36498. return BoxGeometry;
  36499. }(_PrimitiveGeometry));
  36500. BABYLON.BoxGeometry = BoxGeometry;
  36501. /**
  36502. * Creates a sphere geometry
  36503. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36504. */
  36505. var SphereGeometry = /** @class */ (function (_super) {
  36506. __extends(SphereGeometry, _super);
  36507. /**
  36508. * Create a new sphere geometry
  36509. * @param id defines the unique ID of the geometry
  36510. * @param scene defines the hosting scene
  36511. * @param segments defines the number of segments to use to create the sphere
  36512. * @param diameter defines the diameter of the sphere
  36513. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36514. * @param mesh defines the hosting mesh (can be null)
  36515. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36516. */
  36517. function SphereGeometry(id, scene,
  36518. /**
  36519. * Defines the number of segments to use to create the sphere
  36520. */
  36521. segments,
  36522. /**
  36523. * Defines the diameter of the sphere
  36524. */
  36525. diameter, canBeRegenerated, mesh,
  36526. /**
  36527. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36528. */
  36529. side) {
  36530. if (mesh === void 0) { mesh = null; }
  36531. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36532. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36533. _this.segments = segments;
  36534. _this.diameter = diameter;
  36535. _this.side = side;
  36536. return _this;
  36537. }
  36538. SphereGeometry.prototype._regenerateVertexData = function () {
  36539. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36540. };
  36541. SphereGeometry.prototype.copy = function (id) {
  36542. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36543. };
  36544. SphereGeometry.prototype.serialize = function () {
  36545. var serializationObject = _super.prototype.serialize.call(this);
  36546. serializationObject.segments = this.segments;
  36547. serializationObject.diameter = this.diameter;
  36548. return serializationObject;
  36549. };
  36550. SphereGeometry.Parse = function (parsedSphere, scene) {
  36551. if (scene.getGeometryByID(parsedSphere.id)) {
  36552. return null; // null since geometry could be something else than a sphere...
  36553. }
  36554. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36555. if (BABYLON.Tags) {
  36556. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36557. }
  36558. scene.pushGeometry(sphere, true);
  36559. return sphere;
  36560. };
  36561. return SphereGeometry;
  36562. }(_PrimitiveGeometry));
  36563. BABYLON.SphereGeometry = SphereGeometry;
  36564. /**
  36565. * Creates a disc geometry
  36566. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36567. */
  36568. var DiscGeometry = /** @class */ (function (_super) {
  36569. __extends(DiscGeometry, _super);
  36570. /**
  36571. * Creates a new disc geometry
  36572. * @param id defines the unique ID of the geometry
  36573. * @param scene defines the hosting scene
  36574. * @param radius defines the radius of the disc
  36575. * @param tessellation defines the tesselation factor to apply to the disc
  36576. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36577. * @param mesh defines the hosting mesh (can be null)
  36578. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36579. */
  36580. function DiscGeometry(id, scene,
  36581. /**
  36582. * Defines the radius of the disc
  36583. */
  36584. radius,
  36585. /**
  36586. * Defines the tesselation factor to apply to the disc
  36587. */
  36588. tessellation, canBeRegenerated, mesh,
  36589. /**
  36590. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36591. */
  36592. side) {
  36593. if (mesh === void 0) { mesh = null; }
  36594. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36595. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36596. _this.radius = radius;
  36597. _this.tessellation = tessellation;
  36598. _this.side = side;
  36599. return _this;
  36600. }
  36601. DiscGeometry.prototype._regenerateVertexData = function () {
  36602. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36603. };
  36604. DiscGeometry.prototype.copy = function (id) {
  36605. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36606. };
  36607. return DiscGeometry;
  36608. }(_PrimitiveGeometry));
  36609. BABYLON.DiscGeometry = DiscGeometry;
  36610. /**
  36611. * Creates a new cylinder geometry
  36612. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36613. */
  36614. var CylinderGeometry = /** @class */ (function (_super) {
  36615. __extends(CylinderGeometry, _super);
  36616. /**
  36617. * Creates a new cylinder geometry
  36618. * @param id defines the unique ID of the geometry
  36619. * @param scene defines the hosting scene
  36620. * @param height defines the height of the cylinder
  36621. * @param diameterTop defines the diameter of the cylinder's top cap
  36622. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36623. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36624. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36625. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36626. * @param mesh defines the hosting mesh (can be null)
  36627. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36628. */
  36629. function CylinderGeometry(id, scene,
  36630. /**
  36631. * Defines the height of the cylinder
  36632. */
  36633. height,
  36634. /**
  36635. * Defines the diameter of the cylinder's top cap
  36636. */
  36637. diameterTop,
  36638. /**
  36639. * Defines the diameter of the cylinder's bottom cap
  36640. */
  36641. diameterBottom,
  36642. /**
  36643. * Defines the tessellation factor to apply to the cylinder
  36644. */
  36645. tessellation,
  36646. /**
  36647. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36648. */
  36649. subdivisions, canBeRegenerated, mesh,
  36650. /**
  36651. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36652. */
  36653. side) {
  36654. if (subdivisions === void 0) { subdivisions = 1; }
  36655. if (mesh === void 0) { mesh = null; }
  36656. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36657. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36658. _this.height = height;
  36659. _this.diameterTop = diameterTop;
  36660. _this.diameterBottom = diameterBottom;
  36661. _this.tessellation = tessellation;
  36662. _this.subdivisions = subdivisions;
  36663. _this.side = side;
  36664. return _this;
  36665. }
  36666. CylinderGeometry.prototype._regenerateVertexData = function () {
  36667. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36668. };
  36669. CylinderGeometry.prototype.copy = function (id) {
  36670. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36671. };
  36672. CylinderGeometry.prototype.serialize = function () {
  36673. var serializationObject = _super.prototype.serialize.call(this);
  36674. serializationObject.height = this.height;
  36675. serializationObject.diameterTop = this.diameterTop;
  36676. serializationObject.diameterBottom = this.diameterBottom;
  36677. serializationObject.tessellation = this.tessellation;
  36678. return serializationObject;
  36679. };
  36680. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36681. if (scene.getGeometryByID(parsedCylinder.id)) {
  36682. return null; // null since geometry could be something else than a cylinder...
  36683. }
  36684. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36685. if (BABYLON.Tags) {
  36686. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36687. }
  36688. scene.pushGeometry(cylinder, true);
  36689. return cylinder;
  36690. };
  36691. return CylinderGeometry;
  36692. }(_PrimitiveGeometry));
  36693. BABYLON.CylinderGeometry = CylinderGeometry;
  36694. /**
  36695. * Creates a new torus geometry
  36696. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36697. */
  36698. var TorusGeometry = /** @class */ (function (_super) {
  36699. __extends(TorusGeometry, _super);
  36700. /**
  36701. * Creates a new torus geometry
  36702. * @param id defines the unique ID of the geometry
  36703. * @param scene defines the hosting scene
  36704. * @param diameter defines the diameter of the torus
  36705. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36706. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36707. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36708. * @param mesh defines the hosting mesh (can be null)
  36709. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36710. */
  36711. function TorusGeometry(id, scene,
  36712. /**
  36713. * Defines the diameter of the torus
  36714. */
  36715. diameter,
  36716. /**
  36717. * Defines the thickness of the torus (ie. internal diameter)
  36718. */
  36719. thickness,
  36720. /**
  36721. * Defines the tesselation factor to apply to the torus
  36722. */
  36723. tessellation, canBeRegenerated, mesh,
  36724. /**
  36725. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36726. */
  36727. side) {
  36728. if (mesh === void 0) { mesh = null; }
  36729. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36730. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36731. _this.diameter = diameter;
  36732. _this.thickness = thickness;
  36733. _this.tessellation = tessellation;
  36734. _this.side = side;
  36735. return _this;
  36736. }
  36737. TorusGeometry.prototype._regenerateVertexData = function () {
  36738. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36739. };
  36740. TorusGeometry.prototype.copy = function (id) {
  36741. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36742. };
  36743. TorusGeometry.prototype.serialize = function () {
  36744. var serializationObject = _super.prototype.serialize.call(this);
  36745. serializationObject.diameter = this.diameter;
  36746. serializationObject.thickness = this.thickness;
  36747. serializationObject.tessellation = this.tessellation;
  36748. return serializationObject;
  36749. };
  36750. TorusGeometry.Parse = function (parsedTorus, scene) {
  36751. if (scene.getGeometryByID(parsedTorus.id)) {
  36752. return null; // null since geometry could be something else than a torus...
  36753. }
  36754. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36755. if (BABYLON.Tags) {
  36756. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36757. }
  36758. scene.pushGeometry(torus, true);
  36759. return torus;
  36760. };
  36761. return TorusGeometry;
  36762. }(_PrimitiveGeometry));
  36763. BABYLON.TorusGeometry = TorusGeometry;
  36764. /**
  36765. * Creates a new ground geometry
  36766. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36767. */
  36768. var GroundGeometry = /** @class */ (function (_super) {
  36769. __extends(GroundGeometry, _super);
  36770. /**
  36771. * Creates a new ground geometry
  36772. * @param id defines the unique ID of the geometry
  36773. * @param scene defines the hosting scene
  36774. * @param width defines the width of the ground
  36775. * @param height defines the height of the ground
  36776. * @param subdivisions defines the subdivisions to apply to the ground
  36777. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36778. * @param mesh defines the hosting mesh (can be null)
  36779. */
  36780. function GroundGeometry(id, scene,
  36781. /**
  36782. * Defines the width of the ground
  36783. */
  36784. width,
  36785. /**
  36786. * Defines the height of the ground
  36787. */
  36788. height,
  36789. /**
  36790. * Defines the subdivisions to apply to the ground
  36791. */
  36792. subdivisions, canBeRegenerated, mesh) {
  36793. if (mesh === void 0) { mesh = null; }
  36794. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36795. _this.width = width;
  36796. _this.height = height;
  36797. _this.subdivisions = subdivisions;
  36798. return _this;
  36799. }
  36800. GroundGeometry.prototype._regenerateVertexData = function () {
  36801. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36802. };
  36803. GroundGeometry.prototype.copy = function (id) {
  36804. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36805. };
  36806. GroundGeometry.prototype.serialize = function () {
  36807. var serializationObject = _super.prototype.serialize.call(this);
  36808. serializationObject.width = this.width;
  36809. serializationObject.height = this.height;
  36810. serializationObject.subdivisions = this.subdivisions;
  36811. return serializationObject;
  36812. };
  36813. GroundGeometry.Parse = function (parsedGround, scene) {
  36814. if (scene.getGeometryByID(parsedGround.id)) {
  36815. return null; // null since geometry could be something else than a ground...
  36816. }
  36817. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36818. if (BABYLON.Tags) {
  36819. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36820. }
  36821. scene.pushGeometry(ground, true);
  36822. return ground;
  36823. };
  36824. return GroundGeometry;
  36825. }(_PrimitiveGeometry));
  36826. BABYLON.GroundGeometry = GroundGeometry;
  36827. /**
  36828. * Creates a tiled ground geometry
  36829. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36830. */
  36831. var TiledGroundGeometry = /** @class */ (function (_super) {
  36832. __extends(TiledGroundGeometry, _super);
  36833. /**
  36834. * Creates a tiled ground geometry
  36835. * @param id defines the unique ID of the geometry
  36836. * @param scene defines the hosting scene
  36837. * @param xmin defines the minimum value on X axis
  36838. * @param zmin defines the minimum value on Z axis
  36839. * @param xmax defines the maximum value on X axis
  36840. * @param zmax defines the maximum value on Z axis
  36841. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36842. * @param precision defines the precision to use when computing the tiles
  36843. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36844. * @param mesh defines the hosting mesh (can be null)
  36845. */
  36846. function TiledGroundGeometry(id, scene,
  36847. /**
  36848. * Defines the minimum value on X axis
  36849. */
  36850. xmin,
  36851. /**
  36852. * Defines the minimum value on Z axis
  36853. */
  36854. zmin,
  36855. /**
  36856. * Defines the maximum value on X axis
  36857. */
  36858. xmax,
  36859. /**
  36860. * Defines the maximum value on Z axis
  36861. */
  36862. zmax,
  36863. /**
  36864. * Defines the subdivisions to apply to the ground
  36865. */
  36866. subdivisions,
  36867. /**
  36868. * Defines the precision to use when computing the tiles
  36869. */
  36870. precision, canBeRegenerated, mesh) {
  36871. if (mesh === void 0) { mesh = null; }
  36872. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36873. _this.xmin = xmin;
  36874. _this.zmin = zmin;
  36875. _this.xmax = xmax;
  36876. _this.zmax = zmax;
  36877. _this.subdivisions = subdivisions;
  36878. _this.precision = precision;
  36879. return _this;
  36880. }
  36881. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36882. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36883. };
  36884. TiledGroundGeometry.prototype.copy = function (id) {
  36885. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36886. };
  36887. return TiledGroundGeometry;
  36888. }(_PrimitiveGeometry));
  36889. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36890. /**
  36891. * Creates a plane geometry
  36892. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36893. */
  36894. var PlaneGeometry = /** @class */ (function (_super) {
  36895. __extends(PlaneGeometry, _super);
  36896. /**
  36897. * Creates a plane geometry
  36898. * @param id defines the unique ID of the geometry
  36899. * @param scene defines the hosting scene
  36900. * @param size defines the size of the plane (width === height)
  36901. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36902. * @param mesh defines the hosting mesh (can be null)
  36903. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36904. */
  36905. function PlaneGeometry(id, scene,
  36906. /**
  36907. * Defines the size of the plane (width === height)
  36908. */
  36909. size, canBeRegenerated, mesh,
  36910. /**
  36911. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36912. */
  36913. side) {
  36914. if (mesh === void 0) { mesh = null; }
  36915. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36916. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36917. _this.size = size;
  36918. _this.side = side;
  36919. return _this;
  36920. }
  36921. PlaneGeometry.prototype._regenerateVertexData = function () {
  36922. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36923. };
  36924. PlaneGeometry.prototype.copy = function (id) {
  36925. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36926. };
  36927. PlaneGeometry.prototype.serialize = function () {
  36928. var serializationObject = _super.prototype.serialize.call(this);
  36929. serializationObject.size = this.size;
  36930. return serializationObject;
  36931. };
  36932. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36933. if (scene.getGeometryByID(parsedPlane.id)) {
  36934. return null; // null since geometry could be something else than a ground...
  36935. }
  36936. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36937. if (BABYLON.Tags) {
  36938. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36939. }
  36940. scene.pushGeometry(plane, true);
  36941. return plane;
  36942. };
  36943. return PlaneGeometry;
  36944. }(_PrimitiveGeometry));
  36945. BABYLON.PlaneGeometry = PlaneGeometry;
  36946. /**
  36947. * Creates a torus knot geometry
  36948. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36949. */
  36950. var TorusKnotGeometry = /** @class */ (function (_super) {
  36951. __extends(TorusKnotGeometry, _super);
  36952. /**
  36953. * Creates a torus knot geometry
  36954. * @param id defines the unique ID of the geometry
  36955. * @param scene defines the hosting scene
  36956. * @param radius defines the radius of the torus knot
  36957. * @param tube defines the thickness of the torus knot tube
  36958. * @param radialSegments defines the number of radial segments
  36959. * @param tubularSegments defines the number of tubular segments
  36960. * @param p defines the first number of windings
  36961. * @param q defines the second number of windings
  36962. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36963. * @param mesh defines the hosting mesh (can be null)
  36964. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36965. */
  36966. function TorusKnotGeometry(id, scene,
  36967. /**
  36968. * Defines the radius of the torus knot
  36969. */
  36970. radius,
  36971. /**
  36972. * Defines the thickness of the torus knot tube
  36973. */
  36974. tube,
  36975. /**
  36976. * Defines the number of radial segments
  36977. */
  36978. radialSegments,
  36979. /**
  36980. * Defines the number of tubular segments
  36981. */
  36982. tubularSegments,
  36983. /**
  36984. * Defines the first number of windings
  36985. */
  36986. p,
  36987. /**
  36988. * Defines the second number of windings
  36989. */
  36990. q, canBeRegenerated, mesh,
  36991. /**
  36992. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36993. */
  36994. side) {
  36995. if (mesh === void 0) { mesh = null; }
  36996. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36997. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36998. _this.radius = radius;
  36999. _this.tube = tube;
  37000. _this.radialSegments = radialSegments;
  37001. _this.tubularSegments = tubularSegments;
  37002. _this.p = p;
  37003. _this.q = q;
  37004. _this.side = side;
  37005. return _this;
  37006. }
  37007. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  37008. 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 });
  37009. };
  37010. TorusKnotGeometry.prototype.copy = function (id) {
  37011. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37012. };
  37013. TorusKnotGeometry.prototype.serialize = function () {
  37014. var serializationObject = _super.prototype.serialize.call(this);
  37015. serializationObject.radius = this.radius;
  37016. serializationObject.tube = this.tube;
  37017. serializationObject.radialSegments = this.radialSegments;
  37018. serializationObject.tubularSegments = this.tubularSegments;
  37019. serializationObject.p = this.p;
  37020. serializationObject.q = this.q;
  37021. return serializationObject;
  37022. };
  37023. ;
  37024. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37025. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37026. return null; // null since geometry could be something else than a ground...
  37027. }
  37028. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37029. if (BABYLON.Tags) {
  37030. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37031. }
  37032. scene.pushGeometry(torusKnot, true);
  37033. return torusKnot;
  37034. };
  37035. return TorusKnotGeometry;
  37036. }(_PrimitiveGeometry));
  37037. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37038. //}
  37039. })(BABYLON || (BABYLON = {}));
  37040. //# sourceMappingURL=babylon.geometry.js.map
  37041. "use strict";
  37042. var BABYLON;
  37043. (function (BABYLON) {
  37044. /**
  37045. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37046. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37047. */
  37048. var PostProcessManager = /** @class */ (function () {
  37049. /**
  37050. * Creates a new instance of @see PostProcess
  37051. * @param scene The scene that the post process is associated with.
  37052. */
  37053. function PostProcessManager(scene) {
  37054. this._vertexBuffers = {};
  37055. this._scene = scene;
  37056. }
  37057. PostProcessManager.prototype._prepareBuffers = function () {
  37058. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37059. return;
  37060. }
  37061. // VBO
  37062. var vertices = [];
  37063. vertices.push(1, 1);
  37064. vertices.push(-1, 1);
  37065. vertices.push(-1, -1);
  37066. vertices.push(1, -1);
  37067. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37068. this._buildIndexBuffer();
  37069. };
  37070. PostProcessManager.prototype._buildIndexBuffer = function () {
  37071. // Indices
  37072. var indices = [];
  37073. indices.push(0);
  37074. indices.push(1);
  37075. indices.push(2);
  37076. indices.push(0);
  37077. indices.push(2);
  37078. indices.push(3);
  37079. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37080. };
  37081. /**
  37082. * Rebuilds the vertex buffers of the manager.
  37083. */
  37084. PostProcessManager.prototype._rebuild = function () {
  37085. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37086. if (!vb) {
  37087. return;
  37088. }
  37089. vb._rebuild();
  37090. this._buildIndexBuffer();
  37091. };
  37092. // Methods
  37093. /**
  37094. * Prepares a frame to be run through a post process.
  37095. * @param sourceTexture The input texture to the post procesess. (default: null)
  37096. * @param postProcesses An array of post processes to be run. (default: null)
  37097. * @returns True if the post processes were able to be run.
  37098. */
  37099. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37100. if (sourceTexture === void 0) { sourceTexture = null; }
  37101. if (postProcesses === void 0) { postProcesses = null; }
  37102. var camera = this._scene.activeCamera;
  37103. if (!camera) {
  37104. return false;
  37105. }
  37106. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37107. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37108. return false;
  37109. }
  37110. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37111. return true;
  37112. };
  37113. /**
  37114. * Manually render a set of post processes to a texture.
  37115. * @param postProcesses An array of post processes to be run.
  37116. * @param targetTexture The target texture to render to.
  37117. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37118. */
  37119. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37120. if (targetTexture === void 0) { targetTexture = null; }
  37121. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37122. var engine = this._scene.getEngine();
  37123. for (var index = 0; index < postProcesses.length; index++) {
  37124. if (index < postProcesses.length - 1) {
  37125. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37126. }
  37127. else {
  37128. if (targetTexture) {
  37129. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37130. }
  37131. else {
  37132. engine.restoreDefaultFramebuffer();
  37133. }
  37134. }
  37135. var pp = postProcesses[index];
  37136. var effect = pp.apply();
  37137. if (effect) {
  37138. pp.onBeforeRenderObservable.notifyObservers(effect);
  37139. // VBOs
  37140. this._prepareBuffers();
  37141. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37142. // Draw order
  37143. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37144. pp.onAfterRenderObservable.notifyObservers(effect);
  37145. }
  37146. }
  37147. // Restore depth buffer
  37148. engine.setDepthBuffer(true);
  37149. engine.setDepthWrite(true);
  37150. };
  37151. /**
  37152. * Finalize the result of the output of the postprocesses.
  37153. * @param doNotPresent If true the result will not be displayed to the screen.
  37154. * @param targetTexture The target texture to render to.
  37155. * @param faceIndex The index of the face to bind the target texture to.
  37156. * @param postProcesses The array of post processes to render.
  37157. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37158. */
  37159. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37160. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37161. var camera = this._scene.activeCamera;
  37162. if (!camera) {
  37163. return;
  37164. }
  37165. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37166. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37167. return;
  37168. }
  37169. var engine = this._scene.getEngine();
  37170. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37171. var pp = postProcesses[index];
  37172. if (index < len - 1) {
  37173. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37174. }
  37175. else {
  37176. if (targetTexture) {
  37177. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37178. }
  37179. else {
  37180. engine.restoreDefaultFramebuffer();
  37181. }
  37182. }
  37183. if (doNotPresent) {
  37184. break;
  37185. }
  37186. var effect = pp.apply();
  37187. if (effect) {
  37188. pp.onBeforeRenderObservable.notifyObservers(effect);
  37189. // VBOs
  37190. this._prepareBuffers();
  37191. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37192. // Draw order
  37193. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37194. pp.onAfterRenderObservable.notifyObservers(effect);
  37195. }
  37196. }
  37197. // Restore states
  37198. engine.setDepthBuffer(true);
  37199. engine.setDepthWrite(true);
  37200. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37201. };
  37202. /**
  37203. * Disposes of the post process manager.
  37204. */
  37205. PostProcessManager.prototype.dispose = function () {
  37206. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37207. if (buffer) {
  37208. buffer.dispose();
  37209. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37210. }
  37211. if (this._indexBuffer) {
  37212. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37213. this._indexBuffer = null;
  37214. }
  37215. };
  37216. return PostProcessManager;
  37217. }());
  37218. BABYLON.PostProcessManager = PostProcessManager;
  37219. })(BABYLON || (BABYLON = {}));
  37220. //# sourceMappingURL=babylon.postProcessManager.js.map
  37221. "use strict";
  37222. var BABYLON;
  37223. (function (BABYLON) {
  37224. /**
  37225. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37226. */
  37227. var PerformanceMonitor = /** @class */ (function () {
  37228. /**
  37229. * constructor
  37230. * @param frameSampleSize The number of samples required to saturate the sliding window
  37231. */
  37232. function PerformanceMonitor(frameSampleSize) {
  37233. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37234. this._enabled = true;
  37235. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37236. }
  37237. /**
  37238. * Samples current frame
  37239. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37240. */
  37241. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37242. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37243. if (!this._enabled)
  37244. return;
  37245. if (this._lastFrameTimeMs != null) {
  37246. var dt = timeMs - this._lastFrameTimeMs;
  37247. this._rollingFrameTime.add(dt);
  37248. }
  37249. this._lastFrameTimeMs = timeMs;
  37250. };
  37251. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37252. /**
  37253. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37254. * @return Average frame time in milliseconds
  37255. */
  37256. get: function () {
  37257. return this._rollingFrameTime.average;
  37258. },
  37259. enumerable: true,
  37260. configurable: true
  37261. });
  37262. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37263. /**
  37264. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37265. * @return Frame time variance in milliseconds squared
  37266. */
  37267. get: function () {
  37268. return this._rollingFrameTime.variance;
  37269. },
  37270. enumerable: true,
  37271. configurable: true
  37272. });
  37273. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37274. /**
  37275. * Returns the frame time of the most recent frame
  37276. * @return Frame time in milliseconds
  37277. */
  37278. get: function () {
  37279. return this._rollingFrameTime.history(0);
  37280. },
  37281. enumerable: true,
  37282. configurable: true
  37283. });
  37284. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37285. /**
  37286. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37287. * @return Framerate in frames per second
  37288. */
  37289. get: function () {
  37290. return 1000.0 / this._rollingFrameTime.average;
  37291. },
  37292. enumerable: true,
  37293. configurable: true
  37294. });
  37295. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37296. /**
  37297. * Returns the average framerate in frames per second using the most recent frame time
  37298. * @return Framerate in frames per second
  37299. */
  37300. get: function () {
  37301. var history = this._rollingFrameTime.history(0);
  37302. if (history === 0) {
  37303. return 0;
  37304. }
  37305. return 1000.0 / history;
  37306. },
  37307. enumerable: true,
  37308. configurable: true
  37309. });
  37310. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37311. /**
  37312. * Returns true if enough samples have been taken to completely fill the sliding window
  37313. * @return true if saturated
  37314. */
  37315. get: function () {
  37316. return this._rollingFrameTime.isSaturated();
  37317. },
  37318. enumerable: true,
  37319. configurable: true
  37320. });
  37321. /**
  37322. * Enables contributions to the sliding window sample set
  37323. */
  37324. PerformanceMonitor.prototype.enable = function () {
  37325. this._enabled = true;
  37326. };
  37327. /**
  37328. * Disables contributions to the sliding window sample set
  37329. * Samples will not be interpolated over the disabled period
  37330. */
  37331. PerformanceMonitor.prototype.disable = function () {
  37332. this._enabled = false;
  37333. //clear last sample to avoid interpolating over the disabled period when next enabled
  37334. this._lastFrameTimeMs = null;
  37335. };
  37336. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37337. /**
  37338. * Returns true if sampling is enabled
  37339. * @return true if enabled
  37340. */
  37341. get: function () {
  37342. return this._enabled;
  37343. },
  37344. enumerable: true,
  37345. configurable: true
  37346. });
  37347. /**
  37348. * Resets performance monitor
  37349. */
  37350. PerformanceMonitor.prototype.reset = function () {
  37351. //clear last sample to avoid interpolating over the disabled period when next enabled
  37352. this._lastFrameTimeMs = null;
  37353. //wipe record
  37354. this._rollingFrameTime.reset();
  37355. };
  37356. return PerformanceMonitor;
  37357. }());
  37358. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37359. /**
  37360. * RollingAverage
  37361. *
  37362. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37363. */
  37364. var RollingAverage = /** @class */ (function () {
  37365. /**
  37366. * constructor
  37367. * @param length The number of samples required to saturate the sliding window
  37368. */
  37369. function RollingAverage(length) {
  37370. this._samples = new Array(length);
  37371. this.reset();
  37372. }
  37373. /**
  37374. * Adds a sample to the sample set
  37375. * @param v The sample value
  37376. */
  37377. RollingAverage.prototype.add = function (v) {
  37378. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37379. var delta;
  37380. //we need to check if we've already wrapped round
  37381. if (this.isSaturated()) {
  37382. //remove bottom of stack from mean
  37383. var bottomValue = this._samples[this._pos];
  37384. delta = bottomValue - this.average;
  37385. this.average -= delta / (this._sampleCount - 1);
  37386. this._m2 -= delta * (bottomValue - this.average);
  37387. }
  37388. else {
  37389. this._sampleCount++;
  37390. }
  37391. //add new value to mean
  37392. delta = v - this.average;
  37393. this.average += delta / (this._sampleCount);
  37394. this._m2 += delta * (v - this.average);
  37395. //set the new variance
  37396. this.variance = this._m2 / (this._sampleCount - 1);
  37397. this._samples[this._pos] = v;
  37398. this._pos++;
  37399. this._pos %= this._samples.length; //positive wrap around
  37400. };
  37401. /**
  37402. * Returns previously added values or null if outside of history or outside the sliding window domain
  37403. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37404. * @return Value previously recorded with add() or null if outside of range
  37405. */
  37406. RollingAverage.prototype.history = function (i) {
  37407. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37408. return 0;
  37409. }
  37410. var i0 = this._wrapPosition(this._pos - 1.0);
  37411. return this._samples[this._wrapPosition(i0 - i)];
  37412. };
  37413. /**
  37414. * Returns true if enough samples have been taken to completely fill the sliding window
  37415. * @return true if sample-set saturated
  37416. */
  37417. RollingAverage.prototype.isSaturated = function () {
  37418. return this._sampleCount >= this._samples.length;
  37419. };
  37420. /**
  37421. * Resets the rolling average (equivalent to 0 samples taken so far)
  37422. */
  37423. RollingAverage.prototype.reset = function () {
  37424. this.average = 0;
  37425. this.variance = 0;
  37426. this._sampleCount = 0;
  37427. this._pos = 0;
  37428. this._m2 = 0;
  37429. };
  37430. /**
  37431. * Wraps a value around the sample range boundaries
  37432. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37433. * @return Wrapped position in sample range
  37434. */
  37435. RollingAverage.prototype._wrapPosition = function (i) {
  37436. var max = this._samples.length;
  37437. return ((i % max) + max) % max;
  37438. };
  37439. return RollingAverage;
  37440. }());
  37441. BABYLON.RollingAverage = RollingAverage;
  37442. })(BABYLON || (BABYLON = {}));
  37443. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37444. "use strict";
  37445. var BABYLON;
  37446. (function (BABYLON) {
  37447. /**
  37448. * This groups together the common properties used for image processing either in direct forward pass
  37449. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37450. * or not.
  37451. */
  37452. var ImageProcessingConfiguration = /** @class */ (function () {
  37453. function ImageProcessingConfiguration() {
  37454. /**
  37455. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37456. */
  37457. this.colorCurves = new BABYLON.ColorCurves();
  37458. this._colorCurvesEnabled = false;
  37459. this._colorGradingEnabled = false;
  37460. this._colorGradingWithGreenDepth = true;
  37461. this._colorGradingBGR = true;
  37462. this._exposure = 1.0;
  37463. this._toneMappingEnabled = false;
  37464. this._contrast = 1.0;
  37465. /**
  37466. * Vignette stretch size.
  37467. */
  37468. this.vignetteStretch = 0;
  37469. /**
  37470. * Vignette centre X Offset.
  37471. */
  37472. this.vignetteCentreX = 0;
  37473. /**
  37474. * Vignette centre Y Offset.
  37475. */
  37476. this.vignetteCentreY = 0;
  37477. /**
  37478. * Vignette weight or intensity of the vignette effect.
  37479. */
  37480. this.vignetteWeight = 1.5;
  37481. /**
  37482. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37483. * if vignetteEnabled is set to true.
  37484. */
  37485. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37486. /**
  37487. * Camera field of view used by the Vignette effect.
  37488. */
  37489. this.vignetteCameraFov = 0.5;
  37490. this._grainEnabled = false;
  37491. this._grainIntensity = 30;
  37492. this._grainAnimated = false;
  37493. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37494. this._vignetteEnabled = false;
  37495. this._applyByPostProcess = false;
  37496. this._isEnabled = true;
  37497. /**
  37498. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37499. * @type {BABYLON.Observable}
  37500. */
  37501. this.onUpdateParameters = new BABYLON.Observable();
  37502. }
  37503. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37504. /**
  37505. * Gets wether the color curves effect is enabled.
  37506. */
  37507. get: function () {
  37508. return this._colorCurvesEnabled;
  37509. },
  37510. /**
  37511. * Sets wether the color curves effect is enabled.
  37512. */
  37513. set: function (value) {
  37514. if (this._colorCurvesEnabled === value) {
  37515. return;
  37516. }
  37517. this._colorCurvesEnabled = value;
  37518. this._updateParameters();
  37519. },
  37520. enumerable: true,
  37521. configurable: true
  37522. });
  37523. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37524. /**
  37525. * Gets wether the color grading effect is enabled.
  37526. */
  37527. get: function () {
  37528. return this._colorGradingEnabled;
  37529. },
  37530. /**
  37531. * Sets wether the color grading effect is enabled.
  37532. */
  37533. set: function (value) {
  37534. if (this._colorGradingEnabled === value) {
  37535. return;
  37536. }
  37537. this._colorGradingEnabled = value;
  37538. this._updateParameters();
  37539. },
  37540. enumerable: true,
  37541. configurable: true
  37542. });
  37543. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37544. /**
  37545. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37546. */
  37547. get: function () {
  37548. return this._colorGradingWithGreenDepth;
  37549. },
  37550. /**
  37551. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37552. */
  37553. set: function (value) {
  37554. if (this._colorGradingWithGreenDepth === value) {
  37555. return;
  37556. }
  37557. this._colorGradingWithGreenDepth = value;
  37558. this._updateParameters();
  37559. },
  37560. enumerable: true,
  37561. configurable: true
  37562. });
  37563. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37564. /**
  37565. * Gets wether the color grading texture contains BGR values.
  37566. */
  37567. get: function () {
  37568. return this._colorGradingBGR;
  37569. },
  37570. /**
  37571. * Sets wether the color grading texture contains BGR values.
  37572. */
  37573. set: function (value) {
  37574. if (this._colorGradingBGR === value) {
  37575. return;
  37576. }
  37577. this._colorGradingBGR = value;
  37578. this._updateParameters();
  37579. },
  37580. enumerable: true,
  37581. configurable: true
  37582. });
  37583. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37584. /**
  37585. * Gets the Exposure used in the effect.
  37586. */
  37587. get: function () {
  37588. return this._exposure;
  37589. },
  37590. /**
  37591. * Sets the Exposure used in the effect.
  37592. */
  37593. set: function (value) {
  37594. if (this._exposure === value) {
  37595. return;
  37596. }
  37597. this._exposure = value;
  37598. this._updateParameters();
  37599. },
  37600. enumerable: true,
  37601. configurable: true
  37602. });
  37603. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37604. /**
  37605. * Gets wether the tone mapping effect is enabled.
  37606. */
  37607. get: function () {
  37608. return this._toneMappingEnabled;
  37609. },
  37610. /**
  37611. * Sets wether the tone mapping effect is enabled.
  37612. */
  37613. set: function (value) {
  37614. if (this._toneMappingEnabled === value) {
  37615. return;
  37616. }
  37617. this._toneMappingEnabled = value;
  37618. this._updateParameters();
  37619. },
  37620. enumerable: true,
  37621. configurable: true
  37622. });
  37623. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37624. /**
  37625. * Gets the contrast used in the effect.
  37626. */
  37627. get: function () {
  37628. return this._contrast;
  37629. },
  37630. /**
  37631. * Sets the contrast used in the effect.
  37632. */
  37633. set: function (value) {
  37634. if (this._contrast === value) {
  37635. return;
  37636. }
  37637. this._contrast = value;
  37638. this._updateParameters();
  37639. },
  37640. enumerable: true,
  37641. configurable: true
  37642. });
  37643. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37644. /**
  37645. * If the grain effect should be enabled.
  37646. */
  37647. get: function () {
  37648. return this._grainEnabled;
  37649. },
  37650. set: function (value) {
  37651. if (this._grainEnabled === value) {
  37652. return;
  37653. }
  37654. this._grainEnabled = value;
  37655. this._updateParameters();
  37656. },
  37657. enumerable: true,
  37658. configurable: true
  37659. });
  37660. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37661. /**
  37662. * Amount of grain to be applied by the grain effect.
  37663. */
  37664. get: function () {
  37665. return this._grainIntensity;
  37666. },
  37667. set: function (value) {
  37668. if (this._grainIntensity === value) {
  37669. return;
  37670. }
  37671. this._grainIntensity = value;
  37672. },
  37673. enumerable: true,
  37674. configurable: true
  37675. });
  37676. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37677. /**
  37678. * If the grain effect should be animated.
  37679. */
  37680. get: function () {
  37681. return this._grainAnimated;
  37682. },
  37683. set: function (value) {
  37684. if (this._grainAnimated === value) {
  37685. return;
  37686. }
  37687. this._grainAnimated = value;
  37688. this._updateParameters();
  37689. },
  37690. enumerable: true,
  37691. configurable: true
  37692. });
  37693. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37694. /**
  37695. * Gets the vignette blend mode allowing different kind of effect.
  37696. */
  37697. get: function () {
  37698. return this._vignetteBlendMode;
  37699. },
  37700. /**
  37701. * Sets the vignette blend mode allowing different kind of effect.
  37702. */
  37703. set: function (value) {
  37704. if (this._vignetteBlendMode === value) {
  37705. return;
  37706. }
  37707. this._vignetteBlendMode = value;
  37708. this._updateParameters();
  37709. },
  37710. enumerable: true,
  37711. configurable: true
  37712. });
  37713. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37714. /**
  37715. * Gets wether the vignette effect is enabled.
  37716. */
  37717. get: function () {
  37718. return this._vignetteEnabled;
  37719. },
  37720. /**
  37721. * Sets wether the vignette effect is enabled.
  37722. */
  37723. set: function (value) {
  37724. if (this._vignetteEnabled === value) {
  37725. return;
  37726. }
  37727. this._vignetteEnabled = value;
  37728. this._updateParameters();
  37729. },
  37730. enumerable: true,
  37731. configurable: true
  37732. });
  37733. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37734. /**
  37735. * Gets wether the image processing is applied through a post process or not.
  37736. */
  37737. get: function () {
  37738. return this._applyByPostProcess;
  37739. },
  37740. /**
  37741. * Sets wether the image processing is applied through a post process or not.
  37742. */
  37743. set: function (value) {
  37744. if (this._applyByPostProcess === value) {
  37745. return;
  37746. }
  37747. this._applyByPostProcess = value;
  37748. this._updateParameters();
  37749. },
  37750. enumerable: true,
  37751. configurable: true
  37752. });
  37753. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37754. /**
  37755. * Gets wether the image processing is enabled or not.
  37756. */
  37757. get: function () {
  37758. return this._isEnabled;
  37759. },
  37760. /**
  37761. * Sets wether the image processing is enabled or not.
  37762. */
  37763. set: function (value) {
  37764. if (this._isEnabled === value) {
  37765. return;
  37766. }
  37767. this._isEnabled = value;
  37768. this._updateParameters();
  37769. },
  37770. enumerable: true,
  37771. configurable: true
  37772. });
  37773. /**
  37774. * Method called each time the image processing information changes requires to recompile the effect.
  37775. */
  37776. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37777. this.onUpdateParameters.notifyObservers(this);
  37778. };
  37779. ImageProcessingConfiguration.prototype.getClassName = function () {
  37780. return "ImageProcessingConfiguration";
  37781. };
  37782. /**
  37783. * Prepare the list of uniforms associated with the Image Processing effects.
  37784. * @param uniformsList The list of uniforms used in the effect
  37785. * @param defines the list of defines currently in use
  37786. */
  37787. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37788. if (defines.EXPOSURE) {
  37789. uniforms.push("exposureLinear");
  37790. }
  37791. if (defines.CONTRAST) {
  37792. uniforms.push("contrast");
  37793. }
  37794. if (defines.COLORGRADING) {
  37795. uniforms.push("colorTransformSettings");
  37796. }
  37797. if (defines.VIGNETTE) {
  37798. uniforms.push("vInverseScreenSize");
  37799. uniforms.push("vignetteSettings1");
  37800. uniforms.push("vignetteSettings2");
  37801. }
  37802. if (defines.COLORCURVES) {
  37803. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37804. }
  37805. if (defines.GRAIN) {
  37806. uniforms.push("grainVarianceAmount");
  37807. uniforms.push("grainAnimatedSeed");
  37808. }
  37809. };
  37810. /**
  37811. * Prepare the list of samplers associated with the Image Processing effects.
  37812. * @param uniformsList The list of uniforms used in the effect
  37813. * @param defines the list of defines currently in use
  37814. */
  37815. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37816. if (defines.COLORGRADING) {
  37817. samplersList.push("txColorTransform");
  37818. }
  37819. };
  37820. /**
  37821. * Prepare the list of defines associated to the shader.
  37822. * @param defines the list of defines to complete
  37823. */
  37824. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37825. if (forPostProcess === void 0) { forPostProcess = false; }
  37826. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37827. defines.VIGNETTE = false;
  37828. defines.TONEMAPPING = false;
  37829. defines.CONTRAST = false;
  37830. defines.EXPOSURE = false;
  37831. defines.COLORCURVES = false;
  37832. defines.COLORGRADING = false;
  37833. defines.COLORGRADING3D = false;
  37834. defines.IMAGEPROCESSING = false;
  37835. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37836. return;
  37837. }
  37838. defines.VIGNETTE = this.vignetteEnabled;
  37839. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37840. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37841. defines.TONEMAPPING = this.toneMappingEnabled;
  37842. defines.CONTRAST = (this.contrast !== 1.0);
  37843. defines.EXPOSURE = (this.exposure !== 1.0);
  37844. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37845. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37846. if (defines.COLORGRADING) {
  37847. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37848. }
  37849. else {
  37850. defines.COLORGRADING3D = false;
  37851. }
  37852. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37853. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37854. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37855. defines.GRAIN = this.grainEnabled;
  37856. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37857. };
  37858. /**
  37859. * Returns true if all the image processing information are ready.
  37860. */
  37861. ImageProcessingConfiguration.prototype.isReady = function () {
  37862. // Color Grading texure can not be none blocking.
  37863. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37864. };
  37865. /**
  37866. * Binds the image processing to the shader.
  37867. * @param effect The effect to bind to
  37868. */
  37869. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37870. if (aspectRatio === void 0) { aspectRatio = 1; }
  37871. // Color Curves
  37872. if (this._colorCurvesEnabled && this.colorCurves) {
  37873. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37874. }
  37875. // Vignette
  37876. if (this._vignetteEnabled) {
  37877. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37878. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37879. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37880. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37881. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37882. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37883. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37884. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37885. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37886. var vignettePower = -2.0 * this.vignetteWeight;
  37887. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37888. }
  37889. // Exposure
  37890. effect.setFloat("exposureLinear", this.exposure);
  37891. // Contrast
  37892. effect.setFloat("contrast", this.contrast);
  37893. // Color transform settings
  37894. if (this.colorGradingTexture) {
  37895. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37896. var textureSize = this.colorGradingTexture.getSize().height;
  37897. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37898. 0.5 / textureSize, // textureOffset
  37899. textureSize, // textureSize
  37900. this.colorGradingTexture.level // weight
  37901. );
  37902. }
  37903. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37904. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37905. };
  37906. /**
  37907. * Clones the current image processing instance.
  37908. * @return The cloned image processing
  37909. */
  37910. ImageProcessingConfiguration.prototype.clone = function () {
  37911. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37912. };
  37913. /**
  37914. * Serializes the current image processing instance to a json representation.
  37915. * @return a JSON representation
  37916. */
  37917. ImageProcessingConfiguration.prototype.serialize = function () {
  37918. return BABYLON.SerializationHelper.Serialize(this);
  37919. };
  37920. /**
  37921. * Parses the image processing from a json representation.
  37922. * @param source the JSON source to parse
  37923. * @return The parsed image processing
  37924. */
  37925. ImageProcessingConfiguration.Parse = function (source) {
  37926. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37927. };
  37928. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37929. /**
  37930. * Used to apply the vignette as a mix with the pixel color.
  37931. */
  37932. get: function () {
  37933. return this._VIGNETTEMODE_MULTIPLY;
  37934. },
  37935. enumerable: true,
  37936. configurable: true
  37937. });
  37938. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37939. /**
  37940. * Used to apply the vignette as a replacement of the pixel color.
  37941. */
  37942. get: function () {
  37943. return this._VIGNETTEMODE_OPAQUE;
  37944. },
  37945. enumerable: true,
  37946. configurable: true
  37947. });
  37948. // Static constants associated to the image processing.
  37949. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37950. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37951. __decorate([
  37952. BABYLON.serializeAsColorCurves()
  37953. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37954. __decorate([
  37955. BABYLON.serialize()
  37956. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37957. __decorate([
  37958. BABYLON.serializeAsTexture()
  37959. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37960. __decorate([
  37961. BABYLON.serialize()
  37962. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37963. __decorate([
  37964. BABYLON.serialize()
  37965. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37966. __decorate([
  37967. BABYLON.serialize()
  37968. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37969. __decorate([
  37970. BABYLON.serialize()
  37971. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37972. __decorate([
  37973. BABYLON.serialize()
  37974. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37975. __decorate([
  37976. BABYLON.serialize()
  37977. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37978. __decorate([
  37979. BABYLON.serialize()
  37980. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37981. __decorate([
  37982. BABYLON.serialize()
  37983. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37984. __decorate([
  37985. BABYLON.serialize()
  37986. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37987. __decorate([
  37988. BABYLON.serialize()
  37989. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37990. __decorate([
  37991. BABYLON.serializeAsColor4()
  37992. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37993. __decorate([
  37994. BABYLON.serialize()
  37995. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37996. __decorate([
  37997. BABYLON.serialize()
  37998. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37999. __decorate([
  38000. BABYLON.serialize()
  38001. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  38002. __decorate([
  38003. BABYLON.serialize()
  38004. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  38005. __decorate([
  38006. BABYLON.serialize()
  38007. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  38008. __decorate([
  38009. BABYLON.serialize()
  38010. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  38011. __decorate([
  38012. BABYLON.serialize()
  38013. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  38014. __decorate([
  38015. BABYLON.serialize()
  38016. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38017. return ImageProcessingConfiguration;
  38018. }());
  38019. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38020. })(BABYLON || (BABYLON = {}));
  38021. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38022. "use strict";
  38023. var BABYLON;
  38024. (function (BABYLON) {
  38025. /**
  38026. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38027. * It can help converting any input color in a desired output one. This can then be used to create effects
  38028. * from sepia, black and white to sixties or futuristic rendering...
  38029. *
  38030. * The only supported format is currently 3dl.
  38031. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38032. */
  38033. var ColorGradingTexture = /** @class */ (function (_super) {
  38034. __extends(ColorGradingTexture, _super);
  38035. /**
  38036. * Instantiates a ColorGradingTexture from the following parameters.
  38037. *
  38038. * @param url The location of the color gradind data (currently only supporting 3dl)
  38039. * @param scene The scene the texture will be used in
  38040. */
  38041. function ColorGradingTexture(url, scene) {
  38042. var _this = _super.call(this, scene) || this;
  38043. if (!url) {
  38044. return _this;
  38045. }
  38046. _this._engine = scene.getEngine();
  38047. _this._textureMatrix = BABYLON.Matrix.Identity();
  38048. _this.name = url;
  38049. _this.url = url;
  38050. _this.hasAlpha = false;
  38051. _this.isCube = false;
  38052. _this.is3D = _this._engine.webGLVersion > 1;
  38053. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38054. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38055. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38056. _this.anisotropicFilteringLevel = 1;
  38057. _this._texture = _this._getFromCache(url, true);
  38058. if (!_this._texture) {
  38059. if (!scene.useDelayedTextureLoading) {
  38060. _this.loadTexture();
  38061. }
  38062. else {
  38063. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38064. }
  38065. }
  38066. return _this;
  38067. }
  38068. /**
  38069. * Returns the texture matrix used in most of the material.
  38070. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38071. */
  38072. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38073. return this._textureMatrix;
  38074. };
  38075. /**
  38076. * Occurs when the file being loaded is a .3dl LUT file.
  38077. */
  38078. ColorGradingTexture.prototype.load3dlTexture = function () {
  38079. var engine = this._engine;
  38080. var texture;
  38081. if (engine.webGLVersion === 1) {
  38082. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38083. }
  38084. else {
  38085. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38086. }
  38087. this._texture = texture;
  38088. var callback = function (text) {
  38089. if (typeof text !== "string") {
  38090. return;
  38091. }
  38092. var data = null;
  38093. var tempData = null;
  38094. var line;
  38095. var lines = text.split('\n');
  38096. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38097. var maxColor = 0;
  38098. for (var i = 0; i < lines.length; i++) {
  38099. line = lines[i];
  38100. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38101. continue;
  38102. if (line.indexOf('#') === 0)
  38103. continue;
  38104. var words = line.split(" ");
  38105. if (size === 0) {
  38106. // Number of space + one
  38107. size = words.length;
  38108. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38109. tempData = new Float32Array(size * size * size * 4);
  38110. continue;
  38111. }
  38112. if (size != 0) {
  38113. var r = Math.max(parseInt(words[0]), 0);
  38114. var g = Math.max(parseInt(words[1]), 0);
  38115. var b = Math.max(parseInt(words[2]), 0);
  38116. maxColor = Math.max(r, maxColor);
  38117. maxColor = Math.max(g, maxColor);
  38118. maxColor = Math.max(b, maxColor);
  38119. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38120. if (tempData) {
  38121. tempData[pixelStorageIndex + 0] = r;
  38122. tempData[pixelStorageIndex + 1] = g;
  38123. tempData[pixelStorageIndex + 2] = b;
  38124. }
  38125. pixelIndexSlice++;
  38126. if (pixelIndexSlice % size == 0) {
  38127. pixelIndexH++;
  38128. pixelIndexSlice = 0;
  38129. if (pixelIndexH % size == 0) {
  38130. pixelIndexW++;
  38131. pixelIndexH = 0;
  38132. }
  38133. }
  38134. }
  38135. }
  38136. if (tempData && data) {
  38137. for (var i = 0; i < tempData.length; i++) {
  38138. if (i > 0 && (i + 1) % 4 === 0) {
  38139. data[i] = 255;
  38140. }
  38141. else {
  38142. var value = tempData[i];
  38143. data[i] = (value / maxColor * 255);
  38144. }
  38145. }
  38146. }
  38147. if (texture.is3D) {
  38148. texture.updateSize(size, size, size);
  38149. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38150. }
  38151. else {
  38152. texture.updateSize(size * size, size);
  38153. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38154. }
  38155. };
  38156. var scene = this.getScene();
  38157. if (scene) {
  38158. scene._loadFile(this.url, callback);
  38159. }
  38160. else {
  38161. this._engine._loadFile(this.url, callback);
  38162. }
  38163. return this._texture;
  38164. };
  38165. /**
  38166. * Starts the loading process of the texture.
  38167. */
  38168. ColorGradingTexture.prototype.loadTexture = function () {
  38169. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38170. this.load3dlTexture();
  38171. }
  38172. };
  38173. /**
  38174. * Clones the color gradind texture.
  38175. */
  38176. ColorGradingTexture.prototype.clone = function () {
  38177. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38178. // Base texture
  38179. newTexture.level = this.level;
  38180. return newTexture;
  38181. };
  38182. /**
  38183. * Called during delayed load for textures.
  38184. */
  38185. ColorGradingTexture.prototype.delayLoad = function () {
  38186. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38187. return;
  38188. }
  38189. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38190. this._texture = this._getFromCache(this.url, true);
  38191. if (!this._texture) {
  38192. this.loadTexture();
  38193. }
  38194. };
  38195. /**
  38196. * Parses a color grading texture serialized by Babylon.
  38197. * @param parsedTexture The texture information being parsedTexture
  38198. * @param scene The scene to load the texture in
  38199. * @param rootUrl The root url of the data assets to load
  38200. * @return A color gradind texture
  38201. */
  38202. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38203. var texture = null;
  38204. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38205. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38206. texture.name = parsedTexture.name;
  38207. texture.level = parsedTexture.level;
  38208. }
  38209. return texture;
  38210. };
  38211. /**
  38212. * Serializes the LUT texture to json format.
  38213. */
  38214. ColorGradingTexture.prototype.serialize = function () {
  38215. if (!this.name) {
  38216. return null;
  38217. }
  38218. var serializationObject = {};
  38219. serializationObject.name = this.name;
  38220. serializationObject.level = this.level;
  38221. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38222. return serializationObject;
  38223. };
  38224. /**
  38225. * Empty line regex stored for GC.
  38226. */
  38227. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38228. return ColorGradingTexture;
  38229. }(BABYLON.BaseTexture));
  38230. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38231. })(BABYLON || (BABYLON = {}));
  38232. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38233. "use strict";
  38234. var BABYLON;
  38235. (function (BABYLON) {
  38236. /**
  38237. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38238. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38239. * 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;
  38240. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38241. */
  38242. var ColorCurves = /** @class */ (function () {
  38243. function ColorCurves() {
  38244. this._dirty = true;
  38245. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38246. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38247. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38248. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38249. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38250. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38251. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38252. this._globalHue = 30;
  38253. this._globalDensity = 0;
  38254. this._globalSaturation = 0;
  38255. this._globalExposure = 0;
  38256. this._highlightsHue = 30;
  38257. this._highlightsDensity = 0;
  38258. this._highlightsSaturation = 0;
  38259. this._highlightsExposure = 0;
  38260. this._midtonesHue = 30;
  38261. this._midtonesDensity = 0;
  38262. this._midtonesSaturation = 0;
  38263. this._midtonesExposure = 0;
  38264. this._shadowsHue = 30;
  38265. this._shadowsDensity = 0;
  38266. this._shadowsSaturation = 0;
  38267. this._shadowsExposure = 0;
  38268. }
  38269. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38270. /**
  38271. * Gets the global Hue value.
  38272. * 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).
  38273. */
  38274. get: function () {
  38275. return this._globalHue;
  38276. },
  38277. /**
  38278. * Sets the global Hue value.
  38279. * 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).
  38280. */
  38281. set: function (value) {
  38282. this._globalHue = value;
  38283. this._dirty = true;
  38284. },
  38285. enumerable: true,
  38286. configurable: true
  38287. });
  38288. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38289. /**
  38290. * Gets the global Density value.
  38291. * 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.
  38292. * Values less than zero provide a filter of opposite hue.
  38293. */
  38294. get: function () {
  38295. return this._globalDensity;
  38296. },
  38297. /**
  38298. * Sets the global Density value.
  38299. * 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.
  38300. * Values less than zero provide a filter of opposite hue.
  38301. */
  38302. set: function (value) {
  38303. this._globalDensity = value;
  38304. this._dirty = true;
  38305. },
  38306. enumerable: true,
  38307. configurable: true
  38308. });
  38309. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38310. /**
  38311. * Gets the global Saturation value.
  38312. * 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.
  38313. */
  38314. get: function () {
  38315. return this._globalSaturation;
  38316. },
  38317. /**
  38318. * Sets the global Saturation value.
  38319. * 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.
  38320. */
  38321. set: function (value) {
  38322. this._globalSaturation = value;
  38323. this._dirty = true;
  38324. },
  38325. enumerable: true,
  38326. configurable: true
  38327. });
  38328. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38329. /**
  38330. * Gets the highlights Hue value.
  38331. * 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).
  38332. */
  38333. get: function () {
  38334. return this._highlightsHue;
  38335. },
  38336. /**
  38337. * Sets the highlights Hue value.
  38338. * 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).
  38339. */
  38340. set: function (value) {
  38341. this._highlightsHue = value;
  38342. this._dirty = true;
  38343. },
  38344. enumerable: true,
  38345. configurable: true
  38346. });
  38347. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38348. /**
  38349. * Gets the highlights Density value.
  38350. * 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.
  38351. * Values less than zero provide a filter of opposite hue.
  38352. */
  38353. get: function () {
  38354. return this._highlightsDensity;
  38355. },
  38356. /**
  38357. * Sets the highlights Density value.
  38358. * 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.
  38359. * Values less than zero provide a filter of opposite hue.
  38360. */
  38361. set: function (value) {
  38362. this._highlightsDensity = value;
  38363. this._dirty = true;
  38364. },
  38365. enumerable: true,
  38366. configurable: true
  38367. });
  38368. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38369. /**
  38370. * Gets the highlights Saturation value.
  38371. * 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.
  38372. */
  38373. get: function () {
  38374. return this._highlightsSaturation;
  38375. },
  38376. /**
  38377. * Sets the highlights Saturation value.
  38378. * 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.
  38379. */
  38380. set: function (value) {
  38381. this._highlightsSaturation = value;
  38382. this._dirty = true;
  38383. },
  38384. enumerable: true,
  38385. configurable: true
  38386. });
  38387. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38388. /**
  38389. * Gets the highlights Exposure value.
  38390. * 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.
  38391. */
  38392. get: function () {
  38393. return this._highlightsExposure;
  38394. },
  38395. /**
  38396. * Sets the highlights Exposure value.
  38397. * 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.
  38398. */
  38399. set: function (value) {
  38400. this._highlightsExposure = value;
  38401. this._dirty = true;
  38402. },
  38403. enumerable: true,
  38404. configurable: true
  38405. });
  38406. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38407. /**
  38408. * Gets the midtones Hue value.
  38409. * 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).
  38410. */
  38411. get: function () {
  38412. return this._midtonesHue;
  38413. },
  38414. /**
  38415. * Sets the midtones Hue value.
  38416. * 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).
  38417. */
  38418. set: function (value) {
  38419. this._midtonesHue = value;
  38420. this._dirty = true;
  38421. },
  38422. enumerable: true,
  38423. configurable: true
  38424. });
  38425. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38426. /**
  38427. * Gets the midtones Density value.
  38428. * 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.
  38429. * Values less than zero provide a filter of opposite hue.
  38430. */
  38431. get: function () {
  38432. return this._midtonesDensity;
  38433. },
  38434. /**
  38435. * Sets the midtones Density value.
  38436. * 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.
  38437. * Values less than zero provide a filter of opposite hue.
  38438. */
  38439. set: function (value) {
  38440. this._midtonesDensity = value;
  38441. this._dirty = true;
  38442. },
  38443. enumerable: true,
  38444. configurable: true
  38445. });
  38446. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38447. /**
  38448. * Gets the midtones Saturation value.
  38449. * 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.
  38450. */
  38451. get: function () {
  38452. return this._midtonesSaturation;
  38453. },
  38454. /**
  38455. * Sets the midtones Saturation value.
  38456. * 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.
  38457. */
  38458. set: function (value) {
  38459. this._midtonesSaturation = value;
  38460. this._dirty = true;
  38461. },
  38462. enumerable: true,
  38463. configurable: true
  38464. });
  38465. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38466. /**
  38467. * Gets the midtones Exposure value.
  38468. * 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.
  38469. */
  38470. get: function () {
  38471. return this._midtonesExposure;
  38472. },
  38473. /**
  38474. * Sets the midtones Exposure value.
  38475. * 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.
  38476. */
  38477. set: function (value) {
  38478. this._midtonesExposure = value;
  38479. this._dirty = true;
  38480. },
  38481. enumerable: true,
  38482. configurable: true
  38483. });
  38484. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38485. /**
  38486. * Gets the shadows Hue value.
  38487. * 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).
  38488. */
  38489. get: function () {
  38490. return this._shadowsHue;
  38491. },
  38492. /**
  38493. * Sets the shadows Hue value.
  38494. * 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).
  38495. */
  38496. set: function (value) {
  38497. this._shadowsHue = value;
  38498. this._dirty = true;
  38499. },
  38500. enumerable: true,
  38501. configurable: true
  38502. });
  38503. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38504. /**
  38505. * Gets the shadows Density value.
  38506. * 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.
  38507. * Values less than zero provide a filter of opposite hue.
  38508. */
  38509. get: function () {
  38510. return this._shadowsDensity;
  38511. },
  38512. /**
  38513. * Sets the shadows Density value.
  38514. * 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.
  38515. * Values less than zero provide a filter of opposite hue.
  38516. */
  38517. set: function (value) {
  38518. this._shadowsDensity = value;
  38519. this._dirty = true;
  38520. },
  38521. enumerable: true,
  38522. configurable: true
  38523. });
  38524. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38525. /**
  38526. * Gets the shadows Saturation value.
  38527. * 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.
  38528. */
  38529. get: function () {
  38530. return this._shadowsSaturation;
  38531. },
  38532. /**
  38533. * Sets the shadows Saturation value.
  38534. * 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.
  38535. */
  38536. set: function (value) {
  38537. this._shadowsSaturation = value;
  38538. this._dirty = true;
  38539. },
  38540. enumerable: true,
  38541. configurable: true
  38542. });
  38543. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38544. /**
  38545. * Gets the shadows Exposure value.
  38546. * 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.
  38547. */
  38548. get: function () {
  38549. return this._shadowsExposure;
  38550. },
  38551. /**
  38552. * Sets the shadows Exposure value.
  38553. * 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.
  38554. */
  38555. set: function (value) {
  38556. this._shadowsExposure = value;
  38557. this._dirty = true;
  38558. },
  38559. enumerable: true,
  38560. configurable: true
  38561. });
  38562. ColorCurves.prototype.getClassName = function () {
  38563. return "ColorCurves";
  38564. };
  38565. /**
  38566. * Binds the color curves to the shader.
  38567. * @param colorCurves The color curve to bind
  38568. * @param effect The effect to bind to
  38569. */
  38570. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38571. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38572. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38573. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38574. if (colorCurves._dirty) {
  38575. colorCurves._dirty = false;
  38576. // Fill in global info.
  38577. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38578. // Compute highlights info.
  38579. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38580. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38581. // Compute midtones info.
  38582. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38583. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38584. // Compute shadows info.
  38585. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38586. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38587. // Compute deltas (neutral is midtones).
  38588. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38589. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38590. }
  38591. if (effect) {
  38592. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38593. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38594. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38595. }
  38596. };
  38597. /**
  38598. * Prepare the list of uniforms associated with the ColorCurves effects.
  38599. * @param uniformsList The list of uniforms used in the effect
  38600. */
  38601. ColorCurves.PrepareUniforms = function (uniformsList) {
  38602. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38603. };
  38604. /**
  38605. * Returns color grading data based on a hue, density, saturation and exposure value.
  38606. * @param filterHue The hue of the color filter.
  38607. * @param filterDensity The density of the color filter.
  38608. * @param saturation The saturation.
  38609. * @param exposure The exposure.
  38610. * @param result The result data container.
  38611. */
  38612. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38613. if (hue == null) {
  38614. return;
  38615. }
  38616. hue = ColorCurves.clamp(hue, 0, 360);
  38617. density = ColorCurves.clamp(density, -100, 100);
  38618. saturation = ColorCurves.clamp(saturation, -100, 100);
  38619. exposure = ColorCurves.clamp(exposure, -100, 100);
  38620. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38621. // so that the maximum filter density is only 50% control. This provides fine control
  38622. // for small values and reasonable range.
  38623. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38624. density *= 0.5;
  38625. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38626. if (density < 0) {
  38627. density *= -1;
  38628. hue = (hue + 180) % 360;
  38629. }
  38630. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38631. result.scaleToRef(2, result);
  38632. result.a = 1 + 0.01 * saturation;
  38633. };
  38634. /**
  38635. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38636. * @param value The input slider value in range [-100,100].
  38637. * @returns Adjusted value.
  38638. */
  38639. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38640. value /= 100;
  38641. var x = Math.abs(value);
  38642. x = Math.pow(x, 2);
  38643. if (value < 0) {
  38644. x *= -1;
  38645. }
  38646. x *= 100;
  38647. return x;
  38648. };
  38649. /**
  38650. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38651. * @param hue The hue (H) input.
  38652. * @param saturation The saturation (S) input.
  38653. * @param brightness The brightness (B) input.
  38654. * @result An RGBA color represented as Vector4.
  38655. */
  38656. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38657. var h = ColorCurves.clamp(hue, 0, 360);
  38658. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38659. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38660. if (s === 0) {
  38661. result.r = v;
  38662. result.g = v;
  38663. result.b = v;
  38664. }
  38665. else {
  38666. // sector 0 to 5
  38667. h /= 60;
  38668. var i = Math.floor(h);
  38669. // fractional part of h
  38670. var f = h - i;
  38671. var p = v * (1 - s);
  38672. var q = v * (1 - s * f);
  38673. var t = v * (1 - s * (1 - f));
  38674. switch (i) {
  38675. case 0:
  38676. result.r = v;
  38677. result.g = t;
  38678. result.b = p;
  38679. break;
  38680. case 1:
  38681. result.r = q;
  38682. result.g = v;
  38683. result.b = p;
  38684. break;
  38685. case 2:
  38686. result.r = p;
  38687. result.g = v;
  38688. result.b = t;
  38689. break;
  38690. case 3:
  38691. result.r = p;
  38692. result.g = q;
  38693. result.b = v;
  38694. break;
  38695. case 4:
  38696. result.r = t;
  38697. result.g = p;
  38698. result.b = v;
  38699. break;
  38700. default:// case 5:
  38701. result.r = v;
  38702. result.g = p;
  38703. result.b = q;
  38704. break;
  38705. }
  38706. }
  38707. result.a = 1;
  38708. };
  38709. /**
  38710. * Returns a value clamped between min and max
  38711. * @param value The value to clamp
  38712. * @param min The minimum of value
  38713. * @param max The maximum of value
  38714. * @returns The clamped value.
  38715. */
  38716. ColorCurves.clamp = function (value, min, max) {
  38717. return Math.min(Math.max(value, min), max);
  38718. };
  38719. /**
  38720. * Clones the current color curve instance.
  38721. * @return The cloned curves
  38722. */
  38723. ColorCurves.prototype.clone = function () {
  38724. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38725. };
  38726. /**
  38727. * Serializes the current color curve instance to a json representation.
  38728. * @return a JSON representation
  38729. */
  38730. ColorCurves.prototype.serialize = function () {
  38731. return BABYLON.SerializationHelper.Serialize(this);
  38732. };
  38733. /**
  38734. * Parses the color curve from a json representation.
  38735. * @param source the JSON source to parse
  38736. * @return The parsed curves
  38737. */
  38738. ColorCurves.Parse = function (source) {
  38739. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38740. };
  38741. __decorate([
  38742. BABYLON.serialize()
  38743. ], ColorCurves.prototype, "_globalHue", void 0);
  38744. __decorate([
  38745. BABYLON.serialize()
  38746. ], ColorCurves.prototype, "_globalDensity", void 0);
  38747. __decorate([
  38748. BABYLON.serialize()
  38749. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38750. __decorate([
  38751. BABYLON.serialize()
  38752. ], ColorCurves.prototype, "_globalExposure", void 0);
  38753. __decorate([
  38754. BABYLON.serialize()
  38755. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38756. __decorate([
  38757. BABYLON.serialize()
  38758. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38759. __decorate([
  38760. BABYLON.serialize()
  38761. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38762. __decorate([
  38763. BABYLON.serialize()
  38764. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38765. __decorate([
  38766. BABYLON.serialize()
  38767. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38768. __decorate([
  38769. BABYLON.serialize()
  38770. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38771. __decorate([
  38772. BABYLON.serialize()
  38773. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38774. __decorate([
  38775. BABYLON.serialize()
  38776. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38777. return ColorCurves;
  38778. }());
  38779. BABYLON.ColorCurves = ColorCurves;
  38780. })(BABYLON || (BABYLON = {}));
  38781. //# sourceMappingURL=babylon.colorCurves.js.map
  38782. "use strict";
  38783. //# sourceMappingURL=babylon.behavior.js.map
  38784. "use strict";
  38785. var BABYLON;
  38786. (function (BABYLON) {
  38787. /**
  38788. * "Static Class" containing the most commonly used helper while dealing with material for
  38789. * rendering purpose.
  38790. *
  38791. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38792. *
  38793. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38794. */
  38795. var MaterialHelper = /** @class */ (function () {
  38796. function MaterialHelper() {
  38797. }
  38798. /**
  38799. * Bind the current view position to an effect.
  38800. * @param effect The effect to be bound
  38801. * @param scene The scene the eyes position is used from
  38802. */
  38803. MaterialHelper.BindEyePosition = function (effect, scene) {
  38804. if (scene._forcedViewPosition) {
  38805. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38806. return;
  38807. }
  38808. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38809. };
  38810. /**
  38811. * Helps preparing the defines values about the UVs in used in the effect.
  38812. * UVs are shared as much as we can accross chanels in the shaders.
  38813. * @param texture The texture we are preparing the UVs for
  38814. * @param defines The defines to update
  38815. * @param key The chanel key "diffuse", "specular"... used in the shader
  38816. */
  38817. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38818. defines._needUVs = true;
  38819. defines[key] = true;
  38820. if (texture.getTextureMatrix().isIdentity(true)) {
  38821. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38822. if (texture.coordinatesIndex === 0) {
  38823. defines["MAINUV1"] = true;
  38824. }
  38825. else {
  38826. defines["MAINUV2"] = true;
  38827. }
  38828. }
  38829. else {
  38830. defines[key + "DIRECTUV"] = 0;
  38831. }
  38832. };
  38833. /**
  38834. * Binds a texture matrix value to its corrsponding uniform
  38835. * @param texture The texture to bind the matrix for
  38836. * @param uniformBuffer The uniform buffer receivin the data
  38837. * @param key The chanel key "diffuse", "specular"... used in the shader
  38838. */
  38839. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38840. var matrix = texture.getTextureMatrix();
  38841. if (!matrix.isIdentity(true)) {
  38842. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38843. }
  38844. };
  38845. /**
  38846. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38847. * @param mesh defines the current mesh
  38848. * @param scene defines the current scene
  38849. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38850. * @param pointsCloud defines if point cloud rendering has to be turned on
  38851. * @param fogEnabled defines if fog has to be turned on
  38852. * @param alphaTest defines if alpha testing has to be turned on
  38853. * @param defines defines the current list of defines
  38854. */
  38855. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38856. if (defines._areMiscDirty) {
  38857. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38858. defines["POINTSIZE"] = pointsCloud;
  38859. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38860. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38861. defines["ALPHATEST"] = alphaTest;
  38862. }
  38863. };
  38864. /**
  38865. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38866. * @param scene defines the current scene
  38867. * @param engine defines the current engine
  38868. * @param defines specifies the list of active defines
  38869. * @param useInstances defines if instances have to be turned on
  38870. * @param useClipPlane defines if clip plane have to be turned on
  38871. */
  38872. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38873. if (useClipPlane === void 0) { useClipPlane = null; }
  38874. var changed = false;
  38875. if (useClipPlane == null) {
  38876. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38877. }
  38878. if (defines["CLIPPLANE"] !== useClipPlane) {
  38879. defines["CLIPPLANE"] = useClipPlane;
  38880. changed = true;
  38881. }
  38882. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38883. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38884. changed = true;
  38885. }
  38886. if (defines["INSTANCES"] !== useInstances) {
  38887. defines["INSTANCES"] = useInstances;
  38888. changed = true;
  38889. }
  38890. if (changed) {
  38891. defines.markAsUnprocessed();
  38892. }
  38893. };
  38894. /**
  38895. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38896. * @param mesh The mesh containing the geometry data we will draw
  38897. * @param defines The defines to update
  38898. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38899. * @param useBones Precise whether bones should be used or not (override mesh info)
  38900. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38901. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38902. * @returns false if defines are considered not dirty and have not been checked
  38903. */
  38904. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38905. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38906. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38907. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38908. return false;
  38909. }
  38910. defines._normals = defines._needNormals;
  38911. defines._uvs = defines._needUVs;
  38912. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38913. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38914. defines["TANGENT"] = true;
  38915. }
  38916. if (defines._needUVs) {
  38917. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38918. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38919. }
  38920. else {
  38921. defines["UV1"] = false;
  38922. defines["UV2"] = false;
  38923. }
  38924. if (useVertexColor) {
  38925. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38926. defines["VERTEXCOLOR"] = hasVertexColors;
  38927. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38928. }
  38929. if (useBones) {
  38930. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38931. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38932. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38933. }
  38934. else {
  38935. defines["NUM_BONE_INFLUENCERS"] = 0;
  38936. defines["BonesPerMesh"] = 0;
  38937. }
  38938. }
  38939. if (useMorphTargets) {
  38940. var manager = mesh.morphTargetManager;
  38941. if (manager) {
  38942. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38943. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38944. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38945. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38946. }
  38947. else {
  38948. defines["MORPHTARGETS_TANGENT"] = false;
  38949. defines["MORPHTARGETS_NORMAL"] = false;
  38950. defines["MORPHTARGETS"] = false;
  38951. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38952. }
  38953. }
  38954. return true;
  38955. };
  38956. /**
  38957. * Prepares the defines related to the light information passed in parameter
  38958. * @param scene The scene we are intending to draw
  38959. * @param mesh The mesh the effect is compiling for
  38960. * @param defines The defines to update
  38961. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38962. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38963. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38964. * @returns true if normals will be required for the rest of the effect
  38965. */
  38966. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38967. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38968. if (disableLighting === void 0) { disableLighting = false; }
  38969. if (!defines._areLightsDirty) {
  38970. return defines._needNormals;
  38971. }
  38972. var lightIndex = 0;
  38973. var needNormals = false;
  38974. var needRebuild = false;
  38975. var lightmapMode = false;
  38976. var shadowEnabled = false;
  38977. var specularEnabled = false;
  38978. if (scene.lightsEnabled && !disableLighting) {
  38979. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38980. var light = _a[_i];
  38981. needNormals = true;
  38982. if (defines["LIGHT" + lightIndex] === undefined) {
  38983. needRebuild = true;
  38984. }
  38985. defines["LIGHT" + lightIndex] = true;
  38986. defines["SPOTLIGHT" + lightIndex] = false;
  38987. defines["HEMILIGHT" + lightIndex] = false;
  38988. defines["POINTLIGHT" + lightIndex] = false;
  38989. defines["DIRLIGHT" + lightIndex] = false;
  38990. var type;
  38991. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38992. type = "SPOTLIGHT" + lightIndex;
  38993. var spotLight = light;
  38994. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38995. }
  38996. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38997. type = "HEMILIGHT" + lightIndex;
  38998. }
  38999. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  39000. type = "POINTLIGHT" + lightIndex;
  39001. }
  39002. else {
  39003. type = "DIRLIGHT" + lightIndex;
  39004. }
  39005. defines[type] = true;
  39006. // Specular
  39007. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  39008. specularEnabled = true;
  39009. }
  39010. // Shadows
  39011. defines["SHADOW" + lightIndex] = false;
  39012. defines["SHADOWPCF" + lightIndex] = false;
  39013. defines["SHADOWPCSS" + lightIndex] = false;
  39014. defines["SHADOWPOISSON" + lightIndex] = false;
  39015. defines["SHADOWESM" + lightIndex] = false;
  39016. defines["SHADOWCUBE" + lightIndex] = false;
  39017. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39018. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39019. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39020. var shadowGenerator = light.getShadowGenerator();
  39021. if (shadowGenerator) {
  39022. shadowEnabled = true;
  39023. shadowGenerator.prepareDefines(defines, lightIndex);
  39024. }
  39025. }
  39026. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39027. lightmapMode = true;
  39028. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39029. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39030. }
  39031. else {
  39032. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39033. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39034. }
  39035. lightIndex++;
  39036. if (lightIndex === maxSimultaneousLights)
  39037. break;
  39038. }
  39039. }
  39040. defines["SPECULARTERM"] = specularEnabled;
  39041. defines["SHADOWS"] = shadowEnabled;
  39042. // Resetting all other lights if any
  39043. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39044. if (defines["LIGHT" + index] !== undefined) {
  39045. defines["LIGHT" + index] = false;
  39046. defines["HEMILIGHT" + lightIndex] = false;
  39047. defines["POINTLIGHT" + lightIndex] = false;
  39048. defines["DIRLIGHT" + lightIndex] = false;
  39049. defines["SPOTLIGHT" + lightIndex] = false;
  39050. defines["SHADOW" + lightIndex] = false;
  39051. }
  39052. }
  39053. var caps = scene.getEngine().getCaps();
  39054. if (defines["SHADOWFLOAT"] === undefined) {
  39055. needRebuild = true;
  39056. }
  39057. defines["SHADOWFLOAT"] = shadowEnabled &&
  39058. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39059. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39060. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39061. if (needRebuild) {
  39062. defines.rebuild();
  39063. }
  39064. return needNormals;
  39065. };
  39066. /**
  39067. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39068. * that won t be acctive due to defines being turned off.
  39069. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39070. * @param samplersList The samplers list
  39071. * @param defines The defines helping in the list generation
  39072. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39073. */
  39074. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39075. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39076. var uniformsList;
  39077. var uniformBuffersList = null;
  39078. if (uniformsListOrOptions.uniformsNames) {
  39079. var options = uniformsListOrOptions;
  39080. uniformsList = options.uniformsNames;
  39081. uniformBuffersList = options.uniformBuffersNames;
  39082. samplersList = options.samplers;
  39083. defines = options.defines;
  39084. maxSimultaneousLights = options.maxSimultaneousLights;
  39085. }
  39086. else {
  39087. uniformsList = uniformsListOrOptions;
  39088. if (!samplersList) {
  39089. samplersList = [];
  39090. }
  39091. }
  39092. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39093. if (!defines["LIGHT" + lightIndex]) {
  39094. break;
  39095. }
  39096. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39097. if (uniformBuffersList) {
  39098. uniformBuffersList.push("Light" + lightIndex);
  39099. }
  39100. samplersList.push("shadowSampler" + lightIndex);
  39101. samplersList.push("depthSampler" + lightIndex);
  39102. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39103. samplersList.push("projectionLightSampler" + lightIndex);
  39104. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39105. }
  39106. }
  39107. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39108. uniformsList.push("morphTargetInfluences");
  39109. }
  39110. };
  39111. /**
  39112. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39113. * @param defines The defines to update while falling back
  39114. * @param fallbacks The authorized effect fallbacks
  39115. * @param maxSimultaneousLights The maximum number of lights allowed
  39116. * @param rank the current rank of the Effect
  39117. * @returns The newly affected rank
  39118. */
  39119. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39120. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39121. if (rank === void 0) { rank = 0; }
  39122. var lightFallbackRank = 0;
  39123. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39124. if (!defines["LIGHT" + lightIndex]) {
  39125. break;
  39126. }
  39127. if (lightIndex > 0) {
  39128. lightFallbackRank = rank + lightIndex;
  39129. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39130. }
  39131. if (!defines["SHADOWS"]) {
  39132. if (defines["SHADOW" + lightIndex]) {
  39133. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39134. }
  39135. if (defines["SHADOWPCF" + lightIndex]) {
  39136. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39137. }
  39138. if (defines["SHADOWPCSS" + lightIndex]) {
  39139. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39140. }
  39141. if (defines["SHADOWPOISSON" + lightIndex]) {
  39142. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39143. }
  39144. if (defines["SHADOWESM" + lightIndex]) {
  39145. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39146. }
  39147. }
  39148. }
  39149. return lightFallbackRank++;
  39150. };
  39151. /**
  39152. * Prepares the list of attributes required for morph targets according to the effect defines.
  39153. * @param attribs The current list of supported attribs
  39154. * @param mesh The mesh to prepare the morph targets attributes for
  39155. * @param defines The current Defines of the effect
  39156. */
  39157. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39158. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39159. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39160. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39161. var manager = mesh.morphTargetManager;
  39162. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39163. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39164. for (var index = 0; index < influencers; index++) {
  39165. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39166. if (normal) {
  39167. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39168. }
  39169. if (tangent) {
  39170. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39171. }
  39172. if (attribs.length > maxAttributesCount) {
  39173. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39174. }
  39175. }
  39176. }
  39177. };
  39178. /**
  39179. * Prepares the list of attributes required for bones according to the effect defines.
  39180. * @param attribs The current list of supported attribs
  39181. * @param mesh The mesh to prepare the bones attributes for
  39182. * @param defines The current Defines of the effect
  39183. * @param fallbacks The current efffect fallback strategy
  39184. */
  39185. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39186. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39187. fallbacks.addCPUSkinningFallback(0, mesh);
  39188. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39189. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39190. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39191. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39192. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39193. }
  39194. }
  39195. };
  39196. /**
  39197. * Prepares the list of attributes required for instances according to the effect defines.
  39198. * @param attribs The current list of supported attribs
  39199. * @param defines The current Defines of the effect
  39200. */
  39201. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39202. if (defines["INSTANCES"]) {
  39203. attribs.push("world0");
  39204. attribs.push("world1");
  39205. attribs.push("world2");
  39206. attribs.push("world3");
  39207. }
  39208. };
  39209. /**
  39210. * Binds the light shadow information to the effect for the given mesh.
  39211. * @param light The light containing the generator
  39212. * @param scene The scene the lights belongs to
  39213. * @param mesh The mesh we are binding the information to render
  39214. * @param lightIndex The light index in the effect used to render the mesh
  39215. * @param effect The effect we are binding the data to
  39216. */
  39217. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39218. if (light.shadowEnabled && mesh.receiveShadows) {
  39219. var shadowGenerator = light.getShadowGenerator();
  39220. if (shadowGenerator) {
  39221. shadowGenerator.bindShadowLight(lightIndex, effect);
  39222. }
  39223. }
  39224. };
  39225. /**
  39226. * Binds the light information to the effect.
  39227. * @param light The light containing the generator
  39228. * @param effect The effect we are binding the data to
  39229. * @param lightIndex The light index in the effect used to render
  39230. */
  39231. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39232. light.transferToEffect(effect, lightIndex + "");
  39233. };
  39234. /**
  39235. * Binds the lights information from the scene to the effect for the given mesh.
  39236. * @param scene The scene the lights belongs to
  39237. * @param mesh The mesh we are binding the information to render
  39238. * @param effect The effect we are binding the data to
  39239. * @param defines The generated defines for the effect
  39240. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39241. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39242. */
  39243. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39244. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39245. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39246. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39247. for (var i = 0; i < len; i++) {
  39248. var light = mesh._lightSources[i];
  39249. var iAsString = i.toString();
  39250. var scaledIntensity = light.getScaledIntensity();
  39251. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39252. MaterialHelper.BindLightProperties(light, effect, i);
  39253. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39254. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39255. if (defines["SPECULARTERM"]) {
  39256. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39257. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39258. }
  39259. // Shadows
  39260. if (scene.shadowsEnabled) {
  39261. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39262. }
  39263. light._uniformBuffer.update();
  39264. }
  39265. };
  39266. /**
  39267. * Binds the fog information from the scene to the effect for the given mesh.
  39268. * @param scene The scene the lights belongs to
  39269. * @param mesh The mesh we are binding the information to render
  39270. * @param effect The effect we are binding the data to
  39271. */
  39272. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39273. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39274. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39275. effect.setColor3("vFogColor", scene.fogColor);
  39276. }
  39277. };
  39278. /**
  39279. * Binds the bones information from the mesh to the effect.
  39280. * @param mesh The mesh we are binding the information to render
  39281. * @param effect The effect we are binding the data to
  39282. */
  39283. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39284. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39285. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39286. if (matrices && effect) {
  39287. effect.setMatrices("mBones", matrices);
  39288. }
  39289. }
  39290. };
  39291. /**
  39292. * Binds the morph targets information from the mesh to the effect.
  39293. * @param abstractMesh The mesh we are binding the information to render
  39294. * @param effect The effect we are binding the data to
  39295. */
  39296. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39297. var manager = abstractMesh.morphTargetManager;
  39298. if (!abstractMesh || !manager) {
  39299. return;
  39300. }
  39301. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39302. };
  39303. /**
  39304. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39305. * @param defines The generated defines used in the effect
  39306. * @param effect The effect we are binding the data to
  39307. * @param scene The scene we are willing to render with logarithmic scale for
  39308. */
  39309. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39310. if (defines["LOGARITHMICDEPTH"]) {
  39311. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39312. }
  39313. };
  39314. /**
  39315. * Binds the clip plane information from the scene to the effect.
  39316. * @param scene The scene the clip plane information are extracted from
  39317. * @param effect The effect we are binding the data to
  39318. */
  39319. MaterialHelper.BindClipPlane = function (effect, scene) {
  39320. if (scene.clipPlane) {
  39321. var clipPlane = scene.clipPlane;
  39322. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39323. }
  39324. };
  39325. return MaterialHelper;
  39326. }());
  39327. BABYLON.MaterialHelper = MaterialHelper;
  39328. })(BABYLON || (BABYLON = {}));
  39329. //# sourceMappingURL=babylon.materialHelper.js.map
  39330. "use strict";
  39331. var BABYLON;
  39332. (function (BABYLON) {
  39333. var PushMaterial = /** @class */ (function (_super) {
  39334. __extends(PushMaterial, _super);
  39335. function PushMaterial(name, scene) {
  39336. var _this = _super.call(this, name, scene) || this;
  39337. _this._normalMatrix = new BABYLON.Matrix();
  39338. _this.storeEffectOnSubMeshes = true;
  39339. return _this;
  39340. }
  39341. PushMaterial.prototype.getEffect = function () {
  39342. return this._activeEffect;
  39343. };
  39344. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39345. if (!mesh) {
  39346. return false;
  39347. }
  39348. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39349. return true;
  39350. }
  39351. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39352. };
  39353. /**
  39354. * Binds the given world matrix to the active effect
  39355. *
  39356. * @param world the matrix to bind
  39357. */
  39358. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39359. this._activeEffect.setMatrix("world", world);
  39360. };
  39361. /**
  39362. * Binds the given normal matrix to the active effect
  39363. *
  39364. * @param normalMatrix the matrix to bind
  39365. */
  39366. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39367. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39368. };
  39369. PushMaterial.prototype.bind = function (world, mesh) {
  39370. if (!mesh) {
  39371. return;
  39372. }
  39373. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39374. };
  39375. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39376. if (effect === void 0) { effect = null; }
  39377. _super.prototype._afterBind.call(this, mesh);
  39378. this.getScene()._cachedEffect = effect;
  39379. };
  39380. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39381. if (visibility === void 0) { visibility = 1; }
  39382. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39383. };
  39384. return PushMaterial;
  39385. }(BABYLON.Material));
  39386. BABYLON.PushMaterial = PushMaterial;
  39387. })(BABYLON || (BABYLON = {}));
  39388. //# sourceMappingURL=babylon.pushMaterial.js.map
  39389. "use strict";
  39390. var BABYLON;
  39391. (function (BABYLON) {
  39392. /** @ignore */
  39393. var StandardMaterialDefines = /** @class */ (function (_super) {
  39394. __extends(StandardMaterialDefines, _super);
  39395. function StandardMaterialDefines() {
  39396. var _this = _super.call(this) || this;
  39397. _this.MAINUV1 = false;
  39398. _this.MAINUV2 = false;
  39399. _this.DIFFUSE = false;
  39400. _this.DIFFUSEDIRECTUV = 0;
  39401. _this.AMBIENT = false;
  39402. _this.AMBIENTDIRECTUV = 0;
  39403. _this.OPACITY = false;
  39404. _this.OPACITYDIRECTUV = 0;
  39405. _this.OPACITYRGB = false;
  39406. _this.REFLECTION = false;
  39407. _this.EMISSIVE = false;
  39408. _this.EMISSIVEDIRECTUV = 0;
  39409. _this.SPECULAR = false;
  39410. _this.SPECULARDIRECTUV = 0;
  39411. _this.BUMP = false;
  39412. _this.BUMPDIRECTUV = 0;
  39413. _this.PARALLAX = false;
  39414. _this.PARALLAXOCCLUSION = false;
  39415. _this.SPECULAROVERALPHA = false;
  39416. _this.CLIPPLANE = false;
  39417. _this.ALPHATEST = false;
  39418. _this.DEPTHPREPASS = false;
  39419. _this.ALPHAFROMDIFFUSE = false;
  39420. _this.POINTSIZE = false;
  39421. _this.FOG = false;
  39422. _this.SPECULARTERM = false;
  39423. _this.DIFFUSEFRESNEL = false;
  39424. _this.OPACITYFRESNEL = false;
  39425. _this.REFLECTIONFRESNEL = false;
  39426. _this.REFRACTIONFRESNEL = false;
  39427. _this.EMISSIVEFRESNEL = false;
  39428. _this.FRESNEL = false;
  39429. _this.NORMAL = false;
  39430. _this.UV1 = false;
  39431. _this.UV2 = false;
  39432. _this.VERTEXCOLOR = false;
  39433. _this.VERTEXALPHA = false;
  39434. _this.NUM_BONE_INFLUENCERS = 0;
  39435. _this.BonesPerMesh = 0;
  39436. _this.INSTANCES = false;
  39437. _this.GLOSSINESS = false;
  39438. _this.ROUGHNESS = false;
  39439. _this.EMISSIVEASILLUMINATION = false;
  39440. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39441. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39442. _this.LIGHTMAP = false;
  39443. _this.LIGHTMAPDIRECTUV = 0;
  39444. _this.OBJECTSPACE_NORMALMAP = false;
  39445. _this.USELIGHTMAPASSHADOWMAP = false;
  39446. _this.REFLECTIONMAP_3D = false;
  39447. _this.REFLECTIONMAP_SPHERICAL = false;
  39448. _this.REFLECTIONMAP_PLANAR = false;
  39449. _this.REFLECTIONMAP_CUBIC = false;
  39450. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39451. _this.REFLECTIONMAP_PROJECTION = false;
  39452. _this.REFLECTIONMAP_SKYBOX = false;
  39453. _this.REFLECTIONMAP_EXPLICIT = false;
  39454. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39455. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39456. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39457. _this.INVERTCUBICMAP = false;
  39458. _this.LOGARITHMICDEPTH = false;
  39459. _this.REFRACTION = false;
  39460. _this.REFRACTIONMAP_3D = false;
  39461. _this.REFLECTIONOVERALPHA = false;
  39462. _this.TWOSIDEDLIGHTING = false;
  39463. _this.SHADOWFLOAT = false;
  39464. _this.MORPHTARGETS = false;
  39465. _this.MORPHTARGETS_NORMAL = false;
  39466. _this.MORPHTARGETS_TANGENT = false;
  39467. _this.NUM_MORPH_INFLUENCERS = 0;
  39468. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39469. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39470. _this.IMAGEPROCESSING = false;
  39471. _this.VIGNETTE = false;
  39472. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39473. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39474. _this.TONEMAPPING = false;
  39475. _this.CONTRAST = false;
  39476. _this.COLORCURVES = false;
  39477. _this.COLORGRADING = false;
  39478. _this.COLORGRADING3D = false;
  39479. _this.SAMPLER3DGREENDEPTH = false;
  39480. _this.SAMPLER3DBGRMAP = false;
  39481. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39482. _this.EXPOSURE = false;
  39483. _this.GRAIN = false;
  39484. _this.rebuild();
  39485. return _this;
  39486. }
  39487. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39488. var modes = [
  39489. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39490. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39491. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39492. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39493. ];
  39494. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39495. var mode = modes_1[_i];
  39496. this[mode] = (mode === modeToEnable);
  39497. }
  39498. };
  39499. return StandardMaterialDefines;
  39500. }(BABYLON.MaterialDefines));
  39501. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39502. var StandardMaterial = /** @class */ (function (_super) {
  39503. __extends(StandardMaterial, _super);
  39504. function StandardMaterial(name, scene) {
  39505. var _this = _super.call(this, name, scene) || this;
  39506. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39507. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39508. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39509. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39510. _this.specularPower = 64;
  39511. _this._useAlphaFromDiffuseTexture = false;
  39512. _this._useEmissiveAsIllumination = false;
  39513. _this._linkEmissiveWithDiffuse = false;
  39514. _this._useSpecularOverAlpha = false;
  39515. _this._useReflectionOverAlpha = false;
  39516. _this._disableLighting = false;
  39517. _this._useObjectSpaceNormalMap = false;
  39518. _this._useParallax = false;
  39519. _this._useParallaxOcclusion = false;
  39520. _this.parallaxScaleBias = 0.05;
  39521. _this._roughness = 0;
  39522. _this.indexOfRefraction = 0.98;
  39523. _this.invertRefractionY = true;
  39524. _this._useLightmapAsShadowmap = false;
  39525. _this._useReflectionFresnelFromSpecular = false;
  39526. _this._useGlossinessFromSpecularMapAlpha = false;
  39527. _this._maxSimultaneousLights = 4;
  39528. /**
  39529. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39530. */
  39531. _this._invertNormalMapX = false;
  39532. /**
  39533. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39534. */
  39535. _this._invertNormalMapY = false;
  39536. /**
  39537. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39538. */
  39539. _this._twoSidedLighting = false;
  39540. _this._renderTargets = new BABYLON.SmartArray(16);
  39541. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39542. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39543. // Setup the default processing configuration to the scene.
  39544. _this._attachImageProcessingConfiguration(null);
  39545. _this.getRenderTargetTextures = function () {
  39546. _this._renderTargets.reset();
  39547. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39548. _this._renderTargets.push(_this._reflectionTexture);
  39549. }
  39550. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39551. _this._renderTargets.push(_this._refractionTexture);
  39552. }
  39553. return _this._renderTargets;
  39554. };
  39555. return _this;
  39556. }
  39557. ;
  39558. ;
  39559. ;
  39560. ;
  39561. ;
  39562. ;
  39563. ;
  39564. ;
  39565. ;
  39566. ;
  39567. ;
  39568. ;
  39569. ;
  39570. ;
  39571. ;
  39572. ;
  39573. ;
  39574. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39575. /**
  39576. * Gets the image processing configuration used either in this material.
  39577. */
  39578. get: function () {
  39579. return this._imageProcessingConfiguration;
  39580. },
  39581. /**
  39582. * Sets the Default image processing configuration used either in the this material.
  39583. *
  39584. * If sets to null, the scene one is in use.
  39585. */
  39586. set: function (value) {
  39587. this._attachImageProcessingConfiguration(value);
  39588. // Ensure the effect will be rebuilt.
  39589. this._markAllSubMeshesAsTexturesDirty();
  39590. },
  39591. enumerable: true,
  39592. configurable: true
  39593. });
  39594. /**
  39595. * Attaches a new image processing configuration to the Standard Material.
  39596. * @param configuration
  39597. */
  39598. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39599. var _this = this;
  39600. if (configuration === this._imageProcessingConfiguration) {
  39601. return;
  39602. }
  39603. // Detaches observer.
  39604. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39605. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39606. }
  39607. // Pick the scene configuration if needed.
  39608. if (!configuration) {
  39609. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39610. }
  39611. else {
  39612. this._imageProcessingConfiguration = configuration;
  39613. }
  39614. // Attaches observer.
  39615. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39616. _this._markAllSubMeshesAsImageProcessingDirty();
  39617. });
  39618. };
  39619. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39620. /**
  39621. * Gets wether the color curves effect is enabled.
  39622. */
  39623. get: function () {
  39624. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39625. },
  39626. /**
  39627. * Sets wether the color curves effect is enabled.
  39628. */
  39629. set: function (value) {
  39630. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39631. },
  39632. enumerable: true,
  39633. configurable: true
  39634. });
  39635. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39636. /**
  39637. * Gets wether the color grading effect is enabled.
  39638. */
  39639. get: function () {
  39640. return this.imageProcessingConfiguration.colorGradingEnabled;
  39641. },
  39642. /**
  39643. * Gets wether the color grading effect is enabled.
  39644. */
  39645. set: function (value) {
  39646. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39647. },
  39648. enumerable: true,
  39649. configurable: true
  39650. });
  39651. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39652. /**
  39653. * Gets wether tonemapping is enabled or not.
  39654. */
  39655. get: function () {
  39656. return this._imageProcessingConfiguration.toneMappingEnabled;
  39657. },
  39658. /**
  39659. * Sets wether tonemapping is enabled or not
  39660. */
  39661. set: function (value) {
  39662. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39663. },
  39664. enumerable: true,
  39665. configurable: true
  39666. });
  39667. ;
  39668. ;
  39669. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39670. /**
  39671. * The camera exposure used on this material.
  39672. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39673. * This corresponds to a photographic exposure.
  39674. */
  39675. get: function () {
  39676. return this._imageProcessingConfiguration.exposure;
  39677. },
  39678. /**
  39679. * The camera exposure used on this material.
  39680. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39681. * This corresponds to a photographic exposure.
  39682. */
  39683. set: function (value) {
  39684. this._imageProcessingConfiguration.exposure = value;
  39685. },
  39686. enumerable: true,
  39687. configurable: true
  39688. });
  39689. ;
  39690. ;
  39691. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39692. /**
  39693. * Gets The camera contrast used on this material.
  39694. */
  39695. get: function () {
  39696. return this._imageProcessingConfiguration.contrast;
  39697. },
  39698. /**
  39699. * Sets The camera contrast used on this material.
  39700. */
  39701. set: function (value) {
  39702. this._imageProcessingConfiguration.contrast = value;
  39703. },
  39704. enumerable: true,
  39705. configurable: true
  39706. });
  39707. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39708. /**
  39709. * Gets the Color Grading 2D Lookup Texture.
  39710. */
  39711. get: function () {
  39712. return this._imageProcessingConfiguration.colorGradingTexture;
  39713. },
  39714. /**
  39715. * Sets the Color Grading 2D Lookup Texture.
  39716. */
  39717. set: function (value) {
  39718. this._imageProcessingConfiguration.colorGradingTexture = value;
  39719. },
  39720. enumerable: true,
  39721. configurable: true
  39722. });
  39723. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39724. /**
  39725. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39726. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39727. * 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;
  39728. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39729. */
  39730. get: function () {
  39731. return this._imageProcessingConfiguration.colorCurves;
  39732. },
  39733. /**
  39734. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39735. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39736. * 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;
  39737. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39738. */
  39739. set: function (value) {
  39740. this._imageProcessingConfiguration.colorCurves = value;
  39741. },
  39742. enumerable: true,
  39743. configurable: true
  39744. });
  39745. StandardMaterial.prototype.getClassName = function () {
  39746. return "StandardMaterial";
  39747. };
  39748. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39749. get: function () {
  39750. return this._useLogarithmicDepth;
  39751. },
  39752. set: function (value) {
  39753. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39754. this._markAllSubMeshesAsMiscDirty();
  39755. },
  39756. enumerable: true,
  39757. configurable: true
  39758. });
  39759. StandardMaterial.prototype.needAlphaBlending = function () {
  39760. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39761. };
  39762. StandardMaterial.prototype.needAlphaTesting = function () {
  39763. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39764. };
  39765. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39766. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39767. };
  39768. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39769. return this._diffuseTexture;
  39770. };
  39771. /**
  39772. * Child classes can use it to update shaders
  39773. */
  39774. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39775. if (useInstances === void 0) { useInstances = false; }
  39776. if (subMesh.effect && this.isFrozen) {
  39777. if (this._wasPreviouslyReady && subMesh.effect) {
  39778. return true;
  39779. }
  39780. }
  39781. if (!subMesh._materialDefines) {
  39782. subMesh._materialDefines = new StandardMaterialDefines();
  39783. }
  39784. var scene = this.getScene();
  39785. var defines = subMesh._materialDefines;
  39786. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39787. if (defines._renderId === scene.getRenderId()) {
  39788. return true;
  39789. }
  39790. }
  39791. var engine = scene.getEngine();
  39792. // Lights
  39793. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39794. // Textures
  39795. if (defines._areTexturesDirty) {
  39796. defines._needUVs = false;
  39797. defines.MAINUV1 = false;
  39798. defines.MAINUV2 = false;
  39799. if (scene.texturesEnabled) {
  39800. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39801. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39802. return false;
  39803. }
  39804. else {
  39805. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39806. }
  39807. }
  39808. else {
  39809. defines.DIFFUSE = false;
  39810. }
  39811. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39812. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39813. return false;
  39814. }
  39815. else {
  39816. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39817. }
  39818. }
  39819. else {
  39820. defines.AMBIENT = false;
  39821. }
  39822. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39823. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39824. return false;
  39825. }
  39826. else {
  39827. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39828. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39829. }
  39830. }
  39831. else {
  39832. defines.OPACITY = false;
  39833. }
  39834. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39835. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39836. return false;
  39837. }
  39838. else {
  39839. defines._needNormals = true;
  39840. defines.REFLECTION = true;
  39841. defines.ROUGHNESS = (this._roughness > 0);
  39842. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39843. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39844. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39845. switch (this._reflectionTexture.coordinatesMode) {
  39846. case BABYLON.Texture.CUBIC_MODE:
  39847. case BABYLON.Texture.INVCUBIC_MODE:
  39848. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39849. break;
  39850. case BABYLON.Texture.EXPLICIT_MODE:
  39851. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39852. break;
  39853. case BABYLON.Texture.PLANAR_MODE:
  39854. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39855. break;
  39856. case BABYLON.Texture.PROJECTION_MODE:
  39857. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39858. break;
  39859. case BABYLON.Texture.SKYBOX_MODE:
  39860. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39861. break;
  39862. case BABYLON.Texture.SPHERICAL_MODE:
  39863. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39864. break;
  39865. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39866. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39867. break;
  39868. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39869. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39870. break;
  39871. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39872. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39873. break;
  39874. }
  39875. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39876. }
  39877. }
  39878. else {
  39879. defines.REFLECTION = false;
  39880. }
  39881. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39882. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39883. return false;
  39884. }
  39885. else {
  39886. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39887. }
  39888. }
  39889. else {
  39890. defines.EMISSIVE = false;
  39891. }
  39892. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39893. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39894. return false;
  39895. }
  39896. else {
  39897. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39898. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39899. }
  39900. }
  39901. else {
  39902. defines.LIGHTMAP = false;
  39903. }
  39904. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39905. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39906. return false;
  39907. }
  39908. else {
  39909. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39910. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39911. }
  39912. }
  39913. else {
  39914. defines.SPECULAR = false;
  39915. }
  39916. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39917. // Bump texure can not be not blocking.
  39918. if (!this._bumpTexture.isReady()) {
  39919. return false;
  39920. }
  39921. else {
  39922. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39923. defines.PARALLAX = this._useParallax;
  39924. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39925. }
  39926. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39927. }
  39928. else {
  39929. defines.BUMP = false;
  39930. }
  39931. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39932. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39933. return false;
  39934. }
  39935. else {
  39936. defines._needUVs = true;
  39937. defines.REFRACTION = true;
  39938. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39939. }
  39940. }
  39941. else {
  39942. defines.REFRACTION = false;
  39943. }
  39944. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39945. }
  39946. else {
  39947. defines.DIFFUSE = false;
  39948. defines.AMBIENT = false;
  39949. defines.OPACITY = false;
  39950. defines.REFLECTION = false;
  39951. defines.EMISSIVE = false;
  39952. defines.LIGHTMAP = false;
  39953. defines.BUMP = false;
  39954. defines.REFRACTION = false;
  39955. }
  39956. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39957. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39958. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39959. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39960. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39961. }
  39962. if (defines._areImageProcessingDirty) {
  39963. if (!this._imageProcessingConfiguration.isReady()) {
  39964. return false;
  39965. }
  39966. this._imageProcessingConfiguration.prepareDefines(defines);
  39967. }
  39968. if (defines._areFresnelDirty) {
  39969. if (StandardMaterial.FresnelEnabled) {
  39970. // Fresnel
  39971. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39972. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39973. this._reflectionFresnelParameters) {
  39974. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39975. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39976. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39977. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39978. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39979. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39980. defines._needNormals = true;
  39981. defines.FRESNEL = true;
  39982. }
  39983. }
  39984. else {
  39985. defines.FRESNEL = false;
  39986. }
  39987. }
  39988. // Misc.
  39989. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39990. // Attribs
  39991. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39992. // Values that need to be evaluated on every frame
  39993. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39994. // Get correct effect
  39995. if (defines.isDirty) {
  39996. defines.markAsProcessed();
  39997. scene.resetCachedMaterial();
  39998. // Fallbacks
  39999. var fallbacks = new BABYLON.EffectFallbacks();
  40000. if (defines.REFLECTION) {
  40001. fallbacks.addFallback(0, "REFLECTION");
  40002. }
  40003. if (defines.SPECULAR) {
  40004. fallbacks.addFallback(0, "SPECULAR");
  40005. }
  40006. if (defines.BUMP) {
  40007. fallbacks.addFallback(0, "BUMP");
  40008. }
  40009. if (defines.PARALLAX) {
  40010. fallbacks.addFallback(1, "PARALLAX");
  40011. }
  40012. if (defines.PARALLAXOCCLUSION) {
  40013. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40014. }
  40015. if (defines.SPECULAROVERALPHA) {
  40016. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40017. }
  40018. if (defines.FOG) {
  40019. fallbacks.addFallback(1, "FOG");
  40020. }
  40021. if (defines.POINTSIZE) {
  40022. fallbacks.addFallback(0, "POINTSIZE");
  40023. }
  40024. if (defines.LOGARITHMICDEPTH) {
  40025. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40026. }
  40027. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40028. if (defines.SPECULARTERM) {
  40029. fallbacks.addFallback(0, "SPECULARTERM");
  40030. }
  40031. if (defines.DIFFUSEFRESNEL) {
  40032. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40033. }
  40034. if (defines.OPACITYFRESNEL) {
  40035. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40036. }
  40037. if (defines.REFLECTIONFRESNEL) {
  40038. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40039. }
  40040. if (defines.EMISSIVEFRESNEL) {
  40041. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40042. }
  40043. if (defines.FRESNEL) {
  40044. fallbacks.addFallback(4, "FRESNEL");
  40045. }
  40046. //Attributes
  40047. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40048. if (defines.NORMAL) {
  40049. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40050. }
  40051. if (defines.UV1) {
  40052. attribs.push(BABYLON.VertexBuffer.UVKind);
  40053. }
  40054. if (defines.UV2) {
  40055. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40056. }
  40057. if (defines.VERTEXCOLOR) {
  40058. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40059. }
  40060. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40061. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40062. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40063. var shaderName = "default";
  40064. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40065. "vFogInfos", "vFogColor", "pointSize",
  40066. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40067. "mBones",
  40068. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40069. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40070. "vReflectionPosition", "vReflectionSize",
  40071. "logarithmicDepthConstant", "vTangentSpaceParams"
  40072. ];
  40073. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40074. var uniformBuffers = ["Material", "Scene"];
  40075. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40076. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40077. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40078. uniformsNames: uniforms,
  40079. uniformBuffersNames: uniformBuffers,
  40080. samplers: samplers,
  40081. defines: defines,
  40082. maxSimultaneousLights: this._maxSimultaneousLights
  40083. });
  40084. if (this.customShaderNameResolve) {
  40085. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40086. }
  40087. var join = defines.toString();
  40088. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40089. attributes: attribs,
  40090. uniformsNames: uniforms,
  40091. uniformBuffersNames: uniformBuffers,
  40092. samplers: samplers,
  40093. defines: join,
  40094. fallbacks: fallbacks,
  40095. onCompiled: this.onCompiled,
  40096. onError: this.onError,
  40097. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40098. }, engine), defines);
  40099. this.buildUniformLayout();
  40100. }
  40101. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40102. return false;
  40103. }
  40104. defines._renderId = scene.getRenderId();
  40105. this._wasPreviouslyReady = true;
  40106. return true;
  40107. };
  40108. StandardMaterial.prototype.buildUniformLayout = function () {
  40109. // Order is important !
  40110. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40111. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40112. this._uniformBuffer.addUniform("opacityParts", 4);
  40113. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40114. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40115. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40116. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40117. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40118. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40119. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40120. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40121. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40122. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40123. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40124. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40125. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40126. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40127. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40128. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40129. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40130. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40131. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40132. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40133. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40134. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40135. this._uniformBuffer.addUniform("specularMatrix", 16);
  40136. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40137. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40138. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40139. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40140. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40141. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40142. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40143. this._uniformBuffer.addUniform("pointSize", 1);
  40144. this._uniformBuffer.create();
  40145. };
  40146. StandardMaterial.prototype.unbind = function () {
  40147. if (this._activeEffect) {
  40148. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40149. this._activeEffect.setTexture("reflection2DSampler", null);
  40150. }
  40151. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40152. this._activeEffect.setTexture("refraction2DSampler", null);
  40153. }
  40154. }
  40155. _super.prototype.unbind.call(this);
  40156. };
  40157. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40158. var scene = this.getScene();
  40159. var defines = subMesh._materialDefines;
  40160. if (!defines) {
  40161. return;
  40162. }
  40163. var effect = subMesh.effect;
  40164. if (!effect) {
  40165. return;
  40166. }
  40167. this._activeEffect = effect;
  40168. // Matrices
  40169. this.bindOnlyWorldMatrix(world);
  40170. // Normal Matrix
  40171. if (defines.OBJECTSPACE_NORMALMAP) {
  40172. world.toNormalMatrix(this._normalMatrix);
  40173. this.bindOnlyNormalMatrix(this._normalMatrix);
  40174. }
  40175. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40176. // Bones
  40177. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40178. if (mustRebind) {
  40179. this._uniformBuffer.bindToEffect(effect, "Material");
  40180. this.bindViewProjection(effect);
  40181. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40182. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40183. // Fresnel
  40184. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40185. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40186. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40187. }
  40188. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40189. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40190. }
  40191. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40192. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40193. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40194. }
  40195. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40196. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40197. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40198. }
  40199. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40200. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40201. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40202. }
  40203. }
  40204. // Textures
  40205. if (scene.texturesEnabled) {
  40206. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40207. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40208. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40209. }
  40210. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40211. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40212. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40213. }
  40214. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40215. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40216. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40217. }
  40218. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40219. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40220. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40221. if (this._reflectionTexture.boundingBoxSize) {
  40222. var cubeTexture = this._reflectionTexture;
  40223. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40224. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40225. }
  40226. }
  40227. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40228. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40229. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40230. }
  40231. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40232. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40233. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40234. }
  40235. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40236. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40237. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40238. }
  40239. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40240. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40241. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40242. if (scene._mirroredCameraPosition) {
  40243. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40244. }
  40245. else {
  40246. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40247. }
  40248. }
  40249. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40250. var depth = 1.0;
  40251. if (!this._refractionTexture.isCube) {
  40252. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40253. if (this._refractionTexture.depth) {
  40254. depth = this._refractionTexture.depth;
  40255. }
  40256. }
  40257. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40258. }
  40259. }
  40260. // Point size
  40261. if (this.pointsCloud) {
  40262. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40263. }
  40264. if (defines.SPECULARTERM) {
  40265. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40266. }
  40267. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40268. // Diffuse
  40269. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40270. }
  40271. // Textures
  40272. if (scene.texturesEnabled) {
  40273. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40274. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40275. }
  40276. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40277. effect.setTexture("ambientSampler", this._ambientTexture);
  40278. }
  40279. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40280. effect.setTexture("opacitySampler", this._opacityTexture);
  40281. }
  40282. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40283. if (this._reflectionTexture.isCube) {
  40284. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40285. }
  40286. else {
  40287. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40288. }
  40289. }
  40290. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40291. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40292. }
  40293. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40294. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40295. }
  40296. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40297. effect.setTexture("specularSampler", this._specularTexture);
  40298. }
  40299. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40300. effect.setTexture("bumpSampler", this._bumpTexture);
  40301. }
  40302. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40303. var depth = 1.0;
  40304. if (this._refractionTexture.isCube) {
  40305. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40306. }
  40307. else {
  40308. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40309. }
  40310. }
  40311. }
  40312. // Clip plane
  40313. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40314. // Colors
  40315. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40316. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40317. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40318. }
  40319. if (mustRebind || !this.isFrozen) {
  40320. // Lights
  40321. if (scene.lightsEnabled && !this._disableLighting) {
  40322. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40323. }
  40324. // View
  40325. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40326. this.bindView(effect);
  40327. }
  40328. // Fog
  40329. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40330. // Morph targets
  40331. if (defines.NUM_MORPH_INFLUENCERS) {
  40332. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40333. }
  40334. // Log. depth
  40335. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40336. // image processing
  40337. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40338. this._imageProcessingConfiguration.bind(this._activeEffect);
  40339. }
  40340. }
  40341. this._uniformBuffer.update();
  40342. this._afterBind(mesh, this._activeEffect);
  40343. };
  40344. StandardMaterial.prototype.getAnimatables = function () {
  40345. var results = [];
  40346. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40347. results.push(this._diffuseTexture);
  40348. }
  40349. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40350. results.push(this._ambientTexture);
  40351. }
  40352. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40353. results.push(this._opacityTexture);
  40354. }
  40355. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40356. results.push(this._reflectionTexture);
  40357. }
  40358. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40359. results.push(this._emissiveTexture);
  40360. }
  40361. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40362. results.push(this._specularTexture);
  40363. }
  40364. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40365. results.push(this._bumpTexture);
  40366. }
  40367. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40368. results.push(this._lightmapTexture);
  40369. }
  40370. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40371. results.push(this._refractionTexture);
  40372. }
  40373. return results;
  40374. };
  40375. StandardMaterial.prototype.getActiveTextures = function () {
  40376. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40377. if (this._diffuseTexture) {
  40378. activeTextures.push(this._diffuseTexture);
  40379. }
  40380. if (this._ambientTexture) {
  40381. activeTextures.push(this._ambientTexture);
  40382. }
  40383. if (this._opacityTexture) {
  40384. activeTextures.push(this._opacityTexture);
  40385. }
  40386. if (this._reflectionTexture) {
  40387. activeTextures.push(this._reflectionTexture);
  40388. }
  40389. if (this._emissiveTexture) {
  40390. activeTextures.push(this._emissiveTexture);
  40391. }
  40392. if (this._specularTexture) {
  40393. activeTextures.push(this._specularTexture);
  40394. }
  40395. if (this._bumpTexture) {
  40396. activeTextures.push(this._bumpTexture);
  40397. }
  40398. if (this._lightmapTexture) {
  40399. activeTextures.push(this._lightmapTexture);
  40400. }
  40401. if (this._refractionTexture) {
  40402. activeTextures.push(this._refractionTexture);
  40403. }
  40404. return activeTextures;
  40405. };
  40406. StandardMaterial.prototype.hasTexture = function (texture) {
  40407. if (_super.prototype.hasTexture.call(this, texture)) {
  40408. return true;
  40409. }
  40410. if (this._diffuseTexture === texture) {
  40411. return true;
  40412. }
  40413. if (this._ambientTexture === texture) {
  40414. return true;
  40415. }
  40416. if (this._opacityTexture === texture) {
  40417. return true;
  40418. }
  40419. if (this._reflectionTexture === texture) {
  40420. return true;
  40421. }
  40422. if (this._emissiveTexture === texture) {
  40423. return true;
  40424. }
  40425. if (this._specularTexture === texture) {
  40426. return true;
  40427. }
  40428. if (this._bumpTexture === texture) {
  40429. return true;
  40430. }
  40431. if (this._lightmapTexture === texture) {
  40432. return true;
  40433. }
  40434. if (this._refractionTexture === texture) {
  40435. return true;
  40436. }
  40437. return false;
  40438. };
  40439. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40440. if (forceDisposeTextures) {
  40441. if (this._diffuseTexture) {
  40442. this._diffuseTexture.dispose();
  40443. }
  40444. if (this._ambientTexture) {
  40445. this._ambientTexture.dispose();
  40446. }
  40447. if (this._opacityTexture) {
  40448. this._opacityTexture.dispose();
  40449. }
  40450. if (this._reflectionTexture) {
  40451. this._reflectionTexture.dispose();
  40452. }
  40453. if (this._emissiveTexture) {
  40454. this._emissiveTexture.dispose();
  40455. }
  40456. if (this._specularTexture) {
  40457. this._specularTexture.dispose();
  40458. }
  40459. if (this._bumpTexture) {
  40460. this._bumpTexture.dispose();
  40461. }
  40462. if (this._lightmapTexture) {
  40463. this._lightmapTexture.dispose();
  40464. }
  40465. if (this._refractionTexture) {
  40466. this._refractionTexture.dispose();
  40467. }
  40468. }
  40469. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40470. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40471. }
  40472. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40473. };
  40474. StandardMaterial.prototype.clone = function (name) {
  40475. var _this = this;
  40476. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40477. result.name = name;
  40478. result.id = name;
  40479. return result;
  40480. };
  40481. StandardMaterial.prototype.serialize = function () {
  40482. return BABYLON.SerializationHelper.Serialize(this);
  40483. };
  40484. // Statics
  40485. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40486. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40487. };
  40488. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40489. get: function () {
  40490. return StandardMaterial._DiffuseTextureEnabled;
  40491. },
  40492. set: function (value) {
  40493. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40494. return;
  40495. }
  40496. StandardMaterial._DiffuseTextureEnabled = value;
  40497. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40498. },
  40499. enumerable: true,
  40500. configurable: true
  40501. });
  40502. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40503. get: function () {
  40504. return StandardMaterial._AmbientTextureEnabled;
  40505. },
  40506. set: function (value) {
  40507. if (StandardMaterial._AmbientTextureEnabled === value) {
  40508. return;
  40509. }
  40510. StandardMaterial._AmbientTextureEnabled = value;
  40511. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40512. },
  40513. enumerable: true,
  40514. configurable: true
  40515. });
  40516. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40517. get: function () {
  40518. return StandardMaterial._OpacityTextureEnabled;
  40519. },
  40520. set: function (value) {
  40521. if (StandardMaterial._OpacityTextureEnabled === value) {
  40522. return;
  40523. }
  40524. StandardMaterial._OpacityTextureEnabled = value;
  40525. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40526. },
  40527. enumerable: true,
  40528. configurable: true
  40529. });
  40530. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40531. get: function () {
  40532. return StandardMaterial._ReflectionTextureEnabled;
  40533. },
  40534. set: function (value) {
  40535. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40536. return;
  40537. }
  40538. StandardMaterial._ReflectionTextureEnabled = value;
  40539. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40540. },
  40541. enumerable: true,
  40542. configurable: true
  40543. });
  40544. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40545. get: function () {
  40546. return StandardMaterial._EmissiveTextureEnabled;
  40547. },
  40548. set: function (value) {
  40549. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40550. return;
  40551. }
  40552. StandardMaterial._EmissiveTextureEnabled = value;
  40553. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40554. },
  40555. enumerable: true,
  40556. configurable: true
  40557. });
  40558. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40559. get: function () {
  40560. return StandardMaterial._SpecularTextureEnabled;
  40561. },
  40562. set: function (value) {
  40563. if (StandardMaterial._SpecularTextureEnabled === value) {
  40564. return;
  40565. }
  40566. StandardMaterial._SpecularTextureEnabled = value;
  40567. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40568. },
  40569. enumerable: true,
  40570. configurable: true
  40571. });
  40572. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40573. get: function () {
  40574. return StandardMaterial._BumpTextureEnabled;
  40575. },
  40576. set: function (value) {
  40577. if (StandardMaterial._BumpTextureEnabled === value) {
  40578. return;
  40579. }
  40580. StandardMaterial._BumpTextureEnabled = value;
  40581. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40582. },
  40583. enumerable: true,
  40584. configurable: true
  40585. });
  40586. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40587. get: function () {
  40588. return StandardMaterial._LightmapTextureEnabled;
  40589. },
  40590. set: function (value) {
  40591. if (StandardMaterial._LightmapTextureEnabled === value) {
  40592. return;
  40593. }
  40594. StandardMaterial._LightmapTextureEnabled = value;
  40595. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40596. },
  40597. enumerable: true,
  40598. configurable: true
  40599. });
  40600. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40601. get: function () {
  40602. return StandardMaterial._RefractionTextureEnabled;
  40603. },
  40604. set: function (value) {
  40605. if (StandardMaterial._RefractionTextureEnabled === value) {
  40606. return;
  40607. }
  40608. StandardMaterial._RefractionTextureEnabled = value;
  40609. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40610. },
  40611. enumerable: true,
  40612. configurable: true
  40613. });
  40614. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40615. get: function () {
  40616. return StandardMaterial._ColorGradingTextureEnabled;
  40617. },
  40618. set: function (value) {
  40619. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40620. return;
  40621. }
  40622. StandardMaterial._ColorGradingTextureEnabled = value;
  40623. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40624. },
  40625. enumerable: true,
  40626. configurable: true
  40627. });
  40628. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40629. get: function () {
  40630. return StandardMaterial._FresnelEnabled;
  40631. },
  40632. set: function (value) {
  40633. if (StandardMaterial._FresnelEnabled === value) {
  40634. return;
  40635. }
  40636. StandardMaterial._FresnelEnabled = value;
  40637. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40638. },
  40639. enumerable: true,
  40640. configurable: true
  40641. });
  40642. // Flags used to enable or disable a type of texture for all Standard Materials
  40643. StandardMaterial._DiffuseTextureEnabled = true;
  40644. StandardMaterial._AmbientTextureEnabled = true;
  40645. StandardMaterial._OpacityTextureEnabled = true;
  40646. StandardMaterial._ReflectionTextureEnabled = true;
  40647. StandardMaterial._EmissiveTextureEnabled = true;
  40648. StandardMaterial._SpecularTextureEnabled = true;
  40649. StandardMaterial._BumpTextureEnabled = true;
  40650. StandardMaterial._LightmapTextureEnabled = true;
  40651. StandardMaterial._RefractionTextureEnabled = true;
  40652. StandardMaterial._ColorGradingTextureEnabled = true;
  40653. StandardMaterial._FresnelEnabled = true;
  40654. __decorate([
  40655. BABYLON.serializeAsTexture("diffuseTexture")
  40656. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40657. __decorate([
  40658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40659. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40660. __decorate([
  40661. BABYLON.serializeAsTexture("ambientTexture")
  40662. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40663. __decorate([
  40664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40665. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40666. __decorate([
  40667. BABYLON.serializeAsTexture("opacityTexture")
  40668. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40669. __decorate([
  40670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40671. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40672. __decorate([
  40673. BABYLON.serializeAsTexture("reflectionTexture")
  40674. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40675. __decorate([
  40676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40677. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40678. __decorate([
  40679. BABYLON.serializeAsTexture("emissiveTexture")
  40680. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40681. __decorate([
  40682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40683. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40684. __decorate([
  40685. BABYLON.serializeAsTexture("specularTexture")
  40686. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40687. __decorate([
  40688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40689. ], StandardMaterial.prototype, "specularTexture", void 0);
  40690. __decorate([
  40691. BABYLON.serializeAsTexture("bumpTexture")
  40692. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40693. __decorate([
  40694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40695. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40696. __decorate([
  40697. BABYLON.serializeAsTexture("lightmapTexture")
  40698. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40699. __decorate([
  40700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40701. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40702. __decorate([
  40703. BABYLON.serializeAsTexture("refractionTexture")
  40704. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40705. __decorate([
  40706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40707. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40708. __decorate([
  40709. BABYLON.serializeAsColor3("ambient")
  40710. ], StandardMaterial.prototype, "ambientColor", void 0);
  40711. __decorate([
  40712. BABYLON.serializeAsColor3("diffuse")
  40713. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40714. __decorate([
  40715. BABYLON.serializeAsColor3("specular")
  40716. ], StandardMaterial.prototype, "specularColor", void 0);
  40717. __decorate([
  40718. BABYLON.serializeAsColor3("emissive")
  40719. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40720. __decorate([
  40721. BABYLON.serialize()
  40722. ], StandardMaterial.prototype, "specularPower", void 0);
  40723. __decorate([
  40724. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40725. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40726. __decorate([
  40727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40728. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40729. __decorate([
  40730. BABYLON.serialize("useEmissiveAsIllumination")
  40731. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40732. __decorate([
  40733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40734. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40735. __decorate([
  40736. BABYLON.serialize("linkEmissiveWithDiffuse")
  40737. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40738. __decorate([
  40739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40740. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40741. __decorate([
  40742. BABYLON.serialize("useSpecularOverAlpha")
  40743. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40744. __decorate([
  40745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40746. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40747. __decorate([
  40748. BABYLON.serialize("useReflectionOverAlpha")
  40749. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40750. __decorate([
  40751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40752. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40753. __decorate([
  40754. BABYLON.serialize("disableLighting")
  40755. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40756. __decorate([
  40757. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40758. ], StandardMaterial.prototype, "disableLighting", void 0);
  40759. __decorate([
  40760. BABYLON.serialize("useObjectSpaceNormalMap")
  40761. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40762. __decorate([
  40763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40764. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40765. __decorate([
  40766. BABYLON.serialize("useParallax")
  40767. ], StandardMaterial.prototype, "_useParallax", void 0);
  40768. __decorate([
  40769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40770. ], StandardMaterial.prototype, "useParallax", void 0);
  40771. __decorate([
  40772. BABYLON.serialize("useParallaxOcclusion")
  40773. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40774. __decorate([
  40775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40776. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40777. __decorate([
  40778. BABYLON.serialize()
  40779. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40780. __decorate([
  40781. BABYLON.serialize("roughness")
  40782. ], StandardMaterial.prototype, "_roughness", void 0);
  40783. __decorate([
  40784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40785. ], StandardMaterial.prototype, "roughness", void 0);
  40786. __decorate([
  40787. BABYLON.serialize()
  40788. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40789. __decorate([
  40790. BABYLON.serialize()
  40791. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40792. __decorate([
  40793. BABYLON.serialize("useLightmapAsShadowmap")
  40794. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40795. __decorate([
  40796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40797. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40798. __decorate([
  40799. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40800. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40801. __decorate([
  40802. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40803. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40804. __decorate([
  40805. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40806. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40807. __decorate([
  40808. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40809. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40810. __decorate([
  40811. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40812. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40813. __decorate([
  40814. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40815. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40816. __decorate([
  40817. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40818. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40819. __decorate([
  40820. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40821. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40822. __decorate([
  40823. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40824. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40825. __decorate([
  40826. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40827. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40828. __decorate([
  40829. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40830. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40831. __decorate([
  40832. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40833. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40834. __decorate([
  40835. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40836. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40837. __decorate([
  40838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40839. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40840. __decorate([
  40841. BABYLON.serialize("maxSimultaneousLights")
  40842. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40843. __decorate([
  40844. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40845. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40846. __decorate([
  40847. BABYLON.serialize("invertNormalMapX")
  40848. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40849. __decorate([
  40850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40851. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40852. __decorate([
  40853. BABYLON.serialize("invertNormalMapY")
  40854. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40855. __decorate([
  40856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40857. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40858. __decorate([
  40859. BABYLON.serialize("twoSidedLighting")
  40860. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40861. __decorate([
  40862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40863. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40864. __decorate([
  40865. BABYLON.serialize()
  40866. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40867. return StandardMaterial;
  40868. }(BABYLON.PushMaterial));
  40869. BABYLON.StandardMaterial = StandardMaterial;
  40870. })(BABYLON || (BABYLON = {}));
  40871. //# sourceMappingURL=babylon.standardMaterial.js.map
  40872. "use strict";
  40873. var BABYLON;
  40874. (function (BABYLON) {
  40875. /**
  40876. * Manages the defines for the PBR Material.
  40877. */
  40878. var PBRMaterialDefines = /** @class */ (function (_super) {
  40879. __extends(PBRMaterialDefines, _super);
  40880. /**
  40881. * Initializes the PBR Material defines.
  40882. */
  40883. function PBRMaterialDefines() {
  40884. var _this = _super.call(this) || this;
  40885. _this.PBR = true;
  40886. _this.MAINUV1 = false;
  40887. _this.MAINUV2 = false;
  40888. _this.UV1 = false;
  40889. _this.UV2 = false;
  40890. _this.ALBEDO = false;
  40891. _this.ALBEDODIRECTUV = 0;
  40892. _this.VERTEXCOLOR = false;
  40893. _this.AMBIENT = false;
  40894. _this.AMBIENTDIRECTUV = 0;
  40895. _this.AMBIENTINGRAYSCALE = false;
  40896. _this.OPACITY = false;
  40897. _this.VERTEXALPHA = false;
  40898. _this.OPACITYDIRECTUV = 0;
  40899. _this.OPACITYRGB = false;
  40900. _this.ALPHATEST = false;
  40901. _this.DEPTHPREPASS = false;
  40902. _this.ALPHABLEND = false;
  40903. _this.ALPHAFROMALBEDO = false;
  40904. _this.ALPHATESTVALUE = "0.5";
  40905. _this.SPECULAROVERALPHA = false;
  40906. _this.RADIANCEOVERALPHA = false;
  40907. _this.ALPHAFRESNEL = false;
  40908. _this.LINEARALPHAFRESNEL = false;
  40909. _this.PREMULTIPLYALPHA = false;
  40910. _this.EMISSIVE = false;
  40911. _this.EMISSIVEDIRECTUV = 0;
  40912. _this.REFLECTIVITY = false;
  40913. _this.REFLECTIVITYDIRECTUV = 0;
  40914. _this.SPECULARTERM = false;
  40915. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40916. _this.MICROSURFACEAUTOMATIC = false;
  40917. _this.LODBASEDMICROSFURACE = false;
  40918. _this.MICROSURFACEMAP = false;
  40919. _this.MICROSURFACEMAPDIRECTUV = 0;
  40920. _this.METALLICWORKFLOW = false;
  40921. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40922. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40923. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40924. _this.AOSTOREINMETALMAPRED = false;
  40925. _this.ENVIRONMENTBRDF = false;
  40926. _this.NORMAL = false;
  40927. _this.TANGENT = false;
  40928. _this.BUMP = false;
  40929. _this.BUMPDIRECTUV = 0;
  40930. _this.OBJECTSPACE_NORMALMAP = false;
  40931. _this.PARALLAX = false;
  40932. _this.PARALLAXOCCLUSION = false;
  40933. _this.NORMALXYSCALE = true;
  40934. _this.LIGHTMAP = false;
  40935. _this.LIGHTMAPDIRECTUV = 0;
  40936. _this.USELIGHTMAPASSHADOWMAP = false;
  40937. _this.GAMMALIGHTMAP = false;
  40938. _this.REFLECTION = false;
  40939. _this.REFLECTIONMAP_3D = false;
  40940. _this.REFLECTIONMAP_SPHERICAL = false;
  40941. _this.REFLECTIONMAP_PLANAR = false;
  40942. _this.REFLECTIONMAP_CUBIC = false;
  40943. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40944. _this.REFLECTIONMAP_PROJECTION = false;
  40945. _this.REFLECTIONMAP_SKYBOX = false;
  40946. _this.REFLECTIONMAP_EXPLICIT = false;
  40947. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40948. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40949. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40950. _this.INVERTCUBICMAP = false;
  40951. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40952. _this.USESPHERICALINVERTEX = false;
  40953. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40954. _this.LODINREFLECTIONALPHA = false;
  40955. _this.GAMMAREFLECTION = false;
  40956. _this.RADIANCEOCCLUSION = false;
  40957. _this.HORIZONOCCLUSION = false;
  40958. _this.REFRACTION = false;
  40959. _this.REFRACTIONMAP_3D = false;
  40960. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40961. _this.LODINREFRACTIONALPHA = false;
  40962. _this.GAMMAREFRACTION = false;
  40963. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40964. _this.INSTANCES = false;
  40965. _this.NUM_BONE_INFLUENCERS = 0;
  40966. _this.BonesPerMesh = 0;
  40967. _this.NONUNIFORMSCALING = false;
  40968. _this.MORPHTARGETS = false;
  40969. _this.MORPHTARGETS_NORMAL = false;
  40970. _this.MORPHTARGETS_TANGENT = false;
  40971. _this.NUM_MORPH_INFLUENCERS = 0;
  40972. _this.IMAGEPROCESSING = false;
  40973. _this.VIGNETTE = false;
  40974. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40975. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40976. _this.TONEMAPPING = false;
  40977. _this.CONTRAST = false;
  40978. _this.COLORCURVES = false;
  40979. _this.COLORGRADING = false;
  40980. _this.COLORGRADING3D = false;
  40981. _this.SAMPLER3DGREENDEPTH = false;
  40982. _this.SAMPLER3DBGRMAP = false;
  40983. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40984. _this.EXPOSURE = false;
  40985. _this.GRAIN = false;
  40986. _this.USEPHYSICALLIGHTFALLOFF = false;
  40987. _this.TWOSIDEDLIGHTING = false;
  40988. _this.SHADOWFLOAT = false;
  40989. _this.CLIPPLANE = false;
  40990. _this.POINTSIZE = false;
  40991. _this.FOG = false;
  40992. _this.LOGARITHMICDEPTH = false;
  40993. _this.FORCENORMALFORWARD = false;
  40994. _this.UNLIT = false;
  40995. _this.rebuild();
  40996. return _this;
  40997. }
  40998. /**
  40999. * Resets the PBR Material defines.
  41000. */
  41001. PBRMaterialDefines.prototype.reset = function () {
  41002. _super.prototype.reset.call(this);
  41003. this.ALPHATESTVALUE = "0.5";
  41004. this.PBR = true;
  41005. };
  41006. return PBRMaterialDefines;
  41007. }(BABYLON.MaterialDefines));
  41008. /**
  41009. * The Physically based material base class of BJS.
  41010. *
  41011. * This offers the main features of a standard PBR material.
  41012. * For more information, please refer to the documentation :
  41013. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41014. */
  41015. var PBRBaseMaterial = /** @class */ (function (_super) {
  41016. __extends(PBRBaseMaterial, _super);
  41017. /**
  41018. * Instantiates a new PBRMaterial instance.
  41019. *
  41020. * @param name The material name
  41021. * @param scene The scene the material will be use in.
  41022. */
  41023. function PBRBaseMaterial(name, scene) {
  41024. var _this = _super.call(this, name, scene) || this;
  41025. /**
  41026. * Intensity of the direct lights e.g. the four lights available in your scene.
  41027. * This impacts both the direct diffuse and specular highlights.
  41028. */
  41029. _this._directIntensity = 1.0;
  41030. /**
  41031. * Intensity of the emissive part of the material.
  41032. * This helps controlling the emissive effect without modifying the emissive color.
  41033. */
  41034. _this._emissiveIntensity = 1.0;
  41035. /**
  41036. * Intensity of the environment e.g. how much the environment will light the object
  41037. * either through harmonics for rough material or through the refelction for shiny ones.
  41038. */
  41039. _this._environmentIntensity = 1.0;
  41040. /**
  41041. * This is a special control allowing the reduction of the specular highlights coming from the
  41042. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41043. */
  41044. _this._specularIntensity = 1.0;
  41045. /**
  41046. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41047. */
  41048. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41049. /**
  41050. * Debug Control allowing disabling the bump map on this material.
  41051. */
  41052. _this._disableBumpMap = false;
  41053. /**
  41054. * AKA Occlusion Texture Intensity in other nomenclature.
  41055. */
  41056. _this._ambientTextureStrength = 1.0;
  41057. /**
  41058. * The color of a material in ambient lighting.
  41059. */
  41060. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41061. /**
  41062. * AKA Diffuse Color in other nomenclature.
  41063. */
  41064. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41065. /**
  41066. * AKA Specular Color in other nomenclature.
  41067. */
  41068. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41069. /**
  41070. * The color applied when light is reflected from a material.
  41071. */
  41072. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41073. /**
  41074. * The color applied when light is emitted from a material.
  41075. */
  41076. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41077. /**
  41078. * AKA Glossiness in other nomenclature.
  41079. */
  41080. _this._microSurface = 0.9;
  41081. /**
  41082. * source material index of refraction (IOR)' / 'destination material IOR.
  41083. */
  41084. _this._indexOfRefraction = 0.66;
  41085. /**
  41086. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41087. */
  41088. _this._invertRefractionY = false;
  41089. /**
  41090. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41091. * Materials half opaque for instance using refraction could benefit from this control.
  41092. */
  41093. _this._linkRefractionWithTransparency = false;
  41094. /**
  41095. * Specifies that the material will use the light map as a show map.
  41096. */
  41097. _this._useLightmapAsShadowmap = false;
  41098. /**
  41099. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41100. * makes the reflect vector face the model (under horizon).
  41101. */
  41102. _this._useHorizonOcclusion = true;
  41103. /**
  41104. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41105. * too much the area relying on ambient texture to define their ambient occlusion.
  41106. */
  41107. _this._useRadianceOcclusion = true;
  41108. /**
  41109. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41110. */
  41111. _this._useAlphaFromAlbedoTexture = false;
  41112. /**
  41113. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41114. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41115. */
  41116. _this._useSpecularOverAlpha = true;
  41117. /**
  41118. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41119. */
  41120. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41121. /**
  41122. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41123. */
  41124. _this._useRoughnessFromMetallicTextureAlpha = true;
  41125. /**
  41126. * Specifies if the metallic texture contains the roughness information in its green channel.
  41127. */
  41128. _this._useRoughnessFromMetallicTextureGreen = false;
  41129. /**
  41130. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41131. */
  41132. _this._useMetallnessFromMetallicTextureBlue = false;
  41133. /**
  41134. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41135. */
  41136. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41137. /**
  41138. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41139. */
  41140. _this._useAmbientInGrayScale = false;
  41141. /**
  41142. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41143. * The material will try to infer what glossiness each pixel should be.
  41144. */
  41145. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41146. /**
  41147. * BJS is using an harcoded light falloff based on a manually sets up range.
  41148. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41149. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41150. */
  41151. _this._usePhysicalLightFalloff = true;
  41152. /**
  41153. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41154. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41155. */
  41156. _this._useRadianceOverAlpha = true;
  41157. /**
  41158. * Allows using an object space normal map (instead of tangent space).
  41159. */
  41160. _this._useObjectSpaceNormalMap = false;
  41161. /**
  41162. * Allows using the bump map in parallax mode.
  41163. */
  41164. _this._useParallax = false;
  41165. /**
  41166. * Allows using the bump map in parallax occlusion mode.
  41167. */
  41168. _this._useParallaxOcclusion = false;
  41169. /**
  41170. * Controls the scale bias of the parallax mode.
  41171. */
  41172. _this._parallaxScaleBias = 0.05;
  41173. /**
  41174. * If sets to true, disables all the lights affecting the material.
  41175. */
  41176. _this._disableLighting = false;
  41177. /**
  41178. * Number of Simultaneous lights allowed on the material.
  41179. */
  41180. _this._maxSimultaneousLights = 4;
  41181. /**
  41182. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41183. */
  41184. _this._invertNormalMapX = false;
  41185. /**
  41186. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41187. */
  41188. _this._invertNormalMapY = false;
  41189. /**
  41190. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41191. */
  41192. _this._twoSidedLighting = false;
  41193. /**
  41194. * Defines the alpha limits in alpha test mode.
  41195. */
  41196. _this._alphaCutOff = 0.4;
  41197. /**
  41198. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41199. */
  41200. _this._forceAlphaTest = false;
  41201. /**
  41202. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41203. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41204. */
  41205. _this._useAlphaFresnel = false;
  41206. /**
  41207. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41208. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41209. */
  41210. _this._useLinearAlphaFresnel = false;
  41211. /**
  41212. * The transparency mode of the material.
  41213. */
  41214. _this._transparencyMode = null;
  41215. /**
  41216. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41217. * from cos thetav and roughness:
  41218. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41219. */
  41220. _this._environmentBRDFTexture = null;
  41221. /**
  41222. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41223. */
  41224. _this._forceIrradianceInFragment = false;
  41225. /**
  41226. * Force normal to face away from face.
  41227. */
  41228. _this._forceNormalForward = false;
  41229. /**
  41230. * Stores the available render targets.
  41231. */
  41232. _this._renderTargets = new BABYLON.SmartArray(16);
  41233. /**
  41234. * Sets the global ambient color for the material used in lighting calculations.
  41235. */
  41236. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41237. /**
  41238. * If set to true, no lighting calculations will be applied.
  41239. */
  41240. _this._unlit = false;
  41241. // Setup the default processing configuration to the scene.
  41242. _this._attachImageProcessingConfiguration(null);
  41243. _this.getRenderTargetTextures = function () {
  41244. _this._renderTargets.reset();
  41245. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41246. _this._renderTargets.push(_this._reflectionTexture);
  41247. }
  41248. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41249. _this._renderTargets.push(_this._refractionTexture);
  41250. }
  41251. return _this._renderTargets;
  41252. };
  41253. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41254. return _this;
  41255. }
  41256. /**
  41257. * Attaches a new image processing configuration to the PBR Material.
  41258. * @param configuration
  41259. */
  41260. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41261. var _this = this;
  41262. if (configuration === this._imageProcessingConfiguration) {
  41263. return;
  41264. }
  41265. // Detaches observer.
  41266. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41267. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41268. }
  41269. // Pick the scene configuration if needed.
  41270. if (!configuration) {
  41271. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41272. }
  41273. else {
  41274. this._imageProcessingConfiguration = configuration;
  41275. }
  41276. // Attaches observer.
  41277. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41278. _this._markAllSubMeshesAsImageProcessingDirty();
  41279. });
  41280. };
  41281. /**
  41282. * Gets the name of the material class.
  41283. */
  41284. PBRBaseMaterial.prototype.getClassName = function () {
  41285. return "PBRBaseMaterial";
  41286. };
  41287. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41288. /**
  41289. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41290. */
  41291. get: function () {
  41292. return this._useLogarithmicDepth;
  41293. },
  41294. /**
  41295. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41296. */
  41297. set: function (value) {
  41298. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41299. },
  41300. enumerable: true,
  41301. configurable: true
  41302. });
  41303. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41304. /**
  41305. * Gets the current transparency mode.
  41306. */
  41307. get: function () {
  41308. return this._transparencyMode;
  41309. },
  41310. /**
  41311. * Sets the transparency mode of the material.
  41312. */
  41313. set: function (value) {
  41314. if (this._transparencyMode === value) {
  41315. return;
  41316. }
  41317. this._transparencyMode = value;
  41318. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41319. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41320. },
  41321. enumerable: true,
  41322. configurable: true
  41323. });
  41324. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41325. /**
  41326. * Returns true if alpha blending should be disabled.
  41327. */
  41328. get: function () {
  41329. return (this._linkRefractionWithTransparency ||
  41330. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41331. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41332. },
  41333. enumerable: true,
  41334. configurable: true
  41335. });
  41336. /**
  41337. * Specifies whether or not this material should be rendered in alpha blend mode.
  41338. */
  41339. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41340. if (this._disableAlphaBlending) {
  41341. return false;
  41342. }
  41343. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41344. };
  41345. /**
  41346. * Specifies if the mesh will require alpha blending.
  41347. * @param mesh - BJS mesh.
  41348. */
  41349. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41350. if (this._disableAlphaBlending) {
  41351. return false;
  41352. }
  41353. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41354. };
  41355. /**
  41356. * Specifies whether or not this material should be rendered in alpha test mode.
  41357. */
  41358. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41359. if (this._forceAlphaTest) {
  41360. return true;
  41361. }
  41362. if (this._linkRefractionWithTransparency) {
  41363. return false;
  41364. }
  41365. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41366. };
  41367. /**
  41368. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41369. */
  41370. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41371. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41372. };
  41373. /**
  41374. * Gets the texture used for the alpha test.
  41375. */
  41376. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41377. return this._albedoTexture;
  41378. };
  41379. /**
  41380. * Specifies that the submesh is ready to be used.
  41381. * @param mesh - BJS mesh.
  41382. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41383. * @param useInstances - Specifies that instances should be used.
  41384. * @returns - boolean indicating that the submesh is ready or not.
  41385. */
  41386. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41387. if (subMesh.effect && this.isFrozen) {
  41388. if (this._wasPreviouslyReady) {
  41389. return true;
  41390. }
  41391. }
  41392. if (!subMesh._materialDefines) {
  41393. subMesh._materialDefines = new PBRMaterialDefines();
  41394. }
  41395. var defines = subMesh._materialDefines;
  41396. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41397. if (defines._renderId === this.getScene().getRenderId()) {
  41398. return true;
  41399. }
  41400. }
  41401. var scene = this.getScene();
  41402. var engine = scene.getEngine();
  41403. if (defines._areTexturesDirty) {
  41404. if (scene.texturesEnabled) {
  41405. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41406. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41407. return false;
  41408. }
  41409. }
  41410. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41411. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41412. return false;
  41413. }
  41414. }
  41415. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41416. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41417. return false;
  41418. }
  41419. }
  41420. var reflectionTexture = this._getReflectionTexture();
  41421. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41422. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41423. return false;
  41424. }
  41425. }
  41426. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41427. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41428. return false;
  41429. }
  41430. }
  41431. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41432. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41433. return false;
  41434. }
  41435. }
  41436. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41437. if (this._metallicTexture) {
  41438. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41439. return false;
  41440. }
  41441. }
  41442. else if (this._reflectivityTexture) {
  41443. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41444. return false;
  41445. }
  41446. }
  41447. if (this._microSurfaceTexture) {
  41448. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41449. return false;
  41450. }
  41451. }
  41452. }
  41453. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41454. // Bump texture cannot be not blocking.
  41455. if (!this._bumpTexture.isReady()) {
  41456. return false;
  41457. }
  41458. }
  41459. var refractionTexture = this._getRefractionTexture();
  41460. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41461. if (!refractionTexture.isReadyOrNotBlocking()) {
  41462. return false;
  41463. }
  41464. }
  41465. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41466. // This is blocking.
  41467. if (!this._environmentBRDFTexture.isReady()) {
  41468. return false;
  41469. }
  41470. }
  41471. }
  41472. }
  41473. if (defines._areImageProcessingDirty) {
  41474. if (!this._imageProcessingConfiguration.isReady()) {
  41475. return false;
  41476. }
  41477. }
  41478. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41479. mesh.createNormals(true);
  41480. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41481. }
  41482. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41483. if (effect) {
  41484. scene.resetCachedMaterial();
  41485. subMesh.setEffect(effect, defines);
  41486. this.buildUniformLayout();
  41487. }
  41488. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41489. return false;
  41490. }
  41491. defines._renderId = scene.getRenderId();
  41492. this._wasPreviouslyReady = true;
  41493. return true;
  41494. };
  41495. /**
  41496. * Specifies if the material uses metallic roughness workflow.
  41497. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41498. */
  41499. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41500. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41501. return true;
  41502. }
  41503. return false;
  41504. };
  41505. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41506. if (onCompiled === void 0) { onCompiled = null; }
  41507. if (onError === void 0) { onError = null; }
  41508. if (useInstances === void 0) { useInstances = null; }
  41509. if (useClipPlane === void 0) { useClipPlane = null; }
  41510. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41511. if (!defines.isDirty) {
  41512. return null;
  41513. }
  41514. defines.markAsProcessed();
  41515. var scene = this.getScene();
  41516. var engine = scene.getEngine();
  41517. // Fallbacks
  41518. var fallbacks = new BABYLON.EffectFallbacks();
  41519. var fallbackRank = 0;
  41520. if (defines.USESPHERICALINVERTEX) {
  41521. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41522. }
  41523. if (defines.FOG) {
  41524. fallbacks.addFallback(fallbackRank, "FOG");
  41525. }
  41526. if (defines.POINTSIZE) {
  41527. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41528. }
  41529. if (defines.LOGARITHMICDEPTH) {
  41530. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41531. }
  41532. if (defines.PARALLAX) {
  41533. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41534. }
  41535. if (defines.PARALLAXOCCLUSION) {
  41536. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41537. }
  41538. if (defines.ENVIRONMENTBRDF) {
  41539. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41540. }
  41541. if (defines.TANGENT) {
  41542. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41543. }
  41544. if (defines.BUMP) {
  41545. fallbacks.addFallback(fallbackRank++, "BUMP");
  41546. }
  41547. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41548. if (defines.SPECULARTERM) {
  41549. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41550. }
  41551. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41552. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41553. }
  41554. if (defines.LIGHTMAP) {
  41555. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41556. }
  41557. if (defines.NORMAL) {
  41558. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41559. }
  41560. if (defines.AMBIENT) {
  41561. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41562. }
  41563. if (defines.EMISSIVE) {
  41564. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41565. }
  41566. if (defines.VERTEXCOLOR) {
  41567. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41568. }
  41569. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41570. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41571. }
  41572. if (defines.MORPHTARGETS) {
  41573. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41574. }
  41575. //Attributes
  41576. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41577. if (defines.NORMAL) {
  41578. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41579. }
  41580. if (defines.TANGENT) {
  41581. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41582. }
  41583. if (defines.UV1) {
  41584. attribs.push(BABYLON.VertexBuffer.UVKind);
  41585. }
  41586. if (defines.UV2) {
  41587. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41588. }
  41589. if (defines.VERTEXCOLOR) {
  41590. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41591. }
  41592. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41593. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41594. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41595. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41596. "vFogInfos", "vFogColor", "pointSize",
  41597. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41598. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41599. "mBones",
  41600. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41601. "vLightingIntensity",
  41602. "logarithmicDepthConstant",
  41603. "vSphericalX", "vSphericalY", "vSphericalZ",
  41604. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41605. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41606. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41607. "vTangentSpaceParams"
  41608. ];
  41609. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41610. "bumpSampler", "lightmapSampler", "opacitySampler",
  41611. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41612. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41613. "microSurfaceSampler", "environmentBrdfSampler"];
  41614. var uniformBuffers = ["Material", "Scene"];
  41615. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41616. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41617. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41618. uniformsNames: uniforms,
  41619. uniformBuffersNames: uniformBuffers,
  41620. samplers: samplers,
  41621. defines: defines,
  41622. maxSimultaneousLights: this._maxSimultaneousLights
  41623. });
  41624. var join = defines.toString();
  41625. return engine.createEffect("pbr", {
  41626. attributes: attribs,
  41627. uniformsNames: uniforms,
  41628. uniformBuffersNames: uniformBuffers,
  41629. samplers: samplers,
  41630. defines: join,
  41631. fallbacks: fallbacks,
  41632. onCompiled: onCompiled,
  41633. onError: onError,
  41634. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41635. }, engine);
  41636. };
  41637. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41638. if (useInstances === void 0) { useInstances = null; }
  41639. if (useClipPlane === void 0) { useClipPlane = null; }
  41640. var scene = this.getScene();
  41641. var engine = scene.getEngine();
  41642. // Lights
  41643. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41644. defines._needNormals = true;
  41645. // Textures
  41646. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41647. if (defines._areTexturesDirty) {
  41648. defines._needUVs = false;
  41649. if (scene.texturesEnabled) {
  41650. if (scene.getEngine().getCaps().textureLOD) {
  41651. defines.LODBASEDMICROSFURACE = true;
  41652. }
  41653. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41654. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41655. }
  41656. else {
  41657. defines.ALBEDO = false;
  41658. }
  41659. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41660. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41661. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41662. }
  41663. else {
  41664. defines.AMBIENT = false;
  41665. }
  41666. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41667. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41668. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41669. }
  41670. else {
  41671. defines.OPACITY = false;
  41672. }
  41673. var reflectionTexture = this._getReflectionTexture();
  41674. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41675. defines.REFLECTION = true;
  41676. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41677. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41678. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41679. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41680. defines.INVERTCUBICMAP = true;
  41681. }
  41682. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41683. switch (reflectionTexture.coordinatesMode) {
  41684. case BABYLON.Texture.CUBIC_MODE:
  41685. case BABYLON.Texture.INVCUBIC_MODE:
  41686. defines.REFLECTIONMAP_CUBIC = true;
  41687. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41688. break;
  41689. case BABYLON.Texture.EXPLICIT_MODE:
  41690. defines.REFLECTIONMAP_EXPLICIT = true;
  41691. break;
  41692. case BABYLON.Texture.PLANAR_MODE:
  41693. defines.REFLECTIONMAP_PLANAR = true;
  41694. break;
  41695. case BABYLON.Texture.PROJECTION_MODE:
  41696. defines.REFLECTIONMAP_PROJECTION = true;
  41697. break;
  41698. case BABYLON.Texture.SKYBOX_MODE:
  41699. defines.REFLECTIONMAP_SKYBOX = true;
  41700. break;
  41701. case BABYLON.Texture.SPHERICAL_MODE:
  41702. defines.REFLECTIONMAP_SPHERICAL = true;
  41703. break;
  41704. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41705. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41706. break;
  41707. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41708. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41709. break;
  41710. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41711. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41712. break;
  41713. }
  41714. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41715. if (reflectionTexture.sphericalPolynomial) {
  41716. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41717. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41718. defines.USESPHERICALINVERTEX = false;
  41719. }
  41720. else {
  41721. defines.USESPHERICALINVERTEX = true;
  41722. }
  41723. }
  41724. }
  41725. }
  41726. else {
  41727. defines.REFLECTION = false;
  41728. defines.REFLECTIONMAP_3D = false;
  41729. defines.REFLECTIONMAP_SPHERICAL = false;
  41730. defines.REFLECTIONMAP_PLANAR = false;
  41731. defines.REFLECTIONMAP_CUBIC = false;
  41732. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41733. defines.REFLECTIONMAP_PROJECTION = false;
  41734. defines.REFLECTIONMAP_SKYBOX = false;
  41735. defines.REFLECTIONMAP_EXPLICIT = false;
  41736. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41737. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41738. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41739. defines.INVERTCUBICMAP = false;
  41740. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41741. defines.USESPHERICALINVERTEX = false;
  41742. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41743. defines.LODINREFLECTIONALPHA = false;
  41744. defines.GAMMAREFLECTION = false;
  41745. }
  41746. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41747. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41748. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41749. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41750. }
  41751. else {
  41752. defines.LIGHTMAP = false;
  41753. }
  41754. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41755. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41756. }
  41757. else {
  41758. defines.EMISSIVE = false;
  41759. }
  41760. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41761. if (this._metallicTexture) {
  41762. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41763. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41764. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41765. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41766. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41767. }
  41768. else if (this._reflectivityTexture) {
  41769. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41770. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41771. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41772. }
  41773. else {
  41774. defines.REFLECTIVITY = false;
  41775. }
  41776. if (this._microSurfaceTexture) {
  41777. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41778. }
  41779. else {
  41780. defines.MICROSURFACEMAP = false;
  41781. }
  41782. }
  41783. else {
  41784. defines.REFLECTIVITY = false;
  41785. defines.MICROSURFACEMAP = false;
  41786. }
  41787. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41788. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41789. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41790. defines.PARALLAX = true;
  41791. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41792. }
  41793. else {
  41794. defines.PARALLAX = false;
  41795. }
  41796. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41797. }
  41798. else {
  41799. defines.BUMP = false;
  41800. }
  41801. var refractionTexture = this._getRefractionTexture();
  41802. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41803. defines.REFRACTION = true;
  41804. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41805. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41806. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41807. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41808. if (this._linkRefractionWithTransparency) {
  41809. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41810. }
  41811. }
  41812. else {
  41813. defines.REFRACTION = false;
  41814. }
  41815. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41816. defines.ENVIRONMENTBRDF = true;
  41817. }
  41818. else {
  41819. defines.ENVIRONMENTBRDF = false;
  41820. }
  41821. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41822. defines.ALPHAFROMALBEDO = true;
  41823. }
  41824. else {
  41825. defines.ALPHAFROMALBEDO = false;
  41826. }
  41827. }
  41828. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41829. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41830. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41831. if (!this.backFaceCulling && this._twoSidedLighting) {
  41832. defines.TWOSIDEDLIGHTING = true;
  41833. }
  41834. else {
  41835. defines.TWOSIDEDLIGHTING = false;
  41836. }
  41837. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41838. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41839. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41840. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41841. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41842. }
  41843. if (defines._areImageProcessingDirty) {
  41844. this._imageProcessingConfiguration.prepareDefines(defines);
  41845. }
  41846. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41847. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41848. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41849. // Misc.
  41850. if (defines._areMiscDirty) {
  41851. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41852. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41853. }
  41854. // Values that need to be evaluated on every frame
  41855. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41856. // Attribs
  41857. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41858. };
  41859. /**
  41860. * Force shader compilation
  41861. */
  41862. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41863. var _this = this;
  41864. var localOptions = __assign({ clipPlane: false }, options);
  41865. var defines = new PBRMaterialDefines();
  41866. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41867. if (effect.isReady()) {
  41868. if (onCompiled) {
  41869. onCompiled(this);
  41870. }
  41871. }
  41872. else {
  41873. effect.onCompileObservable.add(function () {
  41874. if (onCompiled) {
  41875. onCompiled(_this);
  41876. }
  41877. });
  41878. }
  41879. };
  41880. /**
  41881. * Initializes the uniform buffer layout for the shader.
  41882. */
  41883. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41884. // Order is important !
  41885. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41886. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41887. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41888. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41889. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41890. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41891. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41892. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41893. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41894. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41895. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41896. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41897. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41898. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41899. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41900. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41901. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41902. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41903. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41904. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41905. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41906. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41907. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41908. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41909. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41910. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41911. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41912. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41913. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41914. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41915. this._uniformBuffer.addUniform("pointSize", 1);
  41916. this._uniformBuffer.create();
  41917. };
  41918. /**
  41919. * Unbinds the textures.
  41920. */
  41921. PBRBaseMaterial.prototype.unbind = function () {
  41922. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41923. this._uniformBuffer.setTexture("reflectionSampler", null);
  41924. }
  41925. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41926. this._uniformBuffer.setTexture("refractionSampler", null);
  41927. }
  41928. _super.prototype.unbind.call(this);
  41929. };
  41930. /**
  41931. * Binds the submesh data.
  41932. * @param world - The world matrix.
  41933. * @param mesh - The BJS mesh.
  41934. * @param subMesh - A submesh of the BJS mesh.
  41935. */
  41936. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41937. var scene = this.getScene();
  41938. var defines = subMesh._materialDefines;
  41939. if (!defines) {
  41940. return;
  41941. }
  41942. var effect = subMesh.effect;
  41943. if (!effect) {
  41944. return;
  41945. }
  41946. this._activeEffect = effect;
  41947. // Matrices
  41948. this.bindOnlyWorldMatrix(world);
  41949. // Normal Matrix
  41950. if (defines.OBJECTSPACE_NORMALMAP) {
  41951. world.toNormalMatrix(this._normalMatrix);
  41952. this.bindOnlyNormalMatrix(this._normalMatrix);
  41953. }
  41954. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41955. // Bones
  41956. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41957. var reflectionTexture = null;
  41958. if (mustRebind) {
  41959. this._uniformBuffer.bindToEffect(effect, "Material");
  41960. this.bindViewProjection(effect);
  41961. reflectionTexture = this._getReflectionTexture();
  41962. var refractionTexture = this._getRefractionTexture();
  41963. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41964. // Texture uniforms
  41965. if (scene.texturesEnabled) {
  41966. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41967. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41968. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41969. }
  41970. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41971. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41972. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41973. }
  41974. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41975. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41976. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41977. }
  41978. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41979. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41980. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41981. if (reflectionTexture.boundingBoxSize) {
  41982. var cubeTexture = reflectionTexture;
  41983. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41984. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41985. }
  41986. var polynomials = reflectionTexture.sphericalPolynomial;
  41987. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41988. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41989. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41990. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41991. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41992. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41993. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41994. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41995. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41996. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41997. }
  41998. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41999. }
  42000. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42001. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42002. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42003. }
  42004. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42005. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42006. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42007. }
  42008. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42009. if (this._metallicTexture) {
  42010. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  42011. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  42012. }
  42013. else if (this._reflectivityTexture) {
  42014. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42015. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42016. }
  42017. if (this._microSurfaceTexture) {
  42018. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42019. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42020. }
  42021. }
  42022. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42023. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42024. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42025. if (scene._mirroredCameraPosition) {
  42026. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42027. }
  42028. else {
  42029. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42030. }
  42031. }
  42032. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42033. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42034. var depth = 1.0;
  42035. if (!refractionTexture.isCube) {
  42036. if (refractionTexture.depth) {
  42037. depth = refractionTexture.depth;
  42038. }
  42039. }
  42040. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42041. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42042. }
  42043. }
  42044. // Point size
  42045. if (this.pointsCloud) {
  42046. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42047. }
  42048. // Colors
  42049. if (defines.METALLICWORKFLOW) {
  42050. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42051. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42052. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42053. }
  42054. else {
  42055. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42056. }
  42057. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42058. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42059. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42060. // Misc
  42061. this._lightingInfos.x = this._directIntensity;
  42062. this._lightingInfos.y = this._emissiveIntensity;
  42063. this._lightingInfos.z = this._environmentIntensity;
  42064. this._lightingInfos.w = this._specularIntensity;
  42065. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42066. }
  42067. // Textures
  42068. if (scene.texturesEnabled) {
  42069. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42070. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42071. }
  42072. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42073. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42074. }
  42075. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42076. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42077. }
  42078. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42079. if (defines.LODBASEDMICROSFURACE) {
  42080. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42081. }
  42082. else {
  42083. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42084. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42085. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42086. }
  42087. }
  42088. if (defines.ENVIRONMENTBRDF) {
  42089. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42090. }
  42091. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42092. if (defines.LODBASEDMICROSFURACE) {
  42093. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42094. }
  42095. else {
  42096. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42097. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42098. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42099. }
  42100. }
  42101. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42102. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42103. }
  42104. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42105. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42106. }
  42107. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42108. if (this._metallicTexture) {
  42109. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42110. }
  42111. else if (this._reflectivityTexture) {
  42112. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42113. }
  42114. if (this._microSurfaceTexture) {
  42115. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42116. }
  42117. }
  42118. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42119. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42120. }
  42121. }
  42122. // Clip plane
  42123. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42124. // Colors
  42125. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42126. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42127. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42128. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42129. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42130. }
  42131. if (mustRebind || !this.isFrozen) {
  42132. // Lights
  42133. if (scene.lightsEnabled && !this._disableLighting) {
  42134. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42135. }
  42136. // View
  42137. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42138. this.bindView(effect);
  42139. }
  42140. // Fog
  42141. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42142. // Morph targets
  42143. if (defines.NUM_MORPH_INFLUENCERS) {
  42144. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42145. }
  42146. // image processing
  42147. this._imageProcessingConfiguration.bind(this._activeEffect);
  42148. // Log. depth
  42149. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42150. }
  42151. this._uniformBuffer.update();
  42152. this._afterBind(mesh);
  42153. };
  42154. /**
  42155. * Returns the animatable textures.
  42156. * @returns - Array of animatable textures.
  42157. */
  42158. PBRBaseMaterial.prototype.getAnimatables = function () {
  42159. var results = [];
  42160. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42161. results.push(this._albedoTexture);
  42162. }
  42163. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42164. results.push(this._ambientTexture);
  42165. }
  42166. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42167. results.push(this._opacityTexture);
  42168. }
  42169. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42170. results.push(this._reflectionTexture);
  42171. }
  42172. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42173. results.push(this._emissiveTexture);
  42174. }
  42175. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42176. results.push(this._metallicTexture);
  42177. }
  42178. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42179. results.push(this._reflectivityTexture);
  42180. }
  42181. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42182. results.push(this._bumpTexture);
  42183. }
  42184. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42185. results.push(this._lightmapTexture);
  42186. }
  42187. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42188. results.push(this._refractionTexture);
  42189. }
  42190. return results;
  42191. };
  42192. /**
  42193. * Returns the texture used for reflections.
  42194. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42195. */
  42196. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42197. if (this._reflectionTexture) {
  42198. return this._reflectionTexture;
  42199. }
  42200. return this.getScene().environmentTexture;
  42201. };
  42202. /**
  42203. * Returns the texture used for refraction or null if none is used.
  42204. * @returns - Refection texture if present. If no refraction texture and refraction
  42205. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42206. */
  42207. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42208. if (this._refractionTexture) {
  42209. return this._refractionTexture;
  42210. }
  42211. if (this._linkRefractionWithTransparency) {
  42212. return this.getScene().environmentTexture;
  42213. }
  42214. return null;
  42215. };
  42216. /**
  42217. * Disposes the resources of the material.
  42218. * @param forceDisposeEffect - Forces the disposal of effects.
  42219. * @param forceDisposeTextures - Forces the disposal of all textures.
  42220. */
  42221. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42222. if (forceDisposeTextures) {
  42223. if (this._albedoTexture) {
  42224. this._albedoTexture.dispose();
  42225. }
  42226. if (this._ambientTexture) {
  42227. this._ambientTexture.dispose();
  42228. }
  42229. if (this._opacityTexture) {
  42230. this._opacityTexture.dispose();
  42231. }
  42232. if (this._reflectionTexture) {
  42233. this._reflectionTexture.dispose();
  42234. }
  42235. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42236. this._environmentBRDFTexture.dispose();
  42237. }
  42238. if (this._emissiveTexture) {
  42239. this._emissiveTexture.dispose();
  42240. }
  42241. if (this._metallicTexture) {
  42242. this._metallicTexture.dispose();
  42243. }
  42244. if (this._reflectivityTexture) {
  42245. this._reflectivityTexture.dispose();
  42246. }
  42247. if (this._bumpTexture) {
  42248. this._bumpTexture.dispose();
  42249. }
  42250. if (this._lightmapTexture) {
  42251. this._lightmapTexture.dispose();
  42252. }
  42253. if (this._refractionTexture) {
  42254. this._refractionTexture.dispose();
  42255. }
  42256. }
  42257. this._renderTargets.dispose();
  42258. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42259. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42260. }
  42261. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42262. };
  42263. /**
  42264. * Stores the reflectivity values based on metallic roughness workflow.
  42265. */
  42266. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42267. __decorate([
  42268. BABYLON.serializeAsImageProcessingConfiguration()
  42269. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42270. __decorate([
  42271. BABYLON.serialize()
  42272. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42273. __decorate([
  42274. BABYLON.serialize()
  42275. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42276. return PBRBaseMaterial;
  42277. }(BABYLON.PushMaterial));
  42278. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42279. })(BABYLON || (BABYLON = {}));
  42280. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42281. "use strict";
  42282. var BABYLON;
  42283. (function (BABYLON) {
  42284. /**
  42285. * The Physically based simple base material of BJS.
  42286. *
  42287. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42288. * It is used as the base class for both the specGloss and metalRough conventions.
  42289. */
  42290. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42291. __extends(PBRBaseSimpleMaterial, _super);
  42292. /**
  42293. * Instantiates a new PBRMaterial instance.
  42294. *
  42295. * @param name The material name
  42296. * @param scene The scene the material will be use in.
  42297. */
  42298. function PBRBaseSimpleMaterial(name, scene) {
  42299. var _this = _super.call(this, name, scene) || this;
  42300. /**
  42301. * Number of Simultaneous lights allowed on the material.
  42302. */
  42303. _this.maxSimultaneousLights = 4;
  42304. /**
  42305. * If sets to true, disables all the lights affecting the material.
  42306. */
  42307. _this.disableLighting = false;
  42308. /**
  42309. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42310. */
  42311. _this.invertNormalMapX = false;
  42312. /**
  42313. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42314. */
  42315. _this.invertNormalMapY = false;
  42316. /**
  42317. * Emissivie color used to self-illuminate the model.
  42318. */
  42319. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42320. /**
  42321. * Occlusion Channel Strenght.
  42322. */
  42323. _this.occlusionStrength = 1.0;
  42324. _this.useLightmapAsShadowmap = false;
  42325. _this._useAlphaFromAlbedoTexture = true;
  42326. _this._useAmbientInGrayScale = true;
  42327. return _this;
  42328. }
  42329. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42330. /**
  42331. * Gets the current double sided mode.
  42332. */
  42333. get: function () {
  42334. return this._twoSidedLighting;
  42335. },
  42336. /**
  42337. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42338. */
  42339. set: function (value) {
  42340. if (this._twoSidedLighting === value) {
  42341. return;
  42342. }
  42343. this._twoSidedLighting = value;
  42344. this.backFaceCulling = !value;
  42345. this._markAllSubMeshesAsTexturesDirty();
  42346. },
  42347. enumerable: true,
  42348. configurable: true
  42349. });
  42350. /**
  42351. * Return the active textures of the material.
  42352. */
  42353. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42354. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42355. if (this.environmentTexture) {
  42356. activeTextures.push(this.environmentTexture);
  42357. }
  42358. if (this.normalTexture) {
  42359. activeTextures.push(this.normalTexture);
  42360. }
  42361. if (this.emissiveTexture) {
  42362. activeTextures.push(this.emissiveTexture);
  42363. }
  42364. if (this.occlusionTexture) {
  42365. activeTextures.push(this.occlusionTexture);
  42366. }
  42367. if (this.lightmapTexture) {
  42368. activeTextures.push(this.lightmapTexture);
  42369. }
  42370. return activeTextures;
  42371. };
  42372. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42373. if (_super.prototype.hasTexture.call(this, texture)) {
  42374. return true;
  42375. }
  42376. if (this.lightmapTexture === texture) {
  42377. return true;
  42378. }
  42379. return false;
  42380. };
  42381. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42382. return "PBRBaseSimpleMaterial";
  42383. };
  42384. __decorate([
  42385. BABYLON.serialize(),
  42386. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42387. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42388. __decorate([
  42389. BABYLON.serialize(),
  42390. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42391. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42392. __decorate([
  42393. BABYLON.serializeAsTexture(),
  42394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42395. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42396. __decorate([
  42397. BABYLON.serialize(),
  42398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42399. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42400. __decorate([
  42401. BABYLON.serialize(),
  42402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42403. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42404. __decorate([
  42405. BABYLON.serializeAsTexture(),
  42406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42407. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42408. __decorate([
  42409. BABYLON.serializeAsColor3("emissive"),
  42410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42411. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42412. __decorate([
  42413. BABYLON.serializeAsTexture(),
  42414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42415. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42416. __decorate([
  42417. BABYLON.serialize(),
  42418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42419. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42420. __decorate([
  42421. BABYLON.serializeAsTexture(),
  42422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42423. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42424. __decorate([
  42425. BABYLON.serialize(),
  42426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42427. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42428. __decorate([
  42429. BABYLON.serialize()
  42430. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42431. __decorate([
  42432. BABYLON.serializeAsTexture(),
  42433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42434. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42435. __decorate([
  42436. BABYLON.serialize(),
  42437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42438. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42439. return PBRBaseSimpleMaterial;
  42440. }(BABYLON.PBRBaseMaterial));
  42441. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42442. })(BABYLON || (BABYLON = {}));
  42443. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42444. "use strict";
  42445. var BABYLON;
  42446. (function (BABYLON) {
  42447. /**
  42448. * The Physically based material of BJS.
  42449. *
  42450. * This offers the main features of a standard PBR material.
  42451. * For more information, please refer to the documentation :
  42452. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42453. */
  42454. var PBRMaterial = /** @class */ (function (_super) {
  42455. __extends(PBRMaterial, _super);
  42456. /**
  42457. * Instantiates a new PBRMaterial instance.
  42458. *
  42459. * @param name The material name
  42460. * @param scene The scene the material will be use in.
  42461. */
  42462. function PBRMaterial(name, scene) {
  42463. var _this = _super.call(this, name, scene) || this;
  42464. /**
  42465. * Intensity of the direct lights e.g. the four lights available in your scene.
  42466. * This impacts both the direct diffuse and specular highlights.
  42467. */
  42468. _this.directIntensity = 1.0;
  42469. /**
  42470. * Intensity of the emissive part of the material.
  42471. * This helps controlling the emissive effect without modifying the emissive color.
  42472. */
  42473. _this.emissiveIntensity = 1.0;
  42474. /**
  42475. * Intensity of the environment e.g. how much the environment will light the object
  42476. * either through harmonics for rough material or through the refelction for shiny ones.
  42477. */
  42478. _this.environmentIntensity = 1.0;
  42479. /**
  42480. * This is a special control allowing the reduction of the specular highlights coming from the
  42481. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42482. */
  42483. _this.specularIntensity = 1.0;
  42484. /**
  42485. * Debug Control allowing disabling the bump map on this material.
  42486. */
  42487. _this.disableBumpMap = false;
  42488. /**
  42489. * AKA Occlusion Texture Intensity in other nomenclature.
  42490. */
  42491. _this.ambientTextureStrength = 1.0;
  42492. /**
  42493. * The color of a material in ambient lighting.
  42494. */
  42495. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42496. /**
  42497. * AKA Diffuse Color in other nomenclature.
  42498. */
  42499. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42500. /**
  42501. * AKA Specular Color in other nomenclature.
  42502. */
  42503. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42504. /**
  42505. * The color reflected from the material.
  42506. */
  42507. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42508. /**
  42509. * The color emitted from the material.
  42510. */
  42511. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42512. /**
  42513. * AKA Glossiness in other nomenclature.
  42514. */
  42515. _this.microSurface = 1.0;
  42516. /**
  42517. * source material index of refraction (IOR)' / 'destination material IOR.
  42518. */
  42519. _this.indexOfRefraction = 0.66;
  42520. /**
  42521. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42522. */
  42523. _this.invertRefractionY = false;
  42524. /**
  42525. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42526. * Materials half opaque for instance using refraction could benefit from this control.
  42527. */
  42528. _this.linkRefractionWithTransparency = false;
  42529. _this.useLightmapAsShadowmap = false;
  42530. /**
  42531. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42532. */
  42533. _this.useAlphaFromAlbedoTexture = false;
  42534. /**
  42535. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42536. */
  42537. _this.forceAlphaTest = false;
  42538. /**
  42539. * Defines the alpha limits in alpha test mode.
  42540. */
  42541. _this.alphaCutOff = 0.4;
  42542. /**
  42543. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42544. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42545. */
  42546. _this.useSpecularOverAlpha = true;
  42547. /**
  42548. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42549. */
  42550. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42551. /**
  42552. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42553. */
  42554. _this.useRoughnessFromMetallicTextureAlpha = true;
  42555. /**
  42556. * Specifies if the metallic texture contains the roughness information in its green channel.
  42557. */
  42558. _this.useRoughnessFromMetallicTextureGreen = false;
  42559. /**
  42560. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42561. */
  42562. _this.useMetallnessFromMetallicTextureBlue = false;
  42563. /**
  42564. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42565. */
  42566. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42567. /**
  42568. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42569. */
  42570. _this.useAmbientInGrayScale = false;
  42571. /**
  42572. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42573. * The material will try to infer what glossiness each pixel should be.
  42574. */
  42575. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42576. /**
  42577. * BJS is using an harcoded light falloff based on a manually sets up range.
  42578. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42579. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42580. */
  42581. _this.usePhysicalLightFalloff = true;
  42582. /**
  42583. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42584. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42585. */
  42586. _this.useRadianceOverAlpha = true;
  42587. /**
  42588. * Allows using an object space normal map (instead of tangent space).
  42589. */
  42590. _this.useObjectSpaceNormalMap = false;
  42591. /**
  42592. * Allows using the bump map in parallax mode.
  42593. */
  42594. _this.useParallax = false;
  42595. /**
  42596. * Allows using the bump map in parallax occlusion mode.
  42597. */
  42598. _this.useParallaxOcclusion = false;
  42599. /**
  42600. * Controls the scale bias of the parallax mode.
  42601. */
  42602. _this.parallaxScaleBias = 0.05;
  42603. /**
  42604. * If sets to true, disables all the lights affecting the material.
  42605. */
  42606. _this.disableLighting = false;
  42607. /**
  42608. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42609. */
  42610. _this.forceIrradianceInFragment = false;
  42611. /**
  42612. * Number of Simultaneous lights allowed on the material.
  42613. */
  42614. _this.maxSimultaneousLights = 4;
  42615. /**
  42616. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42617. */
  42618. _this.invertNormalMapX = false;
  42619. /**
  42620. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42621. */
  42622. _this.invertNormalMapY = false;
  42623. /**
  42624. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42625. */
  42626. _this.twoSidedLighting = false;
  42627. /**
  42628. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42629. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42630. */
  42631. _this.useAlphaFresnel = false;
  42632. /**
  42633. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42634. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42635. */
  42636. _this.useLinearAlphaFresnel = false;
  42637. /**
  42638. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42639. * And/Or occlude the blended part.
  42640. */
  42641. _this.environmentBRDFTexture = null;
  42642. /**
  42643. * Force normal to face away from face.
  42644. */
  42645. _this.forceNormalForward = false;
  42646. /**
  42647. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42648. * makes the reflect vector face the model (under horizon).
  42649. */
  42650. _this.useHorizonOcclusion = true;
  42651. /**
  42652. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42653. * too much the area relying on ambient texture to define their ambient occlusion.
  42654. */
  42655. _this.useRadianceOcclusion = true;
  42656. /**
  42657. * If set to true, no lighting calculations will be applied.
  42658. */
  42659. _this.unlit = false;
  42660. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42661. return _this;
  42662. }
  42663. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42664. /**
  42665. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42666. */
  42667. get: function () {
  42668. return this._PBRMATERIAL_OPAQUE;
  42669. },
  42670. enumerable: true,
  42671. configurable: true
  42672. });
  42673. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42674. /**
  42675. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42676. */
  42677. get: function () {
  42678. return this._PBRMATERIAL_ALPHATEST;
  42679. },
  42680. enumerable: true,
  42681. configurable: true
  42682. });
  42683. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42684. /**
  42685. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42686. */
  42687. get: function () {
  42688. return this._PBRMATERIAL_ALPHABLEND;
  42689. },
  42690. enumerable: true,
  42691. configurable: true
  42692. });
  42693. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42694. /**
  42695. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42696. * They are also discarded below the alpha cutoff threshold to improve performances.
  42697. */
  42698. get: function () {
  42699. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42700. },
  42701. enumerable: true,
  42702. configurable: true
  42703. });
  42704. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42705. /**
  42706. * Gets the image processing configuration used either in this material.
  42707. */
  42708. get: function () {
  42709. return this._imageProcessingConfiguration;
  42710. },
  42711. /**
  42712. * Sets the Default image processing configuration used either in the this material.
  42713. *
  42714. * If sets to null, the scene one is in use.
  42715. */
  42716. set: function (value) {
  42717. this._attachImageProcessingConfiguration(value);
  42718. // Ensure the effect will be rebuilt.
  42719. this._markAllSubMeshesAsTexturesDirty();
  42720. },
  42721. enumerable: true,
  42722. configurable: true
  42723. });
  42724. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42725. /**
  42726. * Gets wether the color curves effect is enabled.
  42727. */
  42728. get: function () {
  42729. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42730. },
  42731. /**
  42732. * Sets wether the color curves effect is enabled.
  42733. */
  42734. set: function (value) {
  42735. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42736. },
  42737. enumerable: true,
  42738. configurable: true
  42739. });
  42740. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42741. /**
  42742. * Gets wether the color grading effect is enabled.
  42743. */
  42744. get: function () {
  42745. return this.imageProcessingConfiguration.colorGradingEnabled;
  42746. },
  42747. /**
  42748. * Gets wether the color grading effect is enabled.
  42749. */
  42750. set: function (value) {
  42751. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42752. },
  42753. enumerable: true,
  42754. configurable: true
  42755. });
  42756. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42757. /**
  42758. * Gets wether tonemapping is enabled or not.
  42759. */
  42760. get: function () {
  42761. return this._imageProcessingConfiguration.toneMappingEnabled;
  42762. },
  42763. /**
  42764. * Sets wether tonemapping is enabled or not
  42765. */
  42766. set: function (value) {
  42767. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42768. },
  42769. enumerable: true,
  42770. configurable: true
  42771. });
  42772. ;
  42773. ;
  42774. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42775. /**
  42776. * The camera exposure used on this material.
  42777. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42778. * This corresponds to a photographic exposure.
  42779. */
  42780. get: function () {
  42781. return this._imageProcessingConfiguration.exposure;
  42782. },
  42783. /**
  42784. * The camera exposure used on this material.
  42785. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42786. * This corresponds to a photographic exposure.
  42787. */
  42788. set: function (value) {
  42789. this._imageProcessingConfiguration.exposure = value;
  42790. },
  42791. enumerable: true,
  42792. configurable: true
  42793. });
  42794. ;
  42795. ;
  42796. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42797. /**
  42798. * Gets The camera contrast used on this material.
  42799. */
  42800. get: function () {
  42801. return this._imageProcessingConfiguration.contrast;
  42802. },
  42803. /**
  42804. * Sets The camera contrast used on this material.
  42805. */
  42806. set: function (value) {
  42807. this._imageProcessingConfiguration.contrast = value;
  42808. },
  42809. enumerable: true,
  42810. configurable: true
  42811. });
  42812. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42813. /**
  42814. * Gets the Color Grading 2D Lookup Texture.
  42815. */
  42816. get: function () {
  42817. return this._imageProcessingConfiguration.colorGradingTexture;
  42818. },
  42819. /**
  42820. * Sets the Color Grading 2D Lookup Texture.
  42821. */
  42822. set: function (value) {
  42823. this._imageProcessingConfiguration.colorGradingTexture = value;
  42824. },
  42825. enumerable: true,
  42826. configurable: true
  42827. });
  42828. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42829. /**
  42830. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42831. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42832. * 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;
  42833. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42834. */
  42835. get: function () {
  42836. return this._imageProcessingConfiguration.colorCurves;
  42837. },
  42838. /**
  42839. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42840. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42841. * 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;
  42842. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42843. */
  42844. set: function (value) {
  42845. this._imageProcessingConfiguration.colorCurves = value;
  42846. },
  42847. enumerable: true,
  42848. configurable: true
  42849. });
  42850. /**
  42851. * Returns the name of this material class.
  42852. */
  42853. PBRMaterial.prototype.getClassName = function () {
  42854. return "PBRMaterial";
  42855. };
  42856. /**
  42857. * Returns an array of the actively used textures.
  42858. * @returns - Array of BaseTextures
  42859. */
  42860. PBRMaterial.prototype.getActiveTextures = function () {
  42861. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42862. if (this._albedoTexture) {
  42863. activeTextures.push(this._albedoTexture);
  42864. }
  42865. if (this._ambientTexture) {
  42866. activeTextures.push(this._ambientTexture);
  42867. }
  42868. if (this._opacityTexture) {
  42869. activeTextures.push(this._opacityTexture);
  42870. }
  42871. if (this._reflectionTexture) {
  42872. activeTextures.push(this._reflectionTexture);
  42873. }
  42874. if (this._emissiveTexture) {
  42875. activeTextures.push(this._emissiveTexture);
  42876. }
  42877. if (this._reflectivityTexture) {
  42878. activeTextures.push(this._reflectivityTexture);
  42879. }
  42880. if (this._metallicTexture) {
  42881. activeTextures.push(this._metallicTexture);
  42882. }
  42883. if (this._microSurfaceTexture) {
  42884. activeTextures.push(this._microSurfaceTexture);
  42885. }
  42886. if (this._bumpTexture) {
  42887. activeTextures.push(this._bumpTexture);
  42888. }
  42889. if (this._lightmapTexture) {
  42890. activeTextures.push(this._lightmapTexture);
  42891. }
  42892. if (this._refractionTexture) {
  42893. activeTextures.push(this._refractionTexture);
  42894. }
  42895. return activeTextures;
  42896. };
  42897. /**
  42898. * Checks to see if a texture is used in the material.
  42899. * @param texture - Base texture to use.
  42900. * @returns - Boolean specifying if a texture is used in the material.
  42901. */
  42902. PBRMaterial.prototype.hasTexture = function (texture) {
  42903. if (_super.prototype.hasTexture.call(this, texture)) {
  42904. return true;
  42905. }
  42906. if (this._albedoTexture === texture) {
  42907. return true;
  42908. }
  42909. if (this._ambientTexture === texture) {
  42910. return true;
  42911. }
  42912. if (this._opacityTexture === texture) {
  42913. return true;
  42914. }
  42915. if (this._reflectionTexture === texture) {
  42916. return true;
  42917. }
  42918. if (this._reflectivityTexture === texture) {
  42919. return true;
  42920. }
  42921. if (this._metallicTexture === texture) {
  42922. return true;
  42923. }
  42924. if (this._microSurfaceTexture === texture) {
  42925. return true;
  42926. }
  42927. if (this._bumpTexture === texture) {
  42928. return true;
  42929. }
  42930. if (this._lightmapTexture === texture) {
  42931. return true;
  42932. }
  42933. if (this._refractionTexture === texture) {
  42934. return true;
  42935. }
  42936. return false;
  42937. };
  42938. /**
  42939. * Makes a duplicate of the current material.
  42940. * @param name - name to use for the new material.
  42941. */
  42942. PBRMaterial.prototype.clone = function (name) {
  42943. var _this = this;
  42944. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42945. clone.id = name;
  42946. clone.name = name;
  42947. return clone;
  42948. };
  42949. /**
  42950. * Serializes this PBR Material.
  42951. * @returns - An object with the serialized material.
  42952. */
  42953. PBRMaterial.prototype.serialize = function () {
  42954. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42955. serializationObject.customType = "BABYLON.PBRMaterial";
  42956. return serializationObject;
  42957. };
  42958. // Statics
  42959. /**
  42960. * Parses a PBR Material from a serialized object.
  42961. * @param source - Serialized object.
  42962. * @param scene - BJS scene instance.
  42963. * @param rootUrl - url for the scene object
  42964. * @returns - PBRMaterial
  42965. */
  42966. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42967. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42968. };
  42969. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42970. /**
  42971. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42972. */
  42973. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42974. /**
  42975. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42976. */
  42977. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42978. /**
  42979. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42980. * They are also discarded below the alpha cutoff threshold to improve performances.
  42981. */
  42982. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42983. __decorate([
  42984. BABYLON.serialize(),
  42985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42986. ], PBRMaterial.prototype, "directIntensity", void 0);
  42987. __decorate([
  42988. BABYLON.serialize(),
  42989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42990. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42991. __decorate([
  42992. BABYLON.serialize(),
  42993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42994. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42995. __decorate([
  42996. BABYLON.serialize(),
  42997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42998. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42999. __decorate([
  43000. BABYLON.serialize(),
  43001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43002. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  43003. __decorate([
  43004. BABYLON.serializeAsTexture(),
  43005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43006. ], PBRMaterial.prototype, "albedoTexture", void 0);
  43007. __decorate([
  43008. BABYLON.serializeAsTexture(),
  43009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43010. ], PBRMaterial.prototype, "ambientTexture", void 0);
  43011. __decorate([
  43012. BABYLON.serialize(),
  43013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43014. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43015. __decorate([
  43016. BABYLON.serializeAsTexture(),
  43017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43018. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43019. __decorate([
  43020. BABYLON.serializeAsTexture(),
  43021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43022. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43023. __decorate([
  43024. BABYLON.serializeAsTexture(),
  43025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43026. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43027. __decorate([
  43028. BABYLON.serializeAsTexture(),
  43029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43030. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43031. __decorate([
  43032. BABYLON.serializeAsTexture(),
  43033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43034. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43035. __decorate([
  43036. BABYLON.serialize(),
  43037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43038. ], PBRMaterial.prototype, "metallic", void 0);
  43039. __decorate([
  43040. BABYLON.serialize(),
  43041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43042. ], PBRMaterial.prototype, "roughness", void 0);
  43043. __decorate([
  43044. BABYLON.serializeAsTexture(),
  43045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43046. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43047. __decorate([
  43048. BABYLON.serializeAsTexture(),
  43049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43050. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43051. __decorate([
  43052. BABYLON.serializeAsTexture(),
  43053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43054. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43055. __decorate([
  43056. BABYLON.serializeAsTexture(),
  43057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43058. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43059. __decorate([
  43060. BABYLON.serializeAsColor3("ambient"),
  43061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43062. ], PBRMaterial.prototype, "ambientColor", void 0);
  43063. __decorate([
  43064. BABYLON.serializeAsColor3("albedo"),
  43065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43066. ], PBRMaterial.prototype, "albedoColor", void 0);
  43067. __decorate([
  43068. BABYLON.serializeAsColor3("reflectivity"),
  43069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43070. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43071. __decorate([
  43072. BABYLON.serializeAsColor3("reflection"),
  43073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43074. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43075. __decorate([
  43076. BABYLON.serializeAsColor3("emissive"),
  43077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43078. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43079. __decorate([
  43080. BABYLON.serialize(),
  43081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43082. ], PBRMaterial.prototype, "microSurface", void 0);
  43083. __decorate([
  43084. BABYLON.serialize(),
  43085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43086. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43087. __decorate([
  43088. BABYLON.serialize(),
  43089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43090. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43091. __decorate([
  43092. BABYLON.serialize(),
  43093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43094. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43095. __decorate([
  43096. BABYLON.serialize(),
  43097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43098. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43099. __decorate([
  43100. BABYLON.serialize(),
  43101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43102. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43103. __decorate([
  43104. BABYLON.serialize(),
  43105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43106. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43107. __decorate([
  43108. BABYLON.serialize(),
  43109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43110. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43111. __decorate([
  43112. BABYLON.serialize(),
  43113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43114. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43115. __decorate([
  43116. BABYLON.serialize(),
  43117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43118. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43119. __decorate([
  43120. BABYLON.serialize(),
  43121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43122. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43123. __decorate([
  43124. BABYLON.serialize(),
  43125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43126. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43127. __decorate([
  43128. BABYLON.serialize(),
  43129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43130. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43131. __decorate([
  43132. BABYLON.serialize(),
  43133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43134. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43135. __decorate([
  43136. BABYLON.serialize(),
  43137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43138. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43139. __decorate([
  43140. BABYLON.serialize(),
  43141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43142. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43143. __decorate([
  43144. BABYLON.serialize(),
  43145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43146. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43147. __decorate([
  43148. BABYLON.serialize(),
  43149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43150. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43151. __decorate([
  43152. BABYLON.serialize(),
  43153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43154. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43155. __decorate([
  43156. BABYLON.serialize(),
  43157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43158. ], PBRMaterial.prototype, "useParallax", void 0);
  43159. __decorate([
  43160. BABYLON.serialize(),
  43161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43162. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43163. __decorate([
  43164. BABYLON.serialize(),
  43165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43166. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43167. __decorate([
  43168. BABYLON.serialize(),
  43169. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43170. ], PBRMaterial.prototype, "disableLighting", void 0);
  43171. __decorate([
  43172. BABYLON.serialize(),
  43173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43174. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43175. __decorate([
  43176. BABYLON.serialize(),
  43177. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43178. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43179. __decorate([
  43180. BABYLON.serialize(),
  43181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43182. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43183. __decorate([
  43184. BABYLON.serialize(),
  43185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43186. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43187. __decorate([
  43188. BABYLON.serialize(),
  43189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43190. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43191. __decorate([
  43192. BABYLON.serialize(),
  43193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43194. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43195. __decorate([
  43196. BABYLON.serialize(),
  43197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43198. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43199. __decorate([
  43200. BABYLON.serializeAsTexture(),
  43201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43202. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43203. __decorate([
  43204. BABYLON.serialize(),
  43205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43206. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43207. __decorate([
  43208. BABYLON.serialize(),
  43209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43210. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43211. __decorate([
  43212. BABYLON.serialize(),
  43213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43214. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43215. __decorate([
  43216. BABYLON.serialize(),
  43217. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43218. ], PBRMaterial.prototype, "unlit", void 0);
  43219. return PBRMaterial;
  43220. }(BABYLON.PBRBaseMaterial));
  43221. BABYLON.PBRMaterial = PBRMaterial;
  43222. })(BABYLON || (BABYLON = {}));
  43223. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43224. "use strict";
  43225. var BABYLON;
  43226. (function (BABYLON) {
  43227. /**
  43228. * The PBR material of BJS following the metal roughness convention.
  43229. *
  43230. * This fits to the PBR convention in the GLTF definition:
  43231. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43232. */
  43233. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43234. __extends(PBRMetallicRoughnessMaterial, _super);
  43235. /**
  43236. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43237. *
  43238. * @param name The material name
  43239. * @param scene The scene the material will be use in.
  43240. */
  43241. function PBRMetallicRoughnessMaterial(name, scene) {
  43242. var _this = _super.call(this, name, scene) || this;
  43243. _this._useRoughnessFromMetallicTextureAlpha = false;
  43244. _this._useRoughnessFromMetallicTextureGreen = true;
  43245. _this._useMetallnessFromMetallicTextureBlue = true;
  43246. _this.metallic = 1.0;
  43247. _this.roughness = 1.0;
  43248. return _this;
  43249. }
  43250. /**
  43251. * Return the currrent class name of the material.
  43252. */
  43253. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43254. return "PBRMetallicRoughnessMaterial";
  43255. };
  43256. /**
  43257. * Return the active textures of the material.
  43258. */
  43259. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43260. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43261. if (this.baseTexture) {
  43262. activeTextures.push(this.baseTexture);
  43263. }
  43264. if (this.metallicRoughnessTexture) {
  43265. activeTextures.push(this.metallicRoughnessTexture);
  43266. }
  43267. return activeTextures;
  43268. };
  43269. /**
  43270. * Checks to see if a texture is used in the material.
  43271. * @param texture - Base texture to use.
  43272. * @returns - Boolean specifying if a texture is used in the material.
  43273. */
  43274. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43275. if (_super.prototype.hasTexture.call(this, texture)) {
  43276. return true;
  43277. }
  43278. if (this.baseTexture === texture) {
  43279. return true;
  43280. }
  43281. if (this.metallicRoughnessTexture === texture) {
  43282. return true;
  43283. }
  43284. return false;
  43285. };
  43286. /**
  43287. * Makes a duplicate of the current material.
  43288. * @param name - name to use for the new material.
  43289. */
  43290. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43291. var _this = this;
  43292. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43293. clone.id = name;
  43294. clone.name = name;
  43295. return clone;
  43296. };
  43297. /**
  43298. * Serialize the material to a parsable JSON object.
  43299. */
  43300. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43301. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43302. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43303. return serializationObject;
  43304. };
  43305. /**
  43306. * Parses a JSON object correponding to the serialize function.
  43307. */
  43308. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43309. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43310. };
  43311. __decorate([
  43312. BABYLON.serializeAsColor3(),
  43313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43314. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43315. __decorate([
  43316. BABYLON.serializeAsTexture(),
  43317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43318. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43319. __decorate([
  43320. BABYLON.serialize(),
  43321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43322. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43323. __decorate([
  43324. BABYLON.serialize(),
  43325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43326. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43327. __decorate([
  43328. BABYLON.serializeAsTexture(),
  43329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43330. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43331. return PBRMetallicRoughnessMaterial;
  43332. }(BABYLON.PBRBaseSimpleMaterial));
  43333. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43334. })(BABYLON || (BABYLON = {}));
  43335. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43336. "use strict";
  43337. var BABYLON;
  43338. (function (BABYLON) {
  43339. /**
  43340. * The PBR material of BJS following the specular glossiness convention.
  43341. *
  43342. * This fits to the PBR convention in the GLTF definition:
  43343. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43344. */
  43345. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43346. __extends(PBRSpecularGlossinessMaterial, _super);
  43347. /**
  43348. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43349. *
  43350. * @param name The material name
  43351. * @param scene The scene the material will be use in.
  43352. */
  43353. function PBRSpecularGlossinessMaterial(name, scene) {
  43354. var _this = _super.call(this, name, scene) || this;
  43355. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43356. return _this;
  43357. }
  43358. /**
  43359. * Return the currrent class name of the material.
  43360. */
  43361. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43362. return "PBRSpecularGlossinessMaterial";
  43363. };
  43364. /**
  43365. * Return the active textures of the material.
  43366. */
  43367. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43368. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43369. if (this.diffuseTexture) {
  43370. activeTextures.push(this.diffuseTexture);
  43371. }
  43372. if (this.specularGlossinessTexture) {
  43373. activeTextures.push(this.specularGlossinessTexture);
  43374. }
  43375. return activeTextures;
  43376. };
  43377. /**
  43378. * Checks to see if a texture is used in the material.
  43379. * @param texture - Base texture to use.
  43380. * @returns - Boolean specifying if a texture is used in the material.
  43381. */
  43382. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43383. if (_super.prototype.hasTexture.call(this, texture)) {
  43384. return true;
  43385. }
  43386. if (this.diffuseTexture === texture) {
  43387. return true;
  43388. }
  43389. if (this.specularGlossinessTexture === texture) {
  43390. return true;
  43391. }
  43392. return false;
  43393. };
  43394. /**
  43395. * Makes a duplicate of the current material.
  43396. * @param name - name to use for the new material.
  43397. */
  43398. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43399. var _this = this;
  43400. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43401. clone.id = name;
  43402. clone.name = name;
  43403. return clone;
  43404. };
  43405. /**
  43406. * Serialize the material to a parsable JSON object.
  43407. */
  43408. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43409. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43410. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43411. return serializationObject;
  43412. };
  43413. /**
  43414. * Parses a JSON object correponding to the serialize function.
  43415. */
  43416. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43417. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43418. };
  43419. __decorate([
  43420. BABYLON.serializeAsColor3("diffuse"),
  43421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43422. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43423. __decorate([
  43424. BABYLON.serializeAsTexture(),
  43425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43426. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43427. __decorate([
  43428. BABYLON.serializeAsColor3("specular"),
  43429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43430. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43431. __decorate([
  43432. BABYLON.serialize(),
  43433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43434. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43435. __decorate([
  43436. BABYLON.serializeAsTexture(),
  43437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43438. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43439. return PBRSpecularGlossinessMaterial;
  43440. }(BABYLON.PBRBaseSimpleMaterial));
  43441. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43442. })(BABYLON || (BABYLON = {}));
  43443. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43444. "use strict";
  43445. var BABYLON;
  43446. (function (BABYLON) {
  43447. BABYLON.CameraInputTypes = {};
  43448. var CameraInputsManager = /** @class */ (function () {
  43449. function CameraInputsManager(camera) {
  43450. this.attached = {};
  43451. this.camera = camera;
  43452. this.checkInputs = function () { };
  43453. }
  43454. /**
  43455. * Add an input method to a camera.
  43456. * builtin inputs example: camera.inputs.addGamepad();
  43457. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43458. * @param input camera input method
  43459. */
  43460. CameraInputsManager.prototype.add = function (input) {
  43461. var type = input.getSimpleName();
  43462. if (this.attached[type]) {
  43463. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43464. return;
  43465. }
  43466. this.attached[type] = input;
  43467. input.camera = this.camera;
  43468. //for checkInputs, we are dynamically creating a function
  43469. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43470. if (input.checkInputs) {
  43471. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43472. }
  43473. if (this.attachedElement) {
  43474. input.attachControl(this.attachedElement);
  43475. }
  43476. };
  43477. /**
  43478. * Remove a specific input method from a camera
  43479. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43480. * @param inputToRemove camera input method
  43481. */
  43482. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43483. for (var cam in this.attached) {
  43484. var input = this.attached[cam];
  43485. if (input === inputToRemove) {
  43486. input.detachControl(this.attachedElement);
  43487. input.camera = null;
  43488. delete this.attached[cam];
  43489. this.rebuildInputCheck();
  43490. }
  43491. }
  43492. };
  43493. CameraInputsManager.prototype.removeByType = function (inputType) {
  43494. for (var cam in this.attached) {
  43495. var input = this.attached[cam];
  43496. if (input.getClassName() === inputType) {
  43497. input.detachControl(this.attachedElement);
  43498. input.camera = null;
  43499. delete this.attached[cam];
  43500. this.rebuildInputCheck();
  43501. }
  43502. }
  43503. };
  43504. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43505. var current = this.checkInputs;
  43506. return function () {
  43507. current();
  43508. fn();
  43509. };
  43510. };
  43511. CameraInputsManager.prototype.attachInput = function (input) {
  43512. if (this.attachedElement) {
  43513. input.attachControl(this.attachedElement, this.noPreventDefault);
  43514. }
  43515. };
  43516. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43517. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43518. if (this.attachedElement) {
  43519. return;
  43520. }
  43521. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43522. this.attachedElement = element;
  43523. this.noPreventDefault = noPreventDefault;
  43524. for (var cam in this.attached) {
  43525. this.attached[cam].attachControl(element, noPreventDefault);
  43526. }
  43527. };
  43528. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43529. if (disconnect === void 0) { disconnect = false; }
  43530. if (this.attachedElement !== element) {
  43531. return;
  43532. }
  43533. for (var cam in this.attached) {
  43534. this.attached[cam].detachControl(element);
  43535. if (disconnect) {
  43536. this.attached[cam].camera = null;
  43537. }
  43538. }
  43539. this.attachedElement = null;
  43540. };
  43541. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43542. this.checkInputs = function () { };
  43543. for (var cam in this.attached) {
  43544. var input = this.attached[cam];
  43545. if (input.checkInputs) {
  43546. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43547. }
  43548. }
  43549. };
  43550. /**
  43551. * Remove all attached input methods from a camera
  43552. */
  43553. CameraInputsManager.prototype.clear = function () {
  43554. if (this.attachedElement) {
  43555. this.detachElement(this.attachedElement, true);
  43556. }
  43557. this.attached = {};
  43558. this.attachedElement = null;
  43559. this.checkInputs = function () { };
  43560. };
  43561. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43562. var inputs = {};
  43563. for (var cam in this.attached) {
  43564. var input = this.attached[cam];
  43565. var res = BABYLON.SerializationHelper.Serialize(input);
  43566. inputs[input.getClassName()] = res;
  43567. }
  43568. serializedCamera.inputsmgr = inputs;
  43569. };
  43570. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43571. var parsedInputs = parsedCamera.inputsmgr;
  43572. if (parsedInputs) {
  43573. this.clear();
  43574. for (var n in parsedInputs) {
  43575. var construct = BABYLON.CameraInputTypes[n];
  43576. if (construct) {
  43577. var parsedinput = parsedInputs[n];
  43578. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43579. this.add(input);
  43580. }
  43581. }
  43582. }
  43583. else {
  43584. //2016-03-08 this part is for managing backward compatibility
  43585. for (var n in this.attached) {
  43586. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43587. if (construct) {
  43588. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43589. this.remove(this.attached[n]);
  43590. this.add(input);
  43591. }
  43592. }
  43593. }
  43594. };
  43595. return CameraInputsManager;
  43596. }());
  43597. BABYLON.CameraInputsManager = CameraInputsManager;
  43598. })(BABYLON || (BABYLON = {}));
  43599. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43600. "use strict";
  43601. var BABYLON;
  43602. (function (BABYLON) {
  43603. var TargetCamera = /** @class */ (function (_super) {
  43604. __extends(TargetCamera, _super);
  43605. function TargetCamera(name, position, scene) {
  43606. var _this = _super.call(this, name, position, scene) || this;
  43607. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43608. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43609. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43610. _this.speed = 2.0;
  43611. _this.noRotationConstraint = false;
  43612. _this.lockedTarget = null;
  43613. _this._currentTarget = BABYLON.Vector3.Zero();
  43614. _this._viewMatrix = BABYLON.Matrix.Zero();
  43615. _this._camMatrix = BABYLON.Matrix.Zero();
  43616. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43617. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43618. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43619. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43620. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43621. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43622. _this._tempMatrix = BABYLON.Matrix.Zero();
  43623. return _this;
  43624. }
  43625. TargetCamera.prototype.getFrontPosition = function (distance) {
  43626. this.getWorldMatrix();
  43627. var direction = this.getTarget().subtract(this.position);
  43628. direction.normalize();
  43629. direction.scaleInPlace(distance);
  43630. return this.globalPosition.add(direction);
  43631. };
  43632. TargetCamera.prototype._getLockedTargetPosition = function () {
  43633. if (!this.lockedTarget) {
  43634. return null;
  43635. }
  43636. if (this.lockedTarget.absolutePosition) {
  43637. this.lockedTarget.computeWorldMatrix();
  43638. }
  43639. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43640. };
  43641. TargetCamera.prototype.storeState = function () {
  43642. this._storedPosition = this.position.clone();
  43643. this._storedRotation = this.rotation.clone();
  43644. if (this.rotationQuaternion) {
  43645. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43646. }
  43647. return _super.prototype.storeState.call(this);
  43648. };
  43649. /**
  43650. * Restored camera state. You must call storeState() first
  43651. */
  43652. TargetCamera.prototype._restoreStateValues = function () {
  43653. if (!_super.prototype._restoreStateValues.call(this)) {
  43654. return false;
  43655. }
  43656. this.position = this._storedPosition.clone();
  43657. this.rotation = this._storedRotation.clone();
  43658. if (this.rotationQuaternion) {
  43659. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43660. }
  43661. this.cameraDirection.copyFromFloats(0, 0, 0);
  43662. this.cameraRotation.copyFromFloats(0, 0);
  43663. return true;
  43664. };
  43665. // Cache
  43666. TargetCamera.prototype._initCache = function () {
  43667. _super.prototype._initCache.call(this);
  43668. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43669. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43670. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43671. };
  43672. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43673. if (!ignoreParentClass) {
  43674. _super.prototype._updateCache.call(this);
  43675. }
  43676. var lockedTargetPosition = this._getLockedTargetPosition();
  43677. if (!lockedTargetPosition) {
  43678. this._cache.lockedTarget = null;
  43679. }
  43680. else {
  43681. if (!this._cache.lockedTarget) {
  43682. this._cache.lockedTarget = lockedTargetPosition.clone();
  43683. }
  43684. else {
  43685. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43686. }
  43687. }
  43688. this._cache.rotation.copyFrom(this.rotation);
  43689. if (this.rotationQuaternion)
  43690. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43691. };
  43692. // Synchronized
  43693. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43694. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43695. return false;
  43696. }
  43697. var lockedTargetPosition = this._getLockedTargetPosition();
  43698. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43699. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43700. };
  43701. // Methods
  43702. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43703. var engine = this.getEngine();
  43704. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43705. };
  43706. // Target
  43707. TargetCamera.prototype.setTarget = function (target) {
  43708. this.upVector.normalize();
  43709. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43710. this._camMatrix.invert();
  43711. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43712. var vDir = target.subtract(this.position);
  43713. if (vDir.x >= 0.0) {
  43714. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43715. }
  43716. else {
  43717. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43718. }
  43719. this.rotation.z = 0;
  43720. if (isNaN(this.rotation.x)) {
  43721. this.rotation.x = 0;
  43722. }
  43723. if (isNaN(this.rotation.y)) {
  43724. this.rotation.y = 0;
  43725. }
  43726. if (isNaN(this.rotation.z)) {
  43727. this.rotation.z = 0;
  43728. }
  43729. if (this.rotationQuaternion) {
  43730. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43731. }
  43732. };
  43733. /**
  43734. * Return the current target position of the camera. This value is expressed in local space.
  43735. */
  43736. TargetCamera.prototype.getTarget = function () {
  43737. return this._currentTarget;
  43738. };
  43739. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43740. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43741. };
  43742. TargetCamera.prototype._updatePosition = function () {
  43743. if (this.parent) {
  43744. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43745. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43746. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43747. return;
  43748. }
  43749. this.position.addInPlace(this.cameraDirection);
  43750. };
  43751. TargetCamera.prototype._checkInputs = function () {
  43752. var needToMove = this._decideIfNeedsToMove();
  43753. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43754. // Move
  43755. if (needToMove) {
  43756. this._updatePosition();
  43757. }
  43758. // Rotate
  43759. if (needToRotate) {
  43760. this.rotation.x += this.cameraRotation.x;
  43761. this.rotation.y += this.cameraRotation.y;
  43762. //rotate, if quaternion is set and rotation was used
  43763. if (this.rotationQuaternion) {
  43764. var len = this.rotation.lengthSquared();
  43765. if (len) {
  43766. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43767. }
  43768. }
  43769. if (!this.noRotationConstraint) {
  43770. var limit = (Math.PI / 2) * 0.95;
  43771. if (this.rotation.x > limit)
  43772. this.rotation.x = limit;
  43773. if (this.rotation.x < -limit)
  43774. this.rotation.x = -limit;
  43775. }
  43776. }
  43777. // Inertia
  43778. if (needToMove) {
  43779. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43780. this.cameraDirection.x = 0;
  43781. }
  43782. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43783. this.cameraDirection.y = 0;
  43784. }
  43785. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43786. this.cameraDirection.z = 0;
  43787. }
  43788. this.cameraDirection.scaleInPlace(this.inertia);
  43789. }
  43790. if (needToRotate) {
  43791. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43792. this.cameraRotation.x = 0;
  43793. }
  43794. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43795. this.cameraRotation.y = 0;
  43796. }
  43797. this.cameraRotation.scaleInPlace(this.inertia);
  43798. }
  43799. _super.prototype._checkInputs.call(this);
  43800. };
  43801. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43802. if (this.rotationQuaternion) {
  43803. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43804. }
  43805. else {
  43806. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43807. }
  43808. //update the up vector!
  43809. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43810. };
  43811. TargetCamera.prototype._getViewMatrix = function () {
  43812. if (this.lockedTarget) {
  43813. this.setTarget(this._getLockedTargetPosition());
  43814. }
  43815. // Compute
  43816. this._updateCameraRotationMatrix();
  43817. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43818. // Computing target and final matrix
  43819. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43820. if (this.getScene().useRightHandedSystem) {
  43821. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43822. }
  43823. else {
  43824. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43825. }
  43826. return this._viewMatrix;
  43827. };
  43828. /**
  43829. * @override
  43830. * Override Camera.createRigCamera
  43831. */
  43832. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43833. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43834. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43835. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43836. if (!this.rotationQuaternion) {
  43837. this.rotationQuaternion = new BABYLON.Quaternion();
  43838. }
  43839. rigCamera._cameraRigParams = {};
  43840. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43841. }
  43842. return rigCamera;
  43843. }
  43844. return null;
  43845. };
  43846. /**
  43847. * @override
  43848. * Override Camera._updateRigCameras
  43849. */
  43850. TargetCamera.prototype._updateRigCameras = function () {
  43851. var camLeft = this._rigCameras[0];
  43852. var camRight = this._rigCameras[1];
  43853. switch (this.cameraRigMode) {
  43854. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43855. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43856. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43857. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43858. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43859. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43860. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43861. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43862. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43863. camLeft.setTarget(this.getTarget());
  43864. camRight.setTarget(this.getTarget());
  43865. break;
  43866. case BABYLON.Camera.RIG_MODE_VR:
  43867. if (camLeft.rotationQuaternion) {
  43868. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43869. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43870. }
  43871. else {
  43872. camLeft.rotation.copyFrom(this.rotation);
  43873. camRight.rotation.copyFrom(this.rotation);
  43874. }
  43875. camLeft.position.copyFrom(this.position);
  43876. camRight.position.copyFrom(this.position);
  43877. break;
  43878. }
  43879. _super.prototype._updateRigCameras.call(this);
  43880. };
  43881. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43882. if (!this._rigCamTransformMatrix) {
  43883. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43884. }
  43885. var target = this.getTarget();
  43886. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43887. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43888. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43889. };
  43890. TargetCamera.prototype.getClassName = function () {
  43891. return "TargetCamera";
  43892. };
  43893. __decorate([
  43894. BABYLON.serializeAsVector3()
  43895. ], TargetCamera.prototype, "rotation", void 0);
  43896. __decorate([
  43897. BABYLON.serialize()
  43898. ], TargetCamera.prototype, "speed", void 0);
  43899. __decorate([
  43900. BABYLON.serializeAsMeshReference("lockedTargetId")
  43901. ], TargetCamera.prototype, "lockedTarget", void 0);
  43902. return TargetCamera;
  43903. }(BABYLON.Camera));
  43904. BABYLON.TargetCamera = TargetCamera;
  43905. })(BABYLON || (BABYLON = {}));
  43906. //# sourceMappingURL=babylon.targetCamera.js.map
  43907. "use strict";
  43908. var BABYLON;
  43909. (function (BABYLON) {
  43910. var FreeCameraMouseInput = /** @class */ (function () {
  43911. function FreeCameraMouseInput(touchEnabled) {
  43912. if (touchEnabled === void 0) { touchEnabled = true; }
  43913. this.touchEnabled = touchEnabled;
  43914. this.buttons = [0, 1, 2];
  43915. this.angularSensibility = 2000.0;
  43916. this.previousPosition = null;
  43917. }
  43918. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43919. var _this = this;
  43920. var engine = this.camera.getEngine();
  43921. if (!this._pointerInput) {
  43922. this._pointerInput = function (p, s) {
  43923. var evt = p.event;
  43924. if (engine.isInVRExclusivePointerMode) {
  43925. return;
  43926. }
  43927. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43928. return;
  43929. }
  43930. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43931. return;
  43932. }
  43933. var srcElement = (evt.srcElement || evt.target);
  43934. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43935. try {
  43936. srcElement.setPointerCapture(evt.pointerId);
  43937. }
  43938. catch (e) {
  43939. //Nothing to do with the error. Execution will continue.
  43940. }
  43941. _this.previousPosition = {
  43942. x: evt.clientX,
  43943. y: evt.clientY
  43944. };
  43945. if (!noPreventDefault) {
  43946. evt.preventDefault();
  43947. element.focus();
  43948. }
  43949. }
  43950. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43951. try {
  43952. srcElement.releasePointerCapture(evt.pointerId);
  43953. }
  43954. catch (e) {
  43955. //Nothing to do with the error.
  43956. }
  43957. _this.previousPosition = null;
  43958. if (!noPreventDefault) {
  43959. evt.preventDefault();
  43960. }
  43961. }
  43962. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43963. if (!_this.previousPosition || engine.isPointerLock) {
  43964. return;
  43965. }
  43966. var offsetX = evt.clientX - _this.previousPosition.x;
  43967. var offsetY = evt.clientY - _this.previousPosition.y;
  43968. if (_this.camera.getScene().useRightHandedSystem) {
  43969. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43970. }
  43971. else {
  43972. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43973. }
  43974. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43975. _this.previousPosition = {
  43976. x: evt.clientX,
  43977. y: evt.clientY
  43978. };
  43979. if (!noPreventDefault) {
  43980. evt.preventDefault();
  43981. }
  43982. }
  43983. };
  43984. }
  43985. this._onMouseMove = function (evt) {
  43986. if (!engine.isPointerLock) {
  43987. return;
  43988. }
  43989. if (engine.isInVRExclusivePointerMode) {
  43990. return;
  43991. }
  43992. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43993. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43994. if (_this.camera.getScene().useRightHandedSystem) {
  43995. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43996. }
  43997. else {
  43998. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43999. }
  44000. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44001. _this.previousPosition = null;
  44002. if (!noPreventDefault) {
  44003. evt.preventDefault();
  44004. }
  44005. };
  44006. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44007. element.addEventListener("mousemove", this._onMouseMove, false);
  44008. };
  44009. FreeCameraMouseInput.prototype.detachControl = function (element) {
  44010. if (this._observer && element) {
  44011. this.camera.getScene().onPointerObservable.remove(this._observer);
  44012. if (this._onMouseMove) {
  44013. element.removeEventListener("mousemove", this._onMouseMove);
  44014. }
  44015. this._observer = null;
  44016. this._onMouseMove = null;
  44017. this.previousPosition = null;
  44018. }
  44019. };
  44020. FreeCameraMouseInput.prototype.getClassName = function () {
  44021. return "FreeCameraMouseInput";
  44022. };
  44023. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44024. return "mouse";
  44025. };
  44026. __decorate([
  44027. BABYLON.serialize()
  44028. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44029. __decorate([
  44030. BABYLON.serialize()
  44031. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44032. return FreeCameraMouseInput;
  44033. }());
  44034. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44035. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44036. })(BABYLON || (BABYLON = {}));
  44037. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44038. "use strict";
  44039. var BABYLON;
  44040. (function (BABYLON) {
  44041. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44042. function FreeCameraKeyboardMoveInput() {
  44043. this._keys = new Array();
  44044. this.keysUp = [38];
  44045. this.keysDown = [40];
  44046. this.keysLeft = [37];
  44047. this.keysRight = [39];
  44048. }
  44049. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44050. var _this = this;
  44051. if (this._onCanvasBlurObserver) {
  44052. return;
  44053. }
  44054. this._scene = this.camera.getScene();
  44055. this._engine = this._scene.getEngine();
  44056. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44057. _this._keys = [];
  44058. });
  44059. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44060. var evt = info.event;
  44061. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44062. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44063. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44064. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44065. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44066. var index = _this._keys.indexOf(evt.keyCode);
  44067. if (index === -1) {
  44068. _this._keys.push(evt.keyCode);
  44069. }
  44070. if (!noPreventDefault) {
  44071. evt.preventDefault();
  44072. }
  44073. }
  44074. }
  44075. else {
  44076. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44077. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44078. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44079. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44080. var index = _this._keys.indexOf(evt.keyCode);
  44081. if (index >= 0) {
  44082. _this._keys.splice(index, 1);
  44083. }
  44084. if (!noPreventDefault) {
  44085. evt.preventDefault();
  44086. }
  44087. }
  44088. }
  44089. });
  44090. };
  44091. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44092. if (this._scene) {
  44093. if (this._onKeyboardObserver) {
  44094. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44095. }
  44096. if (this._onCanvasBlurObserver) {
  44097. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44098. }
  44099. this._onKeyboardObserver = null;
  44100. this._onCanvasBlurObserver = null;
  44101. }
  44102. this._keys = [];
  44103. };
  44104. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44105. if (this._onKeyboardObserver) {
  44106. var camera = this.camera;
  44107. // Keyboard
  44108. for (var index = 0; index < this._keys.length; index++) {
  44109. var keyCode = this._keys[index];
  44110. var speed = camera._computeLocalCameraSpeed();
  44111. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44112. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44113. }
  44114. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44115. camera._localDirection.copyFromFloats(0, 0, speed);
  44116. }
  44117. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44118. camera._localDirection.copyFromFloats(speed, 0, 0);
  44119. }
  44120. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44121. camera._localDirection.copyFromFloats(0, 0, -speed);
  44122. }
  44123. if (camera.getScene().useRightHandedSystem) {
  44124. camera._localDirection.z *= -1;
  44125. }
  44126. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44127. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44128. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44129. }
  44130. }
  44131. };
  44132. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44133. return "FreeCameraKeyboardMoveInput";
  44134. };
  44135. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44136. this._keys = [];
  44137. };
  44138. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44139. return "keyboard";
  44140. };
  44141. __decorate([
  44142. BABYLON.serialize()
  44143. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44144. __decorate([
  44145. BABYLON.serialize()
  44146. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44147. __decorate([
  44148. BABYLON.serialize()
  44149. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44150. __decorate([
  44151. BABYLON.serialize()
  44152. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44153. return FreeCameraKeyboardMoveInput;
  44154. }());
  44155. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44156. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44157. })(BABYLON || (BABYLON = {}));
  44158. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44159. "use strict";
  44160. var BABYLON;
  44161. (function (BABYLON) {
  44162. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44163. __extends(FreeCameraInputsManager, _super);
  44164. function FreeCameraInputsManager(camera) {
  44165. return _super.call(this, camera) || this;
  44166. }
  44167. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44168. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44169. return this;
  44170. };
  44171. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44172. if (touchEnabled === void 0) { touchEnabled = true; }
  44173. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44174. return this;
  44175. };
  44176. FreeCameraInputsManager.prototype.addGamepad = function () {
  44177. this.add(new BABYLON.FreeCameraGamepadInput());
  44178. return this;
  44179. };
  44180. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44181. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44182. return this;
  44183. };
  44184. FreeCameraInputsManager.prototype.addTouch = function () {
  44185. this.add(new BABYLON.FreeCameraTouchInput());
  44186. return this;
  44187. };
  44188. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44189. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44190. return this;
  44191. };
  44192. return FreeCameraInputsManager;
  44193. }(BABYLON.CameraInputsManager));
  44194. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44195. })(BABYLON || (BABYLON = {}));
  44196. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44197. "use strict";
  44198. var BABYLON;
  44199. (function (BABYLON) {
  44200. var FreeCamera = /** @class */ (function (_super) {
  44201. __extends(FreeCamera, _super);
  44202. function FreeCamera(name, position, scene) {
  44203. var _this = _super.call(this, name, position, scene) || this;
  44204. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44205. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44206. _this.checkCollisions = false;
  44207. _this.applyGravity = false;
  44208. _this._needMoveForGravity = false;
  44209. _this._oldPosition = BABYLON.Vector3.Zero();
  44210. _this._diffPosition = BABYLON.Vector3.Zero();
  44211. _this._newPosition = BABYLON.Vector3.Zero();
  44212. // Collisions
  44213. _this._collisionMask = -1;
  44214. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44215. if (collidedMesh === void 0) { collidedMesh = null; }
  44216. //TODO move this to the collision coordinator!
  44217. if (_this.getScene().workerCollisions)
  44218. newPosition.multiplyInPlace(_this._collider._radius);
  44219. var updatePosition = function (newPos) {
  44220. _this._newPosition.copyFrom(newPos);
  44221. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44222. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44223. _this.position.addInPlace(_this._diffPosition);
  44224. if (_this.onCollide && collidedMesh) {
  44225. _this.onCollide(collidedMesh);
  44226. }
  44227. }
  44228. };
  44229. updatePosition(newPosition);
  44230. };
  44231. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44232. _this.inputs.addKeyboard().addMouse();
  44233. return _this;
  44234. }
  44235. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44236. //-- begin properties for backward compatibility for inputs
  44237. /**
  44238. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44239. * Higher values reduce sensitivity.
  44240. */
  44241. get: function () {
  44242. var mouse = this.inputs.attached["mouse"];
  44243. if (mouse)
  44244. return mouse.angularSensibility;
  44245. return 0;
  44246. },
  44247. /**
  44248. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44249. * Higher values reduce sensitivity.
  44250. */
  44251. set: function (value) {
  44252. var mouse = this.inputs.attached["mouse"];
  44253. if (mouse)
  44254. mouse.angularSensibility = value;
  44255. },
  44256. enumerable: true,
  44257. configurable: true
  44258. });
  44259. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44260. get: function () {
  44261. var keyboard = this.inputs.attached["keyboard"];
  44262. if (keyboard)
  44263. return keyboard.keysUp;
  44264. return [];
  44265. },
  44266. set: function (value) {
  44267. var keyboard = this.inputs.attached["keyboard"];
  44268. if (keyboard)
  44269. keyboard.keysUp = value;
  44270. },
  44271. enumerable: true,
  44272. configurable: true
  44273. });
  44274. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44275. get: function () {
  44276. var keyboard = this.inputs.attached["keyboard"];
  44277. if (keyboard)
  44278. return keyboard.keysDown;
  44279. return [];
  44280. },
  44281. set: function (value) {
  44282. var keyboard = this.inputs.attached["keyboard"];
  44283. if (keyboard)
  44284. keyboard.keysDown = value;
  44285. },
  44286. enumerable: true,
  44287. configurable: true
  44288. });
  44289. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44290. get: function () {
  44291. var keyboard = this.inputs.attached["keyboard"];
  44292. if (keyboard)
  44293. return keyboard.keysLeft;
  44294. return [];
  44295. },
  44296. set: function (value) {
  44297. var keyboard = this.inputs.attached["keyboard"];
  44298. if (keyboard)
  44299. keyboard.keysLeft = value;
  44300. },
  44301. enumerable: true,
  44302. configurable: true
  44303. });
  44304. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44305. get: function () {
  44306. var keyboard = this.inputs.attached["keyboard"];
  44307. if (keyboard)
  44308. return keyboard.keysRight;
  44309. return [];
  44310. },
  44311. set: function (value) {
  44312. var keyboard = this.inputs.attached["keyboard"];
  44313. if (keyboard)
  44314. keyboard.keysRight = value;
  44315. },
  44316. enumerable: true,
  44317. configurable: true
  44318. });
  44319. // Controls
  44320. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44321. this.inputs.attachElement(element, noPreventDefault);
  44322. };
  44323. FreeCamera.prototype.detachControl = function (element) {
  44324. this.inputs.detachElement(element);
  44325. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44326. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44327. };
  44328. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44329. get: function () {
  44330. return this._collisionMask;
  44331. },
  44332. set: function (mask) {
  44333. this._collisionMask = !isNaN(mask) ? mask : -1;
  44334. },
  44335. enumerable: true,
  44336. configurable: true
  44337. });
  44338. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44339. var globalPosition;
  44340. if (this.parent) {
  44341. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44342. }
  44343. else {
  44344. globalPosition = this.position;
  44345. }
  44346. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44347. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44348. if (!this._collider) {
  44349. this._collider = new BABYLON.Collider();
  44350. }
  44351. this._collider._radius = this.ellipsoid;
  44352. this._collider.collisionMask = this._collisionMask;
  44353. //no need for clone, as long as gravity is not on.
  44354. var actualDisplacement = displacement;
  44355. //add gravity to the direction to prevent the dual-collision checking
  44356. if (this.applyGravity) {
  44357. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44358. actualDisplacement = displacement.add(this.getScene().gravity);
  44359. }
  44360. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44361. };
  44362. FreeCamera.prototype._checkInputs = function () {
  44363. if (!this._localDirection) {
  44364. this._localDirection = BABYLON.Vector3.Zero();
  44365. this._transformedDirection = BABYLON.Vector3.Zero();
  44366. }
  44367. this.inputs.checkInputs();
  44368. _super.prototype._checkInputs.call(this);
  44369. };
  44370. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44371. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44372. };
  44373. FreeCamera.prototype._updatePosition = function () {
  44374. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44375. this._collideWithWorld(this.cameraDirection);
  44376. }
  44377. else {
  44378. _super.prototype._updatePosition.call(this);
  44379. }
  44380. };
  44381. FreeCamera.prototype.dispose = function () {
  44382. this.inputs.clear();
  44383. _super.prototype.dispose.call(this);
  44384. };
  44385. FreeCamera.prototype.getClassName = function () {
  44386. return "FreeCamera";
  44387. };
  44388. __decorate([
  44389. BABYLON.serializeAsVector3()
  44390. ], FreeCamera.prototype, "ellipsoid", void 0);
  44391. __decorate([
  44392. BABYLON.serializeAsVector3()
  44393. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44394. __decorate([
  44395. BABYLON.serialize()
  44396. ], FreeCamera.prototype, "checkCollisions", void 0);
  44397. __decorate([
  44398. BABYLON.serialize()
  44399. ], FreeCamera.prototype, "applyGravity", void 0);
  44400. return FreeCamera;
  44401. }(BABYLON.TargetCamera));
  44402. BABYLON.FreeCamera = FreeCamera;
  44403. })(BABYLON || (BABYLON = {}));
  44404. //# sourceMappingURL=babylon.freeCamera.js.map
  44405. "use strict";
  44406. var BABYLON;
  44407. (function (BABYLON) {
  44408. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44409. function ArcRotateCameraKeyboardMoveInput() {
  44410. this._keys = new Array();
  44411. this.keysUp = [38];
  44412. this.keysDown = [40];
  44413. this.keysLeft = [37];
  44414. this.keysRight = [39];
  44415. this.keysReset = [220];
  44416. this.panningSensibility = 50.0;
  44417. this.zoomingSensibility = 25.0;
  44418. this.useAltToZoom = true;
  44419. }
  44420. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44421. var _this = this;
  44422. if (this._onCanvasBlurObserver) {
  44423. return;
  44424. }
  44425. this._scene = this.camera.getScene();
  44426. this._engine = this._scene.getEngine();
  44427. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44428. _this._keys = [];
  44429. });
  44430. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44431. var evt = info.event;
  44432. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44433. _this._ctrlPressed = evt.ctrlKey;
  44434. _this._altPressed = evt.altKey;
  44435. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44436. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44437. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44438. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44439. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44440. var index = _this._keys.indexOf(evt.keyCode);
  44441. if (index === -1) {
  44442. _this._keys.push(evt.keyCode);
  44443. }
  44444. if (evt.preventDefault) {
  44445. if (!noPreventDefault) {
  44446. evt.preventDefault();
  44447. }
  44448. }
  44449. }
  44450. }
  44451. else {
  44452. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44453. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44454. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44455. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44456. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44457. var index = _this._keys.indexOf(evt.keyCode);
  44458. if (index >= 0) {
  44459. _this._keys.splice(index, 1);
  44460. }
  44461. if (evt.preventDefault) {
  44462. if (!noPreventDefault) {
  44463. evt.preventDefault();
  44464. }
  44465. }
  44466. }
  44467. }
  44468. });
  44469. };
  44470. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44471. if (this._scene) {
  44472. if (this._onKeyboardObserver) {
  44473. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44474. }
  44475. if (this._onCanvasBlurObserver) {
  44476. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44477. }
  44478. this._onKeyboardObserver = null;
  44479. this._onCanvasBlurObserver = null;
  44480. }
  44481. this._keys = [];
  44482. };
  44483. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44484. if (this._onKeyboardObserver) {
  44485. var camera = this.camera;
  44486. for (var index = 0; index < this._keys.length; index++) {
  44487. var keyCode = this._keys[index];
  44488. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44489. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44490. camera.inertialPanningX -= 1 / this.panningSensibility;
  44491. }
  44492. else {
  44493. camera.inertialAlphaOffset -= 0.01;
  44494. }
  44495. }
  44496. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44497. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44498. camera.inertialPanningY += 1 / this.panningSensibility;
  44499. }
  44500. else if (this._altPressed && this.useAltToZoom) {
  44501. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44502. }
  44503. else {
  44504. camera.inertialBetaOffset -= 0.01;
  44505. }
  44506. }
  44507. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44508. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44509. camera.inertialPanningX += 1 / this.panningSensibility;
  44510. }
  44511. else {
  44512. camera.inertialAlphaOffset += 0.01;
  44513. }
  44514. }
  44515. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44516. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44517. camera.inertialPanningY -= 1 / this.panningSensibility;
  44518. }
  44519. else if (this._altPressed && this.useAltToZoom) {
  44520. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44521. }
  44522. else {
  44523. camera.inertialBetaOffset += 0.01;
  44524. }
  44525. }
  44526. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44527. camera.restoreState();
  44528. }
  44529. }
  44530. }
  44531. };
  44532. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44533. return "ArcRotateCameraKeyboardMoveInput";
  44534. };
  44535. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44536. return "keyboard";
  44537. };
  44538. __decorate([
  44539. BABYLON.serialize()
  44540. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44541. __decorate([
  44542. BABYLON.serialize()
  44543. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44544. __decorate([
  44545. BABYLON.serialize()
  44546. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44547. __decorate([
  44548. BABYLON.serialize()
  44549. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44550. __decorate([
  44551. BABYLON.serialize()
  44552. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44553. __decorate([
  44554. BABYLON.serialize()
  44555. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44556. __decorate([
  44557. BABYLON.serialize()
  44558. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44559. __decorate([
  44560. BABYLON.serialize()
  44561. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44562. return ArcRotateCameraKeyboardMoveInput;
  44563. }());
  44564. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44565. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44566. })(BABYLON || (BABYLON = {}));
  44567. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44568. "use strict";
  44569. var BABYLON;
  44570. (function (BABYLON) {
  44571. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44572. function ArcRotateCameraMouseWheelInput() {
  44573. this.wheelPrecision = 3.0;
  44574. /**
  44575. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44576. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44577. */
  44578. this.wheelDeltaPercentage = 0;
  44579. }
  44580. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44581. var _this = this;
  44582. this._wheel = function (p, s) {
  44583. //sanity check - this should be a PointerWheel event.
  44584. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44585. return;
  44586. var event = p.event;
  44587. var delta = 0;
  44588. if (event.wheelDelta) {
  44589. if (_this.wheelDeltaPercentage) {
  44590. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  44591. if (event.wheelDelta > 0) {
  44592. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  44593. }
  44594. else {
  44595. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  44596. }
  44597. }
  44598. else {
  44599. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  44600. }
  44601. }
  44602. else if (event.detail) {
  44603. delta = -event.detail / _this.wheelPrecision;
  44604. }
  44605. if (delta)
  44606. _this.camera.inertialRadiusOffset += delta;
  44607. if (event.preventDefault) {
  44608. if (!noPreventDefault) {
  44609. event.preventDefault();
  44610. }
  44611. }
  44612. };
  44613. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44614. };
  44615. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44616. if (this._observer && element) {
  44617. this.camera.getScene().onPointerObservable.remove(this._observer);
  44618. this._observer = null;
  44619. this._wheel = null;
  44620. }
  44621. };
  44622. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44623. return "ArcRotateCameraMouseWheelInput";
  44624. };
  44625. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44626. return "mousewheel";
  44627. };
  44628. __decorate([
  44629. BABYLON.serialize()
  44630. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44631. __decorate([
  44632. BABYLON.serialize()
  44633. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44634. return ArcRotateCameraMouseWheelInput;
  44635. }());
  44636. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44637. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44638. })(BABYLON || (BABYLON = {}));
  44639. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44640. "use strict";
  44641. var BABYLON;
  44642. (function (BABYLON) {
  44643. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44644. function ArcRotateCameraPointersInput() {
  44645. this.buttons = [0, 1, 2];
  44646. this.angularSensibilityX = 1000.0;
  44647. this.angularSensibilityY = 1000.0;
  44648. this.pinchPrecision = 12.0;
  44649. /**
  44650. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44651. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44652. */
  44653. this.pinchDeltaPercentage = 0;
  44654. this.panningSensibility = 1000.0;
  44655. this.multiTouchPanning = true;
  44656. this.multiTouchPanAndZoom = true;
  44657. this._isPanClick = false;
  44658. this.pinchInwards = true;
  44659. }
  44660. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44661. var _this = this;
  44662. var engine = this.camera.getEngine();
  44663. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44664. var pointA = null;
  44665. var pointB = null;
  44666. var previousPinchSquaredDistance = 0;
  44667. var initialDistance = 0;
  44668. var twoFingerActivityCount = 0;
  44669. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44670. this._pointerInput = function (p, s) {
  44671. var evt = p.event;
  44672. var isTouch = p.event.pointerType === "touch";
  44673. if (engine.isInVRExclusivePointerMode) {
  44674. return;
  44675. }
  44676. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44677. return;
  44678. }
  44679. var srcElement = (evt.srcElement || evt.target);
  44680. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44681. try {
  44682. srcElement.setPointerCapture(evt.pointerId);
  44683. }
  44684. catch (e) {
  44685. //Nothing to do with the error. Execution will continue.
  44686. }
  44687. // Manage panning with pan button click
  44688. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44689. // manage pointers
  44690. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44691. if (pointA === null) {
  44692. pointA = cacheSoloPointer;
  44693. }
  44694. else if (pointB === null) {
  44695. pointB = cacheSoloPointer;
  44696. }
  44697. if (!noPreventDefault) {
  44698. evt.preventDefault();
  44699. element.focus();
  44700. }
  44701. }
  44702. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44703. _this.camera.restoreState();
  44704. }
  44705. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44706. try {
  44707. srcElement.releasePointerCapture(evt.pointerId);
  44708. }
  44709. catch (e) {
  44710. //Nothing to do with the error.
  44711. }
  44712. cacheSoloPointer = null;
  44713. previousPinchSquaredDistance = 0;
  44714. previousMultiTouchPanPosition.isPaning = false;
  44715. previousMultiTouchPanPosition.isPinching = false;
  44716. twoFingerActivityCount = 0;
  44717. initialDistance = 0;
  44718. if (!isTouch) {
  44719. pointB = null; // Mouse and pen are mono pointer
  44720. }
  44721. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44722. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44723. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44724. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44725. if (engine.badOS) {
  44726. pointA = pointB = null;
  44727. }
  44728. else {
  44729. //only remove the impacted pointer in case of multitouch allowing on most
  44730. //platforms switching from rotate to zoom and pan seamlessly.
  44731. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44732. pointA = pointB;
  44733. pointB = null;
  44734. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44735. }
  44736. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44737. pointB = null;
  44738. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44739. }
  44740. else {
  44741. pointA = pointB = null;
  44742. }
  44743. }
  44744. if (!noPreventDefault) {
  44745. evt.preventDefault();
  44746. }
  44747. }
  44748. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44749. if (!noPreventDefault) {
  44750. evt.preventDefault();
  44751. }
  44752. // One button down
  44753. if (pointA && pointB === null && cacheSoloPointer) {
  44754. if (_this.panningSensibility !== 0 &&
  44755. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44756. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44757. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44758. }
  44759. else {
  44760. var offsetX = evt.clientX - cacheSoloPointer.x;
  44761. var offsetY = evt.clientY - cacheSoloPointer.y;
  44762. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44763. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44764. }
  44765. cacheSoloPointer.x = evt.clientX;
  44766. cacheSoloPointer.y = evt.clientY;
  44767. }
  44768. else if (pointA && pointB) {
  44769. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44770. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44771. ed.x = evt.clientX;
  44772. ed.y = evt.clientY;
  44773. var direction = _this.pinchInwards ? 1 : -1;
  44774. var distX = pointA.x - pointB.x;
  44775. var distY = pointA.y - pointB.y;
  44776. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44777. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44778. if (previousPinchSquaredDistance === 0) {
  44779. initialDistance = pinchDistance;
  44780. previousPinchSquaredDistance = pinchSquaredDistance;
  44781. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44782. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44783. return;
  44784. }
  44785. if (_this.multiTouchPanAndZoom) {
  44786. if (_this.pinchDeltaPercentage) {
  44787. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44788. }
  44789. else {
  44790. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44791. (_this.pinchPrecision *
  44792. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44793. direction);
  44794. }
  44795. if (_this.panningSensibility !== 0) {
  44796. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44797. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44798. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44799. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44800. previousMultiTouchPanPosition.x = pointersCenterX;
  44801. previousMultiTouchPanPosition.y = pointersCenterY;
  44802. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44803. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44804. }
  44805. }
  44806. else {
  44807. twoFingerActivityCount++;
  44808. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44809. if (_this.pinchDeltaPercentage) {
  44810. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44811. }
  44812. else {
  44813. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44814. (_this.pinchPrecision *
  44815. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44816. direction);
  44817. }
  44818. previousMultiTouchPanPosition.isPaning = false;
  44819. previousMultiTouchPanPosition.isPinching = true;
  44820. }
  44821. else {
  44822. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44823. if (!previousMultiTouchPanPosition.isPaning) {
  44824. previousMultiTouchPanPosition.isPaning = true;
  44825. previousMultiTouchPanPosition.isPinching = false;
  44826. previousMultiTouchPanPosition.x = ed.x;
  44827. previousMultiTouchPanPosition.y = ed.y;
  44828. return;
  44829. }
  44830. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44831. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44832. }
  44833. }
  44834. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44835. previousMultiTouchPanPosition.x = ed.x;
  44836. previousMultiTouchPanPosition.y = ed.y;
  44837. }
  44838. }
  44839. previousPinchSquaredDistance = pinchSquaredDistance;
  44840. }
  44841. }
  44842. };
  44843. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44844. this._onContextMenu = function (evt) {
  44845. evt.preventDefault();
  44846. };
  44847. if (!this.camera._useCtrlForPanning) {
  44848. element.addEventListener("contextmenu", this._onContextMenu, false);
  44849. }
  44850. this._onLostFocus = function () {
  44851. //this._keys = [];
  44852. pointA = pointB = null;
  44853. previousPinchSquaredDistance = 0;
  44854. previousMultiTouchPanPosition.isPaning = false;
  44855. previousMultiTouchPanPosition.isPinching = false;
  44856. twoFingerActivityCount = 0;
  44857. cacheSoloPointer = null;
  44858. initialDistance = 0;
  44859. };
  44860. this._onMouseMove = function (evt) {
  44861. if (!engine.isPointerLock) {
  44862. return;
  44863. }
  44864. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44865. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44866. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44867. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44868. if (!noPreventDefault) {
  44869. evt.preventDefault();
  44870. }
  44871. };
  44872. this._onGestureStart = function (e) {
  44873. if (window.MSGesture === undefined) {
  44874. return;
  44875. }
  44876. if (!_this._MSGestureHandler) {
  44877. _this._MSGestureHandler = new MSGesture();
  44878. _this._MSGestureHandler.target = element;
  44879. }
  44880. _this._MSGestureHandler.addPointer(e.pointerId);
  44881. };
  44882. this._onGesture = function (e) {
  44883. _this.camera.radius *= e.scale;
  44884. if (e.preventDefault) {
  44885. if (!noPreventDefault) {
  44886. e.stopPropagation();
  44887. e.preventDefault();
  44888. }
  44889. }
  44890. };
  44891. element.addEventListener("mousemove", this._onMouseMove, false);
  44892. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44893. element.addEventListener("MSGestureChange", this._onGesture, false);
  44894. BABYLON.Tools.RegisterTopRootEvents([
  44895. { name: "blur", handler: this._onLostFocus }
  44896. ]);
  44897. };
  44898. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44899. if (this._onLostFocus) {
  44900. BABYLON.Tools.UnregisterTopRootEvents([
  44901. { name: "blur", handler: this._onLostFocus }
  44902. ]);
  44903. }
  44904. if (element && this._observer) {
  44905. this.camera.getScene().onPointerObservable.remove(this._observer);
  44906. this._observer = null;
  44907. if (this._onContextMenu) {
  44908. element.removeEventListener("contextmenu", this._onContextMenu);
  44909. }
  44910. if (this._onMouseMove) {
  44911. element.removeEventListener("mousemove", this._onMouseMove);
  44912. }
  44913. if (this._onGestureStart) {
  44914. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44915. }
  44916. if (this._onGesture) {
  44917. element.removeEventListener("MSGestureChange", this._onGesture);
  44918. }
  44919. this._isPanClick = false;
  44920. this.pinchInwards = true;
  44921. this._onMouseMove = null;
  44922. this._onGestureStart = null;
  44923. this._onGesture = null;
  44924. this._MSGestureHandler = null;
  44925. this._onLostFocus = null;
  44926. this._onContextMenu = null;
  44927. }
  44928. };
  44929. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44930. return "ArcRotateCameraPointersInput";
  44931. };
  44932. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44933. return "pointers";
  44934. };
  44935. __decorate([
  44936. BABYLON.serialize()
  44937. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44938. __decorate([
  44939. BABYLON.serialize()
  44940. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44941. __decorate([
  44942. BABYLON.serialize()
  44943. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44944. __decorate([
  44945. BABYLON.serialize()
  44946. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44947. __decorate([
  44948. BABYLON.serialize()
  44949. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44950. __decorate([
  44951. BABYLON.serialize()
  44952. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44953. __decorate([
  44954. BABYLON.serialize()
  44955. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44956. __decorate([
  44957. BABYLON.serialize()
  44958. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44959. return ArcRotateCameraPointersInput;
  44960. }());
  44961. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44962. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44963. })(BABYLON || (BABYLON = {}));
  44964. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44965. "use strict";
  44966. var BABYLON;
  44967. (function (BABYLON) {
  44968. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44969. __extends(ArcRotateCameraInputsManager, _super);
  44970. function ArcRotateCameraInputsManager(camera) {
  44971. return _super.call(this, camera) || this;
  44972. }
  44973. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44974. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44975. return this;
  44976. };
  44977. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44978. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44979. return this;
  44980. };
  44981. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44982. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44983. return this;
  44984. };
  44985. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44986. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44987. return this;
  44988. };
  44989. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44990. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44991. return this;
  44992. };
  44993. return ArcRotateCameraInputsManager;
  44994. }(BABYLON.CameraInputsManager));
  44995. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44996. })(BABYLON || (BABYLON = {}));
  44997. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44998. "use strict";
  44999. var BABYLON;
  45000. (function (BABYLON) {
  45001. var ArcRotateCamera = /** @class */ (function (_super) {
  45002. __extends(ArcRotateCamera, _super);
  45003. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  45004. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45005. _this.inertialAlphaOffset = 0;
  45006. _this.inertialBetaOffset = 0;
  45007. _this.inertialRadiusOffset = 0;
  45008. _this.lowerAlphaLimit = null;
  45009. _this.upperAlphaLimit = null;
  45010. _this.lowerBetaLimit = 0.01;
  45011. _this.upperBetaLimit = Math.PI;
  45012. _this.lowerRadiusLimit = null;
  45013. _this.upperRadiusLimit = null;
  45014. _this.inertialPanningX = 0;
  45015. _this.inertialPanningY = 0;
  45016. _this.pinchToPanMaxDistance = 20;
  45017. _this.panningDistanceLimit = null;
  45018. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  45019. _this.panningInertia = 0.9;
  45020. //-- end properties for backward compatibility for inputs
  45021. _this.zoomOnFactor = 1;
  45022. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  45023. _this.allowUpsideDown = true;
  45024. _this._viewMatrix = new BABYLON.Matrix();
  45025. // Panning
  45026. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45027. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45028. _this.checkCollisions = false;
  45029. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45030. _this._previousPosition = BABYLON.Vector3.Zero();
  45031. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45032. _this._newPosition = BABYLON.Vector3.Zero();
  45033. _this._computationVector = BABYLON.Vector3.Zero();
  45034. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45035. if (collidedMesh === void 0) { collidedMesh = null; }
  45036. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45037. newPosition.multiplyInPlace(_this._collider._radius);
  45038. }
  45039. if (!collidedMesh) {
  45040. _this._previousPosition.copyFrom(_this.position);
  45041. }
  45042. else {
  45043. _this.setPosition(newPosition);
  45044. if (_this.onCollide) {
  45045. _this.onCollide(collidedMesh);
  45046. }
  45047. }
  45048. // Recompute because of constraints
  45049. var cosa = Math.cos(_this.alpha);
  45050. var sina = Math.sin(_this.alpha);
  45051. var cosb = Math.cos(_this.beta);
  45052. var sinb = Math.sin(_this.beta);
  45053. if (sinb === 0) {
  45054. sinb = 0.0001;
  45055. }
  45056. var target = _this._getTargetPosition();
  45057. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45058. target.addToRef(_this._computationVector, _this._newPosition);
  45059. _this.position.copyFrom(_this._newPosition);
  45060. var up = _this.upVector;
  45061. if (_this.allowUpsideDown && _this.beta < 0) {
  45062. up = up.clone();
  45063. up = up.negate();
  45064. }
  45065. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45066. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45067. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45068. _this._collisionTriggered = false;
  45069. };
  45070. _this._target = BABYLON.Vector3.Zero();
  45071. if (target) {
  45072. _this.setTarget(target);
  45073. }
  45074. _this.alpha = alpha;
  45075. _this.beta = beta;
  45076. _this.radius = radius;
  45077. _this.getViewMatrix();
  45078. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45079. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45080. return _this;
  45081. }
  45082. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45083. get: function () {
  45084. return this._target;
  45085. },
  45086. set: function (value) {
  45087. this.setTarget(value);
  45088. },
  45089. enumerable: true,
  45090. configurable: true
  45091. });
  45092. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45093. //-- begin properties for backward compatibility for inputs
  45094. get: function () {
  45095. var pointers = this.inputs.attached["pointers"];
  45096. if (pointers)
  45097. return pointers.angularSensibilityX;
  45098. return 0;
  45099. },
  45100. set: function (value) {
  45101. var pointers = this.inputs.attached["pointers"];
  45102. if (pointers) {
  45103. pointers.angularSensibilityX = value;
  45104. }
  45105. },
  45106. enumerable: true,
  45107. configurable: true
  45108. });
  45109. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45110. get: function () {
  45111. var pointers = this.inputs.attached["pointers"];
  45112. if (pointers)
  45113. return pointers.angularSensibilityY;
  45114. return 0;
  45115. },
  45116. set: function (value) {
  45117. var pointers = this.inputs.attached["pointers"];
  45118. if (pointers) {
  45119. pointers.angularSensibilityY = value;
  45120. }
  45121. },
  45122. enumerable: true,
  45123. configurable: true
  45124. });
  45125. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45126. get: function () {
  45127. var pointers = this.inputs.attached["pointers"];
  45128. if (pointers)
  45129. return pointers.pinchPrecision;
  45130. return 0;
  45131. },
  45132. set: function (value) {
  45133. var pointers = this.inputs.attached["pointers"];
  45134. if (pointers) {
  45135. pointers.pinchPrecision = value;
  45136. }
  45137. },
  45138. enumerable: true,
  45139. configurable: true
  45140. });
  45141. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45142. get: function () {
  45143. var pointers = this.inputs.attached["pointers"];
  45144. if (pointers)
  45145. return pointers.pinchDeltaPercentage;
  45146. return 0;
  45147. },
  45148. set: function (value) {
  45149. var pointers = this.inputs.attached["pointers"];
  45150. if (pointers) {
  45151. pointers.pinchDeltaPercentage = value;
  45152. }
  45153. },
  45154. enumerable: true,
  45155. configurable: true
  45156. });
  45157. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45158. get: function () {
  45159. var pointers = this.inputs.attached["pointers"];
  45160. if (pointers)
  45161. return pointers.panningSensibility;
  45162. return 0;
  45163. },
  45164. set: function (value) {
  45165. var pointers = this.inputs.attached["pointers"];
  45166. if (pointers) {
  45167. pointers.panningSensibility = value;
  45168. }
  45169. },
  45170. enumerable: true,
  45171. configurable: true
  45172. });
  45173. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45174. get: function () {
  45175. var keyboard = this.inputs.attached["keyboard"];
  45176. if (keyboard)
  45177. return keyboard.keysUp;
  45178. return [];
  45179. },
  45180. set: function (value) {
  45181. var keyboard = this.inputs.attached["keyboard"];
  45182. if (keyboard)
  45183. keyboard.keysUp = value;
  45184. },
  45185. enumerable: true,
  45186. configurable: true
  45187. });
  45188. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45189. get: function () {
  45190. var keyboard = this.inputs.attached["keyboard"];
  45191. if (keyboard)
  45192. return keyboard.keysDown;
  45193. return [];
  45194. },
  45195. set: function (value) {
  45196. var keyboard = this.inputs.attached["keyboard"];
  45197. if (keyboard)
  45198. keyboard.keysDown = value;
  45199. },
  45200. enumerable: true,
  45201. configurable: true
  45202. });
  45203. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45204. get: function () {
  45205. var keyboard = this.inputs.attached["keyboard"];
  45206. if (keyboard)
  45207. return keyboard.keysLeft;
  45208. return [];
  45209. },
  45210. set: function (value) {
  45211. var keyboard = this.inputs.attached["keyboard"];
  45212. if (keyboard)
  45213. keyboard.keysLeft = value;
  45214. },
  45215. enumerable: true,
  45216. configurable: true
  45217. });
  45218. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45219. get: function () {
  45220. var keyboard = this.inputs.attached["keyboard"];
  45221. if (keyboard)
  45222. return keyboard.keysRight;
  45223. return [];
  45224. },
  45225. set: function (value) {
  45226. var keyboard = this.inputs.attached["keyboard"];
  45227. if (keyboard)
  45228. keyboard.keysRight = value;
  45229. },
  45230. enumerable: true,
  45231. configurable: true
  45232. });
  45233. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45234. get: function () {
  45235. var mousewheel = this.inputs.attached["mousewheel"];
  45236. if (mousewheel)
  45237. return mousewheel.wheelPrecision;
  45238. return 0;
  45239. },
  45240. set: function (value) {
  45241. var mousewheel = this.inputs.attached["mousewheel"];
  45242. if (mousewheel)
  45243. mousewheel.wheelPrecision = value;
  45244. },
  45245. enumerable: true,
  45246. configurable: true
  45247. });
  45248. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45249. get: function () {
  45250. var mousewheel = this.inputs.attached["mousewheel"];
  45251. if (mousewheel)
  45252. return mousewheel.wheelDeltaPercentage;
  45253. return 0;
  45254. },
  45255. set: function (value) {
  45256. var mousewheel = this.inputs.attached["mousewheel"];
  45257. if (mousewheel)
  45258. mousewheel.wheelDeltaPercentage = value;
  45259. },
  45260. enumerable: true,
  45261. configurable: true
  45262. });
  45263. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45264. get: function () {
  45265. return this._bouncingBehavior;
  45266. },
  45267. enumerable: true,
  45268. configurable: true
  45269. });
  45270. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45271. get: function () {
  45272. return this._bouncingBehavior != null;
  45273. },
  45274. set: function (value) {
  45275. if (value === this.useBouncingBehavior) {
  45276. return;
  45277. }
  45278. if (value) {
  45279. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45280. this.addBehavior(this._bouncingBehavior);
  45281. }
  45282. else if (this._bouncingBehavior) {
  45283. this.removeBehavior(this._bouncingBehavior);
  45284. this._bouncingBehavior = null;
  45285. }
  45286. },
  45287. enumerable: true,
  45288. configurable: true
  45289. });
  45290. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45291. get: function () {
  45292. return this._framingBehavior;
  45293. },
  45294. enumerable: true,
  45295. configurable: true
  45296. });
  45297. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45298. get: function () {
  45299. return this._framingBehavior != null;
  45300. },
  45301. set: function (value) {
  45302. if (value === this.useFramingBehavior) {
  45303. return;
  45304. }
  45305. if (value) {
  45306. this._framingBehavior = new BABYLON.FramingBehavior();
  45307. this.addBehavior(this._framingBehavior);
  45308. }
  45309. else if (this._framingBehavior) {
  45310. this.removeBehavior(this._framingBehavior);
  45311. this._framingBehavior = null;
  45312. }
  45313. },
  45314. enumerable: true,
  45315. configurable: true
  45316. });
  45317. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45318. get: function () {
  45319. return this._autoRotationBehavior;
  45320. },
  45321. enumerable: true,
  45322. configurable: true
  45323. });
  45324. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45325. get: function () {
  45326. return this._autoRotationBehavior != null;
  45327. },
  45328. set: function (value) {
  45329. if (value === this.useAutoRotationBehavior) {
  45330. return;
  45331. }
  45332. if (value) {
  45333. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45334. this.addBehavior(this._autoRotationBehavior);
  45335. }
  45336. else if (this._autoRotationBehavior) {
  45337. this.removeBehavior(this._autoRotationBehavior);
  45338. this._autoRotationBehavior = null;
  45339. }
  45340. },
  45341. enumerable: true,
  45342. configurable: true
  45343. });
  45344. // Cache
  45345. ArcRotateCamera.prototype._initCache = function () {
  45346. _super.prototype._initCache.call(this);
  45347. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45348. this._cache.alpha = undefined;
  45349. this._cache.beta = undefined;
  45350. this._cache.radius = undefined;
  45351. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45352. };
  45353. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45354. if (!ignoreParentClass) {
  45355. _super.prototype._updateCache.call(this);
  45356. }
  45357. this._cache._target.copyFrom(this._getTargetPosition());
  45358. this._cache.alpha = this.alpha;
  45359. this._cache.beta = this.beta;
  45360. this._cache.radius = this.radius;
  45361. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45362. };
  45363. ArcRotateCamera.prototype._getTargetPosition = function () {
  45364. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45365. var pos = this._targetHost.getAbsolutePosition();
  45366. if (this._targetBoundingCenter) {
  45367. pos.addToRef(this._targetBoundingCenter, this._target);
  45368. }
  45369. else {
  45370. this._target.copyFrom(pos);
  45371. }
  45372. }
  45373. var lockedTargetPosition = this._getLockedTargetPosition();
  45374. if (lockedTargetPosition) {
  45375. return lockedTargetPosition;
  45376. }
  45377. return this._target;
  45378. };
  45379. ArcRotateCamera.prototype.storeState = function () {
  45380. this._storedAlpha = this.alpha;
  45381. this._storedBeta = this.beta;
  45382. this._storedRadius = this.radius;
  45383. this._storedTarget = this._getTargetPosition().clone();
  45384. return _super.prototype.storeState.call(this);
  45385. };
  45386. /**
  45387. * Restored camera state. You must call storeState() first
  45388. */
  45389. ArcRotateCamera.prototype._restoreStateValues = function () {
  45390. if (!_super.prototype._restoreStateValues.call(this)) {
  45391. return false;
  45392. }
  45393. this.alpha = this._storedAlpha;
  45394. this.beta = this._storedBeta;
  45395. this.radius = this._storedRadius;
  45396. this.setTarget(this._storedTarget.clone());
  45397. this.inertialAlphaOffset = 0;
  45398. this.inertialBetaOffset = 0;
  45399. this.inertialRadiusOffset = 0;
  45400. this.inertialPanningX = 0;
  45401. this.inertialPanningY = 0;
  45402. return true;
  45403. };
  45404. // Synchronized
  45405. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45406. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45407. return false;
  45408. return this._cache._target.equals(this._getTargetPosition())
  45409. && this._cache.alpha === this.alpha
  45410. && this._cache.beta === this.beta
  45411. && this._cache.radius === this.radius
  45412. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45413. };
  45414. // Methods
  45415. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45416. var _this = this;
  45417. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45418. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45419. this._useCtrlForPanning = useCtrlForPanning;
  45420. this._panningMouseButton = panningMouseButton;
  45421. this.inputs.attachElement(element, noPreventDefault);
  45422. this._reset = function () {
  45423. _this.inertialAlphaOffset = 0;
  45424. _this.inertialBetaOffset = 0;
  45425. _this.inertialRadiusOffset = 0;
  45426. _this.inertialPanningX = 0;
  45427. _this.inertialPanningY = 0;
  45428. };
  45429. };
  45430. ArcRotateCamera.prototype.detachControl = function (element) {
  45431. this.inputs.detachElement(element);
  45432. if (this._reset) {
  45433. this._reset();
  45434. }
  45435. };
  45436. ArcRotateCamera.prototype._checkInputs = function () {
  45437. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45438. if (this._collisionTriggered) {
  45439. return;
  45440. }
  45441. this.inputs.checkInputs();
  45442. // Inertia
  45443. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45444. if (this.getScene().useRightHandedSystem) {
  45445. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45446. }
  45447. else {
  45448. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45449. }
  45450. this.beta += this.inertialBetaOffset;
  45451. this.radius -= this.inertialRadiusOffset;
  45452. this.inertialAlphaOffset *= this.inertia;
  45453. this.inertialBetaOffset *= this.inertia;
  45454. this.inertialRadiusOffset *= this.inertia;
  45455. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45456. this.inertialAlphaOffset = 0;
  45457. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45458. this.inertialBetaOffset = 0;
  45459. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45460. this.inertialRadiusOffset = 0;
  45461. }
  45462. // Panning inertia
  45463. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45464. if (!this._localDirection) {
  45465. this._localDirection = BABYLON.Vector3.Zero();
  45466. this._transformedDirection = BABYLON.Vector3.Zero();
  45467. }
  45468. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45469. this._localDirection.multiplyInPlace(this.panningAxis);
  45470. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45471. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45472. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45473. if (!this.panningAxis.y) {
  45474. this._transformedDirection.y = 0;
  45475. }
  45476. if (!this._targetHost) {
  45477. if (this.panningDistanceLimit) {
  45478. this._transformedDirection.addInPlace(this._target);
  45479. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45480. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45481. this._target.copyFrom(this._transformedDirection);
  45482. }
  45483. }
  45484. else {
  45485. this._target.addInPlace(this._transformedDirection);
  45486. }
  45487. }
  45488. this.inertialPanningX *= this.panningInertia;
  45489. this.inertialPanningY *= this.panningInertia;
  45490. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45491. this.inertialPanningX = 0;
  45492. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45493. this.inertialPanningY = 0;
  45494. }
  45495. // Limits
  45496. this._checkLimits();
  45497. _super.prototype._checkInputs.call(this);
  45498. };
  45499. ArcRotateCamera.prototype._checkLimits = function () {
  45500. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45501. if (this.allowUpsideDown && this.beta > Math.PI) {
  45502. this.beta = this.beta - (2 * Math.PI);
  45503. }
  45504. }
  45505. else {
  45506. if (this.beta < this.lowerBetaLimit) {
  45507. this.beta = this.lowerBetaLimit;
  45508. }
  45509. }
  45510. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45511. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45512. this.beta = this.beta + (2 * Math.PI);
  45513. }
  45514. }
  45515. else {
  45516. if (this.beta > this.upperBetaLimit) {
  45517. this.beta = this.upperBetaLimit;
  45518. }
  45519. }
  45520. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45521. this.alpha = this.lowerAlphaLimit;
  45522. }
  45523. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45524. this.alpha = this.upperAlphaLimit;
  45525. }
  45526. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45527. this.radius = this.lowerRadiusLimit;
  45528. }
  45529. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45530. this.radius = this.upperRadiusLimit;
  45531. }
  45532. };
  45533. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45534. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45535. this.radius = this._computationVector.length();
  45536. if (this.radius === 0) {
  45537. this.radius = 0.0001; // Just to avoid division by zero
  45538. }
  45539. // Alpha
  45540. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45541. if (this._computationVector.z < 0) {
  45542. this.alpha = 2 * Math.PI - this.alpha;
  45543. }
  45544. // Beta
  45545. this.beta = Math.acos(this._computationVector.y / this.radius);
  45546. this._checkLimits();
  45547. };
  45548. ArcRotateCamera.prototype.setPosition = function (position) {
  45549. if (this.position.equals(position)) {
  45550. return;
  45551. }
  45552. this.position.copyFrom(position);
  45553. this.rebuildAnglesAndRadius();
  45554. };
  45555. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45556. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45557. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45558. if (target.getBoundingInfo) {
  45559. if (toBoundingCenter) {
  45560. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45561. }
  45562. else {
  45563. this._targetBoundingCenter = null;
  45564. }
  45565. this._targetHost = target;
  45566. this._target = this._getTargetPosition();
  45567. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45568. }
  45569. else {
  45570. var newTarget = target;
  45571. var currentTarget = this._getTargetPosition();
  45572. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45573. return;
  45574. }
  45575. this._targetHost = null;
  45576. this._target = newTarget;
  45577. this._targetBoundingCenter = null;
  45578. this.onMeshTargetChangedObservable.notifyObservers(null);
  45579. }
  45580. this.rebuildAnglesAndRadius();
  45581. };
  45582. ArcRotateCamera.prototype._getViewMatrix = function () {
  45583. // Compute
  45584. var cosa = Math.cos(this.alpha);
  45585. var sina = Math.sin(this.alpha);
  45586. var cosb = Math.cos(this.beta);
  45587. var sinb = Math.sin(this.beta);
  45588. if (sinb === 0) {
  45589. sinb = 0.0001;
  45590. }
  45591. var target = this._getTargetPosition();
  45592. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45593. target.addToRef(this._computationVector, this._newPosition);
  45594. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45595. if (!this._collider) {
  45596. this._collider = new BABYLON.Collider();
  45597. }
  45598. this._collider._radius = this.collisionRadius;
  45599. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45600. this._collisionTriggered = true;
  45601. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45602. }
  45603. else {
  45604. this.position.copyFrom(this._newPosition);
  45605. var up = this.upVector;
  45606. if (this.allowUpsideDown && sinb < 0) {
  45607. up = up.clone();
  45608. up = up.negate();
  45609. }
  45610. if (this.getScene().useRightHandedSystem) {
  45611. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45612. }
  45613. else {
  45614. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45615. }
  45616. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45617. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45618. }
  45619. this._currentTarget = target;
  45620. return this._viewMatrix;
  45621. };
  45622. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45623. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45624. meshes = meshes || this.getScene().meshes;
  45625. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45626. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45627. this.radius = distance * this.zoomOnFactor;
  45628. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45629. };
  45630. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45631. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45632. var meshesOrMinMaxVector;
  45633. var distance;
  45634. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45635. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45636. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45637. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45638. }
  45639. else {
  45640. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45641. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45642. distance = minMaxVectorAndDistance.distance;
  45643. }
  45644. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45645. if (!doNotUpdateMaxZ) {
  45646. this.maxZ = distance * 2;
  45647. }
  45648. };
  45649. /**
  45650. * @override
  45651. * Override Camera.createRigCamera
  45652. */
  45653. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45654. var alphaShift = 0;
  45655. switch (this.cameraRigMode) {
  45656. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45657. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45658. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45659. case BABYLON.Camera.RIG_MODE_VR:
  45660. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45661. break;
  45662. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45663. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45664. break;
  45665. }
  45666. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45667. rigCam._cameraRigParams = {};
  45668. return rigCam;
  45669. };
  45670. /**
  45671. * @override
  45672. * Override Camera._updateRigCameras
  45673. */
  45674. ArcRotateCamera.prototype._updateRigCameras = function () {
  45675. var camLeft = this._rigCameras[0];
  45676. var camRight = this._rigCameras[1];
  45677. camLeft.beta = camRight.beta = this.beta;
  45678. camLeft.radius = camRight.radius = this.radius;
  45679. switch (this.cameraRigMode) {
  45680. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45681. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45682. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45683. case BABYLON.Camera.RIG_MODE_VR:
  45684. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45685. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45686. break;
  45687. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45688. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45689. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45690. break;
  45691. }
  45692. _super.prototype._updateRigCameras.call(this);
  45693. };
  45694. ArcRotateCamera.prototype.dispose = function () {
  45695. this.inputs.clear();
  45696. _super.prototype.dispose.call(this);
  45697. };
  45698. ArcRotateCamera.prototype.getClassName = function () {
  45699. return "ArcRotateCamera";
  45700. };
  45701. __decorate([
  45702. BABYLON.serialize()
  45703. ], ArcRotateCamera.prototype, "alpha", void 0);
  45704. __decorate([
  45705. BABYLON.serialize()
  45706. ], ArcRotateCamera.prototype, "beta", void 0);
  45707. __decorate([
  45708. BABYLON.serialize()
  45709. ], ArcRotateCamera.prototype, "radius", void 0);
  45710. __decorate([
  45711. BABYLON.serializeAsVector3("target")
  45712. ], ArcRotateCamera.prototype, "_target", void 0);
  45713. __decorate([
  45714. BABYLON.serialize()
  45715. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45716. __decorate([
  45717. BABYLON.serialize()
  45718. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45719. __decorate([
  45720. BABYLON.serialize()
  45721. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45722. __decorate([
  45723. BABYLON.serialize()
  45724. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45725. __decorate([
  45726. BABYLON.serialize()
  45727. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45728. __decorate([
  45729. BABYLON.serialize()
  45730. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45731. __decorate([
  45732. BABYLON.serialize()
  45733. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45734. __decorate([
  45735. BABYLON.serialize()
  45736. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45737. __decorate([
  45738. BABYLON.serialize()
  45739. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45740. __decorate([
  45741. BABYLON.serialize()
  45742. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45743. __decorate([
  45744. BABYLON.serialize()
  45745. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45746. __decorate([
  45747. BABYLON.serialize()
  45748. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45749. __decorate([
  45750. BABYLON.serialize()
  45751. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45752. __decorate([
  45753. BABYLON.serializeAsVector3()
  45754. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45755. __decorate([
  45756. BABYLON.serialize()
  45757. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45758. __decorate([
  45759. BABYLON.serialize()
  45760. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45761. __decorate([
  45762. BABYLON.serialize()
  45763. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45764. return ArcRotateCamera;
  45765. }(BABYLON.TargetCamera));
  45766. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45767. })(BABYLON || (BABYLON = {}));
  45768. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45769. "use strict";
  45770. var BABYLON;
  45771. (function (BABYLON) {
  45772. /**
  45773. * The HemisphericLight simulates the ambient environment light,
  45774. * so the passed direction is the light reflection direction, not the incoming direction.
  45775. */
  45776. var HemisphericLight = /** @class */ (function (_super) {
  45777. __extends(HemisphericLight, _super);
  45778. /**
  45779. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45780. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45781. * The HemisphericLight can't cast shadows.
  45782. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45783. * @param name The friendly name of the light
  45784. * @param direction The direction of the light reflection
  45785. * @param scene The scene the light belongs to
  45786. */
  45787. function HemisphericLight(name, direction, scene) {
  45788. var _this = _super.call(this, name, scene) || this;
  45789. /**
  45790. * The groundColor is the light in the opposite direction to the one specified during creation.
  45791. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  45792. */
  45793. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45794. _this.direction = direction || BABYLON.Vector3.Up();
  45795. return _this;
  45796. }
  45797. HemisphericLight.prototype._buildUniformLayout = function () {
  45798. this._uniformBuffer.addUniform("vLightData", 4);
  45799. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45800. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45801. this._uniformBuffer.addUniform("vLightGround", 3);
  45802. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45803. this._uniformBuffer.addUniform("depthValues", 2);
  45804. this._uniformBuffer.create();
  45805. };
  45806. /**
  45807. * Returns the string "HemisphericLight".
  45808. * @return The class name
  45809. */
  45810. HemisphericLight.prototype.getClassName = function () {
  45811. return "HemisphericLight";
  45812. };
  45813. /**
  45814. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45815. * Returns the updated direction.
  45816. * @param target The target the direction should point to
  45817. * @return The computed direction
  45818. */
  45819. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45820. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45821. return this.direction;
  45822. };
  45823. /**
  45824. * Returns the shadow generator associated to the light.
  45825. * @returns Always null for hemispheric lights because it does not support shadows.
  45826. */
  45827. HemisphericLight.prototype.getShadowGenerator = function () {
  45828. return null;
  45829. };
  45830. /**
  45831. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45832. * @param effect The effect to update
  45833. * @param lightIndex The index of the light in the effect to update
  45834. * @returns The hemispheric light
  45835. */
  45836. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45837. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45838. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45839. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45840. return this;
  45841. };
  45842. /**
  45843. * @ignore internal use only.
  45844. */
  45845. HemisphericLight.prototype._getWorldMatrix = function () {
  45846. if (!this._worldMatrix) {
  45847. this._worldMatrix = BABYLON.Matrix.Identity();
  45848. }
  45849. return this._worldMatrix;
  45850. };
  45851. /**
  45852. * Returns the integer 3.
  45853. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45854. */
  45855. HemisphericLight.prototype.getTypeID = function () {
  45856. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45857. };
  45858. __decorate([
  45859. BABYLON.serializeAsColor3()
  45860. ], HemisphericLight.prototype, "groundColor", void 0);
  45861. __decorate([
  45862. BABYLON.serializeAsVector3()
  45863. ], HemisphericLight.prototype, "direction", void 0);
  45864. return HemisphericLight;
  45865. }(BABYLON.Light));
  45866. BABYLON.HemisphericLight = HemisphericLight;
  45867. })(BABYLON || (BABYLON = {}));
  45868. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45869. "use strict";
  45870. var BABYLON;
  45871. (function (BABYLON) {
  45872. /**
  45873. * Base implementation of @see IShadowLight
  45874. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45875. */
  45876. var ShadowLight = /** @class */ (function (_super) {
  45877. __extends(ShadowLight, _super);
  45878. function ShadowLight() {
  45879. var _this = _super !== null && _super.apply(this, arguments) || this;
  45880. _this._needProjectionMatrixCompute = true;
  45881. return _this;
  45882. }
  45883. ShadowLight.prototype._setPosition = function (value) {
  45884. this._position = value;
  45885. };
  45886. Object.defineProperty(ShadowLight.prototype, "position", {
  45887. /**
  45888. * Sets the position the shadow will be casted from. Also use as the light position for both
  45889. * point and spot lights.
  45890. */
  45891. get: function () {
  45892. return this._position;
  45893. },
  45894. /**
  45895. * Sets the position the shadow will be casted from. Also use as the light position for both
  45896. * point and spot lights.
  45897. */
  45898. set: function (value) {
  45899. this._setPosition(value);
  45900. },
  45901. enumerable: true,
  45902. configurable: true
  45903. });
  45904. ShadowLight.prototype._setDirection = function (value) {
  45905. this._direction = value;
  45906. };
  45907. Object.defineProperty(ShadowLight.prototype, "direction", {
  45908. /**
  45909. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45910. * Also use as the light direction on spot and directional lights.
  45911. */
  45912. get: function () {
  45913. return this._direction;
  45914. },
  45915. /**
  45916. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45917. * Also use as the light direction on spot and directional lights.
  45918. */
  45919. set: function (value) {
  45920. this._setDirection(value);
  45921. },
  45922. enumerable: true,
  45923. configurable: true
  45924. });
  45925. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45926. /**
  45927. * Gets the shadow projection clipping minimum z value.
  45928. */
  45929. get: function () {
  45930. return this._shadowMinZ;
  45931. },
  45932. /**
  45933. * Sets the shadow projection clipping minimum z value.
  45934. */
  45935. set: function (value) {
  45936. this._shadowMinZ = value;
  45937. this.forceProjectionMatrixCompute();
  45938. },
  45939. enumerable: true,
  45940. configurable: true
  45941. });
  45942. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45943. /**
  45944. * Sets the shadow projection clipping maximum z value.
  45945. */
  45946. get: function () {
  45947. return this._shadowMaxZ;
  45948. },
  45949. /**
  45950. * Gets the shadow projection clipping maximum z value.
  45951. */
  45952. set: function (value) {
  45953. this._shadowMaxZ = value;
  45954. this.forceProjectionMatrixCompute();
  45955. },
  45956. enumerable: true,
  45957. configurable: true
  45958. });
  45959. /**
  45960. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45961. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45962. */
  45963. ShadowLight.prototype.computeTransformedInformation = function () {
  45964. if (this.parent && this.parent.getWorldMatrix) {
  45965. if (!this.transformedPosition) {
  45966. this.transformedPosition = BABYLON.Vector3.Zero();
  45967. }
  45968. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45969. // In case the direction is present.
  45970. if (this.direction) {
  45971. if (!this.transformedDirection) {
  45972. this.transformedDirection = BABYLON.Vector3.Zero();
  45973. }
  45974. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45975. }
  45976. return true;
  45977. }
  45978. return false;
  45979. };
  45980. /**
  45981. * Return the depth scale used for the shadow map.
  45982. * @returns the depth scale.
  45983. */
  45984. ShadowLight.prototype.getDepthScale = function () {
  45985. return 50.0;
  45986. };
  45987. /**
  45988. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45989. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45990. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45991. */
  45992. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45993. return this.transformedDirection ? this.transformedDirection : this.direction;
  45994. };
  45995. /**
  45996. * Returns the ShadowLight absolute position in the World.
  45997. * @returns the position vector in world space
  45998. */
  45999. ShadowLight.prototype.getAbsolutePosition = function () {
  46000. return this.transformedPosition ? this.transformedPosition : this.position;
  46001. };
  46002. /**
  46003. * Sets the ShadowLight direction toward the passed target.
  46004. * @param target The point tot target in local space
  46005. * @returns the updated ShadowLight direction
  46006. */
  46007. ShadowLight.prototype.setDirectionToTarget = function (target) {
  46008. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  46009. return this.direction;
  46010. };
  46011. /**
  46012. * Returns the light rotation in euler definition.
  46013. * @returns the x y z rotation in local space.
  46014. */
  46015. ShadowLight.prototype.getRotation = function () {
  46016. this.direction.normalize();
  46017. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  46018. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  46019. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  46020. };
  46021. /**
  46022. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  46023. * @returns true if a cube texture needs to be use
  46024. */
  46025. ShadowLight.prototype.needCube = function () {
  46026. return false;
  46027. };
  46028. /**
  46029. * Detects if the projection matrix requires to be recomputed this frame.
  46030. * @returns true if it requires to be recomputed otherwise, false.
  46031. */
  46032. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46033. return this._needProjectionMatrixCompute;
  46034. };
  46035. /**
  46036. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46037. */
  46038. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46039. this._needProjectionMatrixCompute = true;
  46040. };
  46041. /**
  46042. * Get the world matrix of the sahdow lights.
  46043. * @ignore Internal Use Only
  46044. */
  46045. ShadowLight.prototype._getWorldMatrix = function () {
  46046. if (!this._worldMatrix) {
  46047. this._worldMatrix = BABYLON.Matrix.Identity();
  46048. }
  46049. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46050. return this._worldMatrix;
  46051. };
  46052. /**
  46053. * Gets the minZ used for shadow according to both the scene and the light.
  46054. * @param activeCamera The camera we are returning the min for
  46055. * @returns the depth min z
  46056. */
  46057. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46058. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46059. };
  46060. /**
  46061. * Gets the maxZ used for shadow according to both the scene and the light.
  46062. * @param activeCamera The camera we are returning the max for
  46063. * @returns the depth max z
  46064. */
  46065. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46066. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46067. };
  46068. /**
  46069. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46070. * @param matrix The materix to updated with the projection information
  46071. * @param viewMatrix The transform matrix of the light
  46072. * @param renderList The list of mesh to render in the map
  46073. * @returns The current light
  46074. */
  46075. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46076. if (this.customProjectionMatrixBuilder) {
  46077. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46078. }
  46079. else {
  46080. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46081. }
  46082. return this;
  46083. };
  46084. __decorate([
  46085. BABYLON.serializeAsVector3()
  46086. ], ShadowLight.prototype, "position", null);
  46087. __decorate([
  46088. BABYLON.serializeAsVector3()
  46089. ], ShadowLight.prototype, "direction", null);
  46090. __decorate([
  46091. BABYLON.serialize()
  46092. ], ShadowLight.prototype, "shadowMinZ", null);
  46093. __decorate([
  46094. BABYLON.serialize()
  46095. ], ShadowLight.prototype, "shadowMaxZ", null);
  46096. return ShadowLight;
  46097. }(BABYLON.Light));
  46098. BABYLON.ShadowLight = ShadowLight;
  46099. })(BABYLON || (BABYLON = {}));
  46100. //# sourceMappingURL=babylon.shadowLight.js.map
  46101. "use strict";
  46102. var BABYLON;
  46103. (function (BABYLON) {
  46104. /**
  46105. * A point light is a light defined by an unique point in world space.
  46106. * The light is emitted in every direction from this point.
  46107. * A good example of a point light is a standard light bulb.
  46108. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46109. */
  46110. var PointLight = /** @class */ (function (_super) {
  46111. __extends(PointLight, _super);
  46112. /**
  46113. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46114. * A PointLight emits the light in every direction.
  46115. * It can cast shadows.
  46116. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46117. * ```javascript
  46118. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46119. * ```
  46120. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46121. * @param name The light friendly name
  46122. * @param position The position of the point light in the scene
  46123. * @param scene The scene the lights belongs to
  46124. */
  46125. function PointLight(name, position, scene) {
  46126. var _this = _super.call(this, name, scene) || this;
  46127. _this._shadowAngle = Math.PI / 2;
  46128. _this.position = position;
  46129. return _this;
  46130. }
  46131. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46132. /**
  46133. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46134. * This specifies what angle the shadow will use to be created.
  46135. *
  46136. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46137. */
  46138. get: function () {
  46139. return this._shadowAngle;
  46140. },
  46141. /**
  46142. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46143. * This specifies what angle the shadow will use to be created.
  46144. *
  46145. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46146. */
  46147. set: function (value) {
  46148. this._shadowAngle = value;
  46149. this.forceProjectionMatrixCompute();
  46150. },
  46151. enumerable: true,
  46152. configurable: true
  46153. });
  46154. Object.defineProperty(PointLight.prototype, "direction", {
  46155. /**
  46156. * Gets the direction if it has been set.
  46157. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46158. */
  46159. get: function () {
  46160. return this._direction;
  46161. },
  46162. /**
  46163. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46164. */
  46165. set: function (value) {
  46166. var previousNeedCube = this.needCube();
  46167. this._direction = value;
  46168. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46169. this._shadowGenerator.recreateShadowMap();
  46170. }
  46171. },
  46172. enumerable: true,
  46173. configurable: true
  46174. });
  46175. /**
  46176. * Returns the string "PointLight"
  46177. * @returns the class name
  46178. */
  46179. PointLight.prototype.getClassName = function () {
  46180. return "PointLight";
  46181. };
  46182. /**
  46183. * Returns the integer 0.
  46184. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46185. */
  46186. PointLight.prototype.getTypeID = function () {
  46187. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46188. };
  46189. /**
  46190. * Specifies wether or not the shadowmap should be a cube texture.
  46191. * @returns true if the shadowmap needs to be a cube texture.
  46192. */
  46193. PointLight.prototype.needCube = function () {
  46194. return !this.direction;
  46195. };
  46196. /**
  46197. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46198. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46199. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46200. */
  46201. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46202. if (this.direction) {
  46203. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46204. }
  46205. else {
  46206. switch (faceIndex) {
  46207. case 0:
  46208. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46209. case 1:
  46210. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46211. case 2:
  46212. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46213. case 3:
  46214. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46215. case 4:
  46216. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46217. case 5:
  46218. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46219. }
  46220. }
  46221. return BABYLON.Vector3.Zero();
  46222. };
  46223. /**
  46224. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46225. * - fov = PI / 2
  46226. * - aspect ratio : 1.0
  46227. * - z-near and far equal to the active camera minZ and maxZ.
  46228. * Returns the PointLight.
  46229. */
  46230. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46231. var activeCamera = this.getScene().activeCamera;
  46232. if (!activeCamera) {
  46233. return;
  46234. }
  46235. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46236. };
  46237. PointLight.prototype._buildUniformLayout = function () {
  46238. this._uniformBuffer.addUniform("vLightData", 4);
  46239. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46240. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46241. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46242. this._uniformBuffer.addUniform("depthValues", 2);
  46243. this._uniformBuffer.create();
  46244. };
  46245. /**
  46246. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46247. * @param effect The effect to update
  46248. * @param lightIndex The index of the light in the effect to update
  46249. * @returns The point light
  46250. */
  46251. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46252. if (this.computeTransformedInformation()) {
  46253. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46254. return this;
  46255. }
  46256. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46257. return this;
  46258. };
  46259. __decorate([
  46260. BABYLON.serialize()
  46261. ], PointLight.prototype, "shadowAngle", null);
  46262. return PointLight;
  46263. }(BABYLON.ShadowLight));
  46264. BABYLON.PointLight = PointLight;
  46265. })(BABYLON || (BABYLON = {}));
  46266. //# sourceMappingURL=babylon.pointLight.js.map
  46267. "use strict";
  46268. var BABYLON;
  46269. (function (BABYLON) {
  46270. /**
  46271. * A directional light is defined by a direction (what a surprise!).
  46272. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46273. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  46274. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46275. */
  46276. var DirectionalLight = /** @class */ (function (_super) {
  46277. __extends(DirectionalLight, _super);
  46278. /**
  46279. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46280. * The directional light is emitted from everywhere in the given direction.
  46281. * It can cast shawdows.
  46282. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46283. * @param name The friendly name of the light
  46284. * @param direction The direction of the light
  46285. * @param scene The scene the light belongs to
  46286. */
  46287. function DirectionalLight(name, direction, scene) {
  46288. var _this = _super.call(this, name, scene) || this;
  46289. _this._shadowFrustumSize = 0;
  46290. _this._shadowOrthoScale = 0.1;
  46291. /**
  46292. * Automatically compute the projection matrix to best fit (including all the casters)
  46293. * on each frame.
  46294. */
  46295. _this.autoUpdateExtends = true;
  46296. // Cache
  46297. _this._orthoLeft = Number.MAX_VALUE;
  46298. _this._orthoRight = Number.MIN_VALUE;
  46299. _this._orthoTop = Number.MIN_VALUE;
  46300. _this._orthoBottom = Number.MAX_VALUE;
  46301. _this.position = direction.scale(-1.0);
  46302. _this.direction = direction;
  46303. return _this;
  46304. }
  46305. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46306. /**
  46307. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46308. */
  46309. get: function () {
  46310. return this._shadowFrustumSize;
  46311. },
  46312. /**
  46313. * Specifies a fix frustum size for the shadow generation.
  46314. */
  46315. set: function (value) {
  46316. this._shadowFrustumSize = value;
  46317. this.forceProjectionMatrixCompute();
  46318. },
  46319. enumerable: true,
  46320. configurable: true
  46321. });
  46322. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46323. /**
  46324. * Gets the shadow projection scale against the optimal computed one.
  46325. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46326. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46327. */
  46328. get: function () {
  46329. return this._shadowOrthoScale;
  46330. },
  46331. /**
  46332. * Sets the shadow projection scale against the optimal computed one.
  46333. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46334. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46335. */
  46336. set: function (value) {
  46337. this._shadowOrthoScale = value;
  46338. this.forceProjectionMatrixCompute();
  46339. },
  46340. enumerable: true,
  46341. configurable: true
  46342. });
  46343. /**
  46344. * Returns the string "DirectionalLight".
  46345. * @return The class name
  46346. */
  46347. DirectionalLight.prototype.getClassName = function () {
  46348. return "DirectionalLight";
  46349. };
  46350. /**
  46351. * Returns the integer 1.
  46352. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46353. */
  46354. DirectionalLight.prototype.getTypeID = function () {
  46355. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46356. };
  46357. /**
  46358. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46359. * Returns the DirectionalLight Shadow projection matrix.
  46360. */
  46361. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46362. if (this.shadowFrustumSize > 0) {
  46363. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46364. }
  46365. else {
  46366. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46367. }
  46368. };
  46369. /**
  46370. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46371. * Returns the DirectionalLight Shadow projection matrix.
  46372. */
  46373. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46374. var activeCamera = this.getScene().activeCamera;
  46375. if (!activeCamera) {
  46376. return;
  46377. }
  46378. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46379. };
  46380. /**
  46381. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46382. * Returns the DirectionalLight Shadow projection matrix.
  46383. */
  46384. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46385. var activeCamera = this.getScene().activeCamera;
  46386. if (!activeCamera) {
  46387. return;
  46388. }
  46389. // Check extends
  46390. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46391. var tempVector3 = BABYLON.Vector3.Zero();
  46392. this._orthoLeft = Number.MAX_VALUE;
  46393. this._orthoRight = Number.MIN_VALUE;
  46394. this._orthoTop = Number.MIN_VALUE;
  46395. this._orthoBottom = Number.MAX_VALUE;
  46396. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46397. var mesh = renderList[meshIndex];
  46398. if (!mesh) {
  46399. continue;
  46400. }
  46401. var boundingInfo = mesh.getBoundingInfo();
  46402. var boundingBox = boundingInfo.boundingBox;
  46403. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46404. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46405. if (tempVector3.x < this._orthoLeft)
  46406. this._orthoLeft = tempVector3.x;
  46407. if (tempVector3.y < this._orthoBottom)
  46408. this._orthoBottom = tempVector3.y;
  46409. if (tempVector3.x > this._orthoRight)
  46410. this._orthoRight = tempVector3.x;
  46411. if (tempVector3.y > this._orthoTop)
  46412. this._orthoTop = tempVector3.y;
  46413. }
  46414. }
  46415. }
  46416. var xOffset = this._orthoRight - this._orthoLeft;
  46417. var yOffset = this._orthoTop - this._orthoBottom;
  46418. 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);
  46419. };
  46420. DirectionalLight.prototype._buildUniformLayout = function () {
  46421. this._uniformBuffer.addUniform("vLightData", 4);
  46422. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46423. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46424. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46425. this._uniformBuffer.addUniform("depthValues", 2);
  46426. this._uniformBuffer.create();
  46427. };
  46428. /**
  46429. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46430. * @param effect The effect to update
  46431. * @param lightIndex The index of the light in the effect to update
  46432. * @returns The directional light
  46433. */
  46434. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46435. if (this.computeTransformedInformation()) {
  46436. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46437. return this;
  46438. }
  46439. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46440. return this;
  46441. };
  46442. /**
  46443. * Gets the minZ used for shadow according to both the scene and the light.
  46444. *
  46445. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46446. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46447. * @param activeCamera The camera we are returning the min for
  46448. * @returns the depth min z
  46449. */
  46450. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46451. return 1;
  46452. };
  46453. /**
  46454. * Gets the maxZ used for shadow according to both the scene and the light.
  46455. *
  46456. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46457. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46458. * @param activeCamera The camera we are returning the max for
  46459. * @returns the depth max z
  46460. */
  46461. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46462. return 1;
  46463. };
  46464. __decorate([
  46465. BABYLON.serialize()
  46466. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46467. __decorate([
  46468. BABYLON.serialize()
  46469. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46470. __decorate([
  46471. BABYLON.serialize()
  46472. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46473. return DirectionalLight;
  46474. }(BABYLON.ShadowLight));
  46475. BABYLON.DirectionalLight = DirectionalLight;
  46476. })(BABYLON || (BABYLON = {}));
  46477. //# sourceMappingURL=babylon.directionalLight.js.map
  46478. "use strict";
  46479. var BABYLON;
  46480. (function (BABYLON) {
  46481. /**
  46482. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46483. * These values define a cone of light starting from the position, emitting toward the direction.
  46484. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46485. * and the exponent defines the speed of the decay of the light with distance (reach).
  46486. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46487. */
  46488. var SpotLight = /** @class */ (function (_super) {
  46489. __extends(SpotLight, _super);
  46490. /**
  46491. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46492. * It can cast shadows.
  46493. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46494. * @param name The light friendly name
  46495. * @param position The position of the spot light in the scene
  46496. * @param direction The direction of the light in the scene
  46497. * @param angle The cone angle of the light in Radians
  46498. * @param exponent The light decay speed with the distance from the emission spot
  46499. * @param scene The scene the lights belongs to
  46500. */
  46501. function SpotLight(name, position, direction, angle, exponent, scene) {
  46502. var _this = _super.call(this, name, scene) || this;
  46503. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46504. _this._projectionTextureLightNear = 1e-6;
  46505. _this._projectionTextureLightFar = 1000.0;
  46506. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46507. _this._projectionTextureViewLightDirty = true;
  46508. _this._projectionTextureProjectionLightDirty = true;
  46509. _this._projectionTextureDirty = true;
  46510. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46511. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46512. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46513. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  46514. _this.position = position;
  46515. _this.direction = direction;
  46516. _this.angle = angle;
  46517. _this.exponent = exponent;
  46518. return _this;
  46519. }
  46520. Object.defineProperty(SpotLight.prototype, "angle", {
  46521. /**
  46522. * Gets the cone angle of the spot light in Radians.
  46523. */
  46524. get: function () {
  46525. return this._angle;
  46526. },
  46527. /**
  46528. * Sets the cone angle of the spot light in Radians.
  46529. */
  46530. set: function (value) {
  46531. this._angle = value;
  46532. this._projectionTextureProjectionLightDirty = true;
  46533. this.forceProjectionMatrixCompute();
  46534. },
  46535. enumerable: true,
  46536. configurable: true
  46537. });
  46538. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46539. /**
  46540. * Allows scaling the angle of the light for shadow generation only.
  46541. */
  46542. get: function () {
  46543. return this._shadowAngleScale;
  46544. },
  46545. /**
  46546. * Allows scaling the angle of the light for shadow generation only.
  46547. */
  46548. set: function (value) {
  46549. this._shadowAngleScale = value;
  46550. this.forceProjectionMatrixCompute();
  46551. },
  46552. enumerable: true,
  46553. configurable: true
  46554. });
  46555. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46556. /**
  46557. * Allows reading the projecton texture
  46558. */
  46559. get: function () {
  46560. return this._projectionTextureMatrix;
  46561. },
  46562. enumerable: true,
  46563. configurable: true
  46564. });
  46565. ;
  46566. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46567. /**
  46568. * Gets the near clip of the Spotlight for texture projection.
  46569. */
  46570. get: function () {
  46571. return this._projectionTextureLightNear;
  46572. },
  46573. /**
  46574. * Sets the near clip of the Spotlight for texture projection.
  46575. */
  46576. set: function (value) {
  46577. this._projectionTextureLightNear = value;
  46578. this._projectionTextureProjectionLightDirty = true;
  46579. },
  46580. enumerable: true,
  46581. configurable: true
  46582. });
  46583. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46584. /**
  46585. * Gets the far clip of the Spotlight for texture projection.
  46586. */
  46587. get: function () {
  46588. return this._projectionTextureLightFar;
  46589. },
  46590. /**
  46591. * Sets the far clip of the Spotlight for texture projection.
  46592. */
  46593. set: function (value) {
  46594. this._projectionTextureLightFar = value;
  46595. this._projectionTextureProjectionLightDirty = true;
  46596. },
  46597. enumerable: true,
  46598. configurable: true
  46599. });
  46600. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46601. /**
  46602. * Gets the Up vector of the Spotlight for texture projection.
  46603. */
  46604. get: function () {
  46605. return this._projectionTextureUpDirection;
  46606. },
  46607. /**
  46608. * Sets the Up vector of the Spotlight for texture projection.
  46609. */
  46610. set: function (value) {
  46611. this._projectionTextureUpDirection = value;
  46612. this._projectionTextureProjectionLightDirty = true;
  46613. },
  46614. enumerable: true,
  46615. configurable: true
  46616. });
  46617. ;
  46618. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46619. /**
  46620. * Gets the projection texture of the light.
  46621. */
  46622. get: function () {
  46623. return this._projectionTexture;
  46624. },
  46625. /**
  46626. * Sets the projection texture of the light.
  46627. */
  46628. set: function (value) {
  46629. this._projectionTexture = value;
  46630. this._projectionTextureDirty = true;
  46631. },
  46632. enumerable: true,
  46633. configurable: true
  46634. });
  46635. /**
  46636. * Returns the string "SpotLight".
  46637. * @returns the class name
  46638. */
  46639. SpotLight.prototype.getClassName = function () {
  46640. return "SpotLight";
  46641. };
  46642. /**
  46643. * Returns the integer 2.
  46644. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46645. */
  46646. SpotLight.prototype.getTypeID = function () {
  46647. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46648. };
  46649. /**
  46650. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46651. */
  46652. SpotLight.prototype._setDirection = function (value) {
  46653. _super.prototype._setDirection.call(this, value);
  46654. this._projectionTextureViewLightDirty = true;
  46655. };
  46656. /**
  46657. * Overrides the position setter to recompute the projection texture view light Matrix.
  46658. */
  46659. SpotLight.prototype._setPosition = function (value) {
  46660. _super.prototype._setPosition.call(this, value);
  46661. this._projectionTextureViewLightDirty = true;
  46662. };
  46663. /**
  46664. * 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.
  46665. * Returns the SpotLight.
  46666. */
  46667. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46668. var activeCamera = this.getScene().activeCamera;
  46669. if (!activeCamera) {
  46670. return;
  46671. }
  46672. this._shadowAngleScale = this._shadowAngleScale || 1;
  46673. var angle = this._shadowAngleScale * this._angle;
  46674. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46675. };
  46676. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46677. this._projectionTextureViewLightDirty = false;
  46678. this._projectionTextureDirty = true;
  46679. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46680. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46681. };
  46682. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46683. this._projectionTextureProjectionLightDirty = false;
  46684. this._projectionTextureDirty = true;
  46685. var light_far = this.projectionTextureLightFar;
  46686. var light_near = this.projectionTextureLightNear;
  46687. var P = light_far / (light_far - light_near);
  46688. var Q = -P * light_near;
  46689. var S = 1.0 / Math.tan(this._angle / 2.0);
  46690. var A = 1.0;
  46691. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  46692. };
  46693. /**
  46694. * Main function for light texture projection matrix computing.
  46695. */
  46696. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46697. this._projectionTextureDirty = false;
  46698. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46699. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46700. };
  46701. SpotLight.prototype._buildUniformLayout = function () {
  46702. this._uniformBuffer.addUniform("vLightData", 4);
  46703. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46704. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46705. this._uniformBuffer.addUniform("vLightDirection", 3);
  46706. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46707. this._uniformBuffer.addUniform("depthValues", 2);
  46708. this._uniformBuffer.create();
  46709. };
  46710. /**
  46711. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46712. * @param effect The effect to update
  46713. * @param lightIndex The index of the light in the effect to update
  46714. * @returns The spot light
  46715. */
  46716. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46717. var normalizeDirection;
  46718. if (this.computeTransformedInformation()) {
  46719. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46720. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46721. }
  46722. else {
  46723. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46724. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46725. }
  46726. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46727. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46728. if (this._projectionTextureViewLightDirty) {
  46729. this._computeProjectionTextureViewLightMatrix();
  46730. }
  46731. if (this._projectionTextureProjectionLightDirty) {
  46732. this._computeProjectionTextureProjectionLightMatrix();
  46733. }
  46734. if (this._projectionTextureDirty) {
  46735. this._computeProjectionTextureMatrix();
  46736. }
  46737. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46738. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46739. }
  46740. return this;
  46741. };
  46742. /**
  46743. * Disposes the light and the associated resources.
  46744. */
  46745. SpotLight.prototype.dispose = function () {
  46746. _super.prototype.dispose.call(this);
  46747. if (this._projectionTexture) {
  46748. this._projectionTexture.dispose();
  46749. }
  46750. };
  46751. __decorate([
  46752. BABYLON.serialize()
  46753. ], SpotLight.prototype, "angle", null);
  46754. __decorate([
  46755. BABYLON.serialize()
  46756. ], SpotLight.prototype, "shadowAngleScale", null);
  46757. __decorate([
  46758. BABYLON.serialize()
  46759. ], SpotLight.prototype, "exponent", void 0);
  46760. __decorate([
  46761. BABYLON.serialize()
  46762. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46763. __decorate([
  46764. BABYLON.serialize()
  46765. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46766. __decorate([
  46767. BABYLON.serialize()
  46768. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46769. __decorate([
  46770. BABYLON.serializeAsTexture("projectedLightTexture")
  46771. ], SpotLight.prototype, "_projectionTexture", void 0);
  46772. return SpotLight;
  46773. }(BABYLON.ShadowLight));
  46774. BABYLON.SpotLight = SpotLight;
  46775. })(BABYLON || (BABYLON = {}));
  46776. //# sourceMappingURL=babylon.spotLight.js.map
  46777. "use strict";
  46778. var BABYLON;
  46779. (function (BABYLON) {
  46780. /**
  46781. * Class used to override all child animations of a given target
  46782. */
  46783. var AnimationPropertiesOverride = /** @class */ (function () {
  46784. function AnimationPropertiesOverride() {
  46785. /**
  46786. * Gets or sets a value indicating if animation blending must be used
  46787. */
  46788. this.enableBlending = false;
  46789. /**
  46790. * Gets or sets the blending speed to use when enableBlending is true
  46791. */
  46792. this.blendingSpeed = 0.01;
  46793. /**
  46794. * Gets or sets the default loop mode to use
  46795. */
  46796. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46797. }
  46798. return AnimationPropertiesOverride;
  46799. }());
  46800. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46801. })(BABYLON || (BABYLON = {}));
  46802. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46803. "use strict";
  46804. var BABYLON;
  46805. (function (BABYLON) {
  46806. var AnimationRange = /** @class */ (function () {
  46807. function AnimationRange(name, from, to) {
  46808. this.name = name;
  46809. this.from = from;
  46810. this.to = to;
  46811. }
  46812. AnimationRange.prototype.clone = function () {
  46813. return new AnimationRange(this.name, this.from, this.to);
  46814. };
  46815. return AnimationRange;
  46816. }());
  46817. BABYLON.AnimationRange = AnimationRange;
  46818. /**
  46819. * Composed of a frame, and an action function
  46820. */
  46821. var AnimationEvent = /** @class */ (function () {
  46822. function AnimationEvent(frame, action, onlyOnce) {
  46823. this.frame = frame;
  46824. this.action = action;
  46825. this.onlyOnce = onlyOnce;
  46826. this.isDone = false;
  46827. }
  46828. return AnimationEvent;
  46829. }());
  46830. BABYLON.AnimationEvent = AnimationEvent;
  46831. var PathCursor = /** @class */ (function () {
  46832. function PathCursor(path) {
  46833. this.path = path;
  46834. this._onchange = new Array();
  46835. this.value = 0;
  46836. this.animations = new Array();
  46837. }
  46838. PathCursor.prototype.getPoint = function () {
  46839. var point = this.path.getPointAtLengthPosition(this.value);
  46840. return new BABYLON.Vector3(point.x, 0, point.y);
  46841. };
  46842. PathCursor.prototype.moveAhead = function (step) {
  46843. if (step === void 0) { step = 0.002; }
  46844. this.move(step);
  46845. return this;
  46846. };
  46847. PathCursor.prototype.moveBack = function (step) {
  46848. if (step === void 0) { step = 0.002; }
  46849. this.move(-step);
  46850. return this;
  46851. };
  46852. PathCursor.prototype.move = function (step) {
  46853. if (Math.abs(step) > 1) {
  46854. throw "step size should be less than 1.";
  46855. }
  46856. this.value += step;
  46857. this.ensureLimits();
  46858. this.raiseOnChange();
  46859. return this;
  46860. };
  46861. PathCursor.prototype.ensureLimits = function () {
  46862. while (this.value > 1) {
  46863. this.value -= 1;
  46864. }
  46865. while (this.value < 0) {
  46866. this.value += 1;
  46867. }
  46868. return this;
  46869. };
  46870. // used by animation engine
  46871. PathCursor.prototype.raiseOnChange = function () {
  46872. var _this = this;
  46873. this._onchange.forEach(function (f) { return f(_this); });
  46874. return this;
  46875. };
  46876. PathCursor.prototype.onchange = function (f) {
  46877. this._onchange.push(f);
  46878. return this;
  46879. };
  46880. return PathCursor;
  46881. }());
  46882. BABYLON.PathCursor = PathCursor;
  46883. var AnimationKeyInterpolation;
  46884. (function (AnimationKeyInterpolation) {
  46885. /**
  46886. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46887. */
  46888. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46889. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46890. var Animation = /** @class */ (function () {
  46891. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46892. this.name = name;
  46893. this.targetProperty = targetProperty;
  46894. this.framePerSecond = framePerSecond;
  46895. this.dataType = dataType;
  46896. this.loopMode = loopMode;
  46897. this.enableBlending = enableBlending;
  46898. this._runtimeAnimations = new Array();
  46899. // The set of event that will be linked to this animation
  46900. this._events = new Array();
  46901. this.blendingSpeed = 0.01;
  46902. this._ranges = {};
  46903. this.targetPropertyPath = targetProperty.split(".");
  46904. this.dataType = dataType;
  46905. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46906. }
  46907. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46908. var dataType = undefined;
  46909. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46910. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46911. }
  46912. else if (from instanceof BABYLON.Quaternion) {
  46913. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46914. }
  46915. else if (from instanceof BABYLON.Vector3) {
  46916. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46917. }
  46918. else if (from instanceof BABYLON.Vector2) {
  46919. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46920. }
  46921. else if (from instanceof BABYLON.Color3) {
  46922. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46923. }
  46924. else if (from instanceof BABYLON.Size) {
  46925. dataType = Animation.ANIMATIONTYPE_SIZE;
  46926. }
  46927. if (dataType == undefined) {
  46928. return null;
  46929. }
  46930. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46931. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46932. animation.setKeys(keys);
  46933. if (easingFunction !== undefined) {
  46934. animation.setEasingFunction(easingFunction);
  46935. }
  46936. return animation;
  46937. };
  46938. /**
  46939. * Sets up an animation.
  46940. * @param property the property to animate
  46941. * @param animationType the animation type to apply
  46942. * @param easingFunction the easing function used in the animation
  46943. * @returns The created animation
  46944. */
  46945. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46946. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46947. animation.setEasingFunction(easingFunction);
  46948. return animation;
  46949. };
  46950. /**
  46951. * Create and start an animation on a node
  46952. * @param {string} name defines the name of the global animation that will be run on all nodes
  46953. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46954. * @param {string} targetProperty defines property to animate
  46955. * @param {number} framePerSecond defines the number of frame per second yo use
  46956. * @param {number} totalFrame defines the number of frames in total
  46957. * @param {any} from defines the initial value
  46958. * @param {any} to defines the final value
  46959. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46960. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46961. * @param onAnimationEnd defines the callback to call when animation end
  46962. * @returns the animatable created for this animation
  46963. */
  46964. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46965. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46966. if (!animation) {
  46967. return null;
  46968. }
  46969. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46970. };
  46971. /**
  46972. * Create and start an animation on a node and its descendants
  46973. * @param {string} name defines the name of the global animation that will be run on all nodes
  46974. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46975. * @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.
  46976. * @param {string} targetProperty defines property to animate
  46977. * @param {number} framePerSecond defines the number of frame per second yo use
  46978. * @param {number} totalFrame defines the number of frames in total
  46979. * @param {any} from defines the initial value
  46980. * @param {any} to defines the final value
  46981. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46982. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46983. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46984. * @returns the list of animatables created for all nodes
  46985. * @example https://www.babylonjs-playground.com/#MH0VLI
  46986. */
  46987. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46988. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46989. if (!animation) {
  46990. return null;
  46991. }
  46992. var scene = node.getScene();
  46993. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46994. };
  46995. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46996. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46997. if (!animation) {
  46998. return null;
  46999. }
  47000. node.animations.push(animation);
  47001. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47002. };
  47003. /**
  47004. * Transition property of the Camera to the target Value.
  47005. * @param property The property to transition
  47006. * @param targetValue The target Value of the property
  47007. * @param host The object where the property to animate belongs
  47008. * @param scene Scene used to run the animation
  47009. * @param frameRate Framerate (in frame/s) to use
  47010. * @param transition The transition type we want to use
  47011. * @param duration The duration of the animation, in milliseconds
  47012. * @param onAnimationEnd Call back trigger at the end of the animation.
  47013. */
  47014. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  47015. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  47016. if (duration <= 0) {
  47017. host[property] = targetValue;
  47018. if (onAnimationEnd) {
  47019. onAnimationEnd();
  47020. }
  47021. return null;
  47022. }
  47023. var endFrame = frameRate * (duration / 1000);
  47024. transition.setKeys([{
  47025. frame: 0,
  47026. value: host[property].clone ? host[property].clone() : host[property]
  47027. },
  47028. {
  47029. frame: endFrame,
  47030. value: targetValue
  47031. }]);
  47032. if (!host.animations) {
  47033. host.animations = [];
  47034. }
  47035. host.animations.push(transition);
  47036. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47037. animation.onAnimationEnd = onAnimationEnd;
  47038. return animation;
  47039. };
  47040. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47041. /**
  47042. * Return the array of runtime animations currently using this animation
  47043. */
  47044. get: function () {
  47045. return this._runtimeAnimations;
  47046. },
  47047. enumerable: true,
  47048. configurable: true
  47049. });
  47050. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47051. get: function () {
  47052. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47053. var runtimeAnimation = _a[_i];
  47054. if (!runtimeAnimation.isStopped) {
  47055. return true;
  47056. }
  47057. }
  47058. return false;
  47059. },
  47060. enumerable: true,
  47061. configurable: true
  47062. });
  47063. // Methods
  47064. /**
  47065. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47066. */
  47067. Animation.prototype.toString = function (fullDetails) {
  47068. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47069. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47070. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47071. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47072. if (fullDetails) {
  47073. ret += ", Ranges: {";
  47074. var first = true;
  47075. for (var name in this._ranges) {
  47076. if (first) {
  47077. ret += ", ";
  47078. first = false;
  47079. }
  47080. ret += name;
  47081. }
  47082. ret += "}";
  47083. }
  47084. return ret;
  47085. };
  47086. /**
  47087. * Add an event to this animation.
  47088. */
  47089. Animation.prototype.addEvent = function (event) {
  47090. this._events.push(event);
  47091. };
  47092. /**
  47093. * Remove all events found at the given frame
  47094. * @param frame
  47095. */
  47096. Animation.prototype.removeEvents = function (frame) {
  47097. for (var index = 0; index < this._events.length; index++) {
  47098. if (this._events[index].frame === frame) {
  47099. this._events.splice(index, 1);
  47100. index--;
  47101. }
  47102. }
  47103. };
  47104. Animation.prototype.getEvents = function () {
  47105. return this._events;
  47106. };
  47107. Animation.prototype.createRange = function (name, from, to) {
  47108. // check name not already in use; could happen for bones after serialized
  47109. if (!this._ranges[name]) {
  47110. this._ranges[name] = new AnimationRange(name, from, to);
  47111. }
  47112. };
  47113. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47114. if (deleteFrames === void 0) { deleteFrames = true; }
  47115. var range = this._ranges[name];
  47116. if (!range) {
  47117. return;
  47118. }
  47119. if (deleteFrames) {
  47120. var from = range.from;
  47121. var to = range.to;
  47122. // this loop MUST go high to low for multiple splices to work
  47123. for (var key = this._keys.length - 1; key >= 0; key--) {
  47124. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47125. this._keys.splice(key, 1);
  47126. }
  47127. }
  47128. }
  47129. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47130. };
  47131. Animation.prototype.getRange = function (name) {
  47132. return this._ranges[name];
  47133. };
  47134. Animation.prototype.getKeys = function () {
  47135. return this._keys;
  47136. };
  47137. Animation.prototype.getHighestFrame = function () {
  47138. var ret = 0;
  47139. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47140. if (ret < this._keys[key].frame) {
  47141. ret = this._keys[key].frame;
  47142. }
  47143. }
  47144. return ret;
  47145. };
  47146. Animation.prototype.getEasingFunction = function () {
  47147. return this._easingFunction;
  47148. };
  47149. Animation.prototype.setEasingFunction = function (easingFunction) {
  47150. this._easingFunction = easingFunction;
  47151. };
  47152. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47153. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47154. };
  47155. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47156. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47157. };
  47158. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47159. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47160. };
  47161. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47162. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47163. };
  47164. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47165. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47166. };
  47167. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47168. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47169. };
  47170. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47171. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47172. };
  47173. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47174. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47175. };
  47176. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47177. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47178. };
  47179. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47180. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47181. };
  47182. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47183. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47184. };
  47185. Animation.prototype.clone = function () {
  47186. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47187. clone.enableBlending = this.enableBlending;
  47188. clone.blendingSpeed = this.blendingSpeed;
  47189. if (this._keys) {
  47190. clone.setKeys(this._keys);
  47191. }
  47192. if (this._ranges) {
  47193. clone._ranges = {};
  47194. for (var name in this._ranges) {
  47195. var range = this._ranges[name];
  47196. if (!range) {
  47197. continue;
  47198. }
  47199. clone._ranges[name] = range.clone();
  47200. }
  47201. }
  47202. return clone;
  47203. };
  47204. Animation.prototype.setKeys = function (values) {
  47205. this._keys = values.slice(0);
  47206. };
  47207. Animation.prototype.serialize = function () {
  47208. var serializationObject = {};
  47209. serializationObject.name = this.name;
  47210. serializationObject.property = this.targetProperty;
  47211. serializationObject.framePerSecond = this.framePerSecond;
  47212. serializationObject.dataType = this.dataType;
  47213. serializationObject.loopBehavior = this.loopMode;
  47214. serializationObject.enableBlending = this.enableBlending;
  47215. serializationObject.blendingSpeed = this.blendingSpeed;
  47216. var dataType = this.dataType;
  47217. serializationObject.keys = [];
  47218. var keys = this.getKeys();
  47219. for (var index = 0; index < keys.length; index++) {
  47220. var animationKey = keys[index];
  47221. var key = {};
  47222. key.frame = animationKey.frame;
  47223. switch (dataType) {
  47224. case Animation.ANIMATIONTYPE_FLOAT:
  47225. key.values = [animationKey.value];
  47226. break;
  47227. case Animation.ANIMATIONTYPE_QUATERNION:
  47228. case Animation.ANIMATIONTYPE_MATRIX:
  47229. case Animation.ANIMATIONTYPE_VECTOR3:
  47230. case Animation.ANIMATIONTYPE_COLOR3:
  47231. key.values = animationKey.value.asArray();
  47232. break;
  47233. }
  47234. serializationObject.keys.push(key);
  47235. }
  47236. serializationObject.ranges = [];
  47237. for (var name in this._ranges) {
  47238. var source = this._ranges[name];
  47239. if (!source) {
  47240. continue;
  47241. }
  47242. var range = {};
  47243. range.name = name;
  47244. range.from = source.from;
  47245. range.to = source.to;
  47246. serializationObject.ranges.push(range);
  47247. }
  47248. return serializationObject;
  47249. };
  47250. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47251. get: function () {
  47252. return Animation._ANIMATIONTYPE_FLOAT;
  47253. },
  47254. enumerable: true,
  47255. configurable: true
  47256. });
  47257. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47258. get: function () {
  47259. return Animation._ANIMATIONTYPE_VECTOR3;
  47260. },
  47261. enumerable: true,
  47262. configurable: true
  47263. });
  47264. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47265. get: function () {
  47266. return Animation._ANIMATIONTYPE_VECTOR2;
  47267. },
  47268. enumerable: true,
  47269. configurable: true
  47270. });
  47271. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47272. get: function () {
  47273. return Animation._ANIMATIONTYPE_SIZE;
  47274. },
  47275. enumerable: true,
  47276. configurable: true
  47277. });
  47278. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47279. get: function () {
  47280. return Animation._ANIMATIONTYPE_QUATERNION;
  47281. },
  47282. enumerable: true,
  47283. configurable: true
  47284. });
  47285. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47286. get: function () {
  47287. return Animation._ANIMATIONTYPE_MATRIX;
  47288. },
  47289. enumerable: true,
  47290. configurable: true
  47291. });
  47292. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47293. get: function () {
  47294. return Animation._ANIMATIONTYPE_COLOR3;
  47295. },
  47296. enumerable: true,
  47297. configurable: true
  47298. });
  47299. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47300. get: function () {
  47301. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47302. },
  47303. enumerable: true,
  47304. configurable: true
  47305. });
  47306. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47307. get: function () {
  47308. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47309. },
  47310. enumerable: true,
  47311. configurable: true
  47312. });
  47313. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47314. get: function () {
  47315. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47316. },
  47317. enumerable: true,
  47318. configurable: true
  47319. });
  47320. Animation.Parse = function (parsedAnimation) {
  47321. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47322. var dataType = parsedAnimation.dataType;
  47323. var keys = [];
  47324. var data;
  47325. var index;
  47326. if (parsedAnimation.enableBlending) {
  47327. animation.enableBlending = parsedAnimation.enableBlending;
  47328. }
  47329. if (parsedAnimation.blendingSpeed) {
  47330. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47331. }
  47332. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47333. var key = parsedAnimation.keys[index];
  47334. var inTangent;
  47335. var outTangent;
  47336. switch (dataType) {
  47337. case Animation.ANIMATIONTYPE_FLOAT:
  47338. data = key.values[0];
  47339. if (key.values.length >= 1) {
  47340. inTangent = key.values[1];
  47341. }
  47342. if (key.values.length >= 2) {
  47343. outTangent = key.values[2];
  47344. }
  47345. break;
  47346. case Animation.ANIMATIONTYPE_QUATERNION:
  47347. data = BABYLON.Quaternion.FromArray(key.values);
  47348. if (key.values.length >= 8) {
  47349. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47350. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47351. inTangent = _inTangent;
  47352. }
  47353. }
  47354. if (key.values.length >= 12) {
  47355. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47356. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47357. outTangent = _outTangent;
  47358. }
  47359. }
  47360. break;
  47361. case Animation.ANIMATIONTYPE_MATRIX:
  47362. data = BABYLON.Matrix.FromArray(key.values);
  47363. break;
  47364. case Animation.ANIMATIONTYPE_COLOR3:
  47365. data = BABYLON.Color3.FromArray(key.values);
  47366. break;
  47367. case Animation.ANIMATIONTYPE_VECTOR3:
  47368. default:
  47369. data = BABYLON.Vector3.FromArray(key.values);
  47370. break;
  47371. }
  47372. var keyData = {};
  47373. keyData.frame = key.frame;
  47374. keyData.value = data;
  47375. if (inTangent != undefined) {
  47376. keyData.inTangent = inTangent;
  47377. }
  47378. if (outTangent != undefined) {
  47379. keyData.outTangent = outTangent;
  47380. }
  47381. keys.push(keyData);
  47382. }
  47383. animation.setKeys(keys);
  47384. if (parsedAnimation.ranges) {
  47385. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47386. data = parsedAnimation.ranges[index];
  47387. animation.createRange(data.name, data.from, data.to);
  47388. }
  47389. }
  47390. return animation;
  47391. };
  47392. Animation.AppendSerializedAnimations = function (source, destination) {
  47393. if (source.animations) {
  47394. destination.animations = [];
  47395. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47396. var animation = source.animations[animationIndex];
  47397. destination.animations.push(animation.serialize());
  47398. }
  47399. }
  47400. };
  47401. Animation.AllowMatricesInterpolation = false;
  47402. // Statics
  47403. Animation._ANIMATIONTYPE_FLOAT = 0;
  47404. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47405. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47406. Animation._ANIMATIONTYPE_MATRIX = 3;
  47407. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47408. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47409. Animation._ANIMATIONTYPE_SIZE = 6;
  47410. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47411. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47412. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47413. return Animation;
  47414. }());
  47415. BABYLON.Animation = Animation;
  47416. })(BABYLON || (BABYLON = {}));
  47417. //# sourceMappingURL=babylon.animation.js.map
  47418. "use strict";
  47419. var BABYLON;
  47420. (function (BABYLON) {
  47421. /**
  47422. * This class defines the direct association between an animation and a target
  47423. */
  47424. var TargetedAnimation = /** @class */ (function () {
  47425. function TargetedAnimation() {
  47426. }
  47427. return TargetedAnimation;
  47428. }());
  47429. BABYLON.TargetedAnimation = TargetedAnimation;
  47430. /**
  47431. * Use this class to create coordinated animations on multiple targets
  47432. */
  47433. var AnimationGroup = /** @class */ (function () {
  47434. function AnimationGroup(name, scene) {
  47435. if (scene === void 0) { scene = null; }
  47436. this.name = name;
  47437. this._targetedAnimations = new Array();
  47438. this._animatables = new Array();
  47439. this._from = Number.MAX_VALUE;
  47440. this._to = -Number.MAX_VALUE;
  47441. this._speedRatio = 1;
  47442. this.onAnimationEndObservable = new BABYLON.Observable();
  47443. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47444. this._scene.animationGroups.push(this);
  47445. }
  47446. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47447. /**
  47448. * Define if the animations are started
  47449. */
  47450. get: function () {
  47451. return this._isStarted;
  47452. },
  47453. enumerable: true,
  47454. configurable: true
  47455. });
  47456. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47457. /**
  47458. * Gets or sets the speed ratio to use for all animations
  47459. */
  47460. get: function () {
  47461. return this._speedRatio;
  47462. },
  47463. /**
  47464. * Gets or sets the speed ratio to use for all animations
  47465. */
  47466. set: function (value) {
  47467. if (this._speedRatio === value) {
  47468. return;
  47469. }
  47470. this._speedRatio = value;
  47471. for (var index = 0; index < this._animatables.length; index++) {
  47472. var animatable = this._animatables[index];
  47473. animatable.speedRatio = this._speedRatio;
  47474. }
  47475. },
  47476. enumerable: true,
  47477. configurable: true
  47478. });
  47479. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47480. /**
  47481. * Gets the targeted animations for this animation group
  47482. */
  47483. get: function () {
  47484. return this._targetedAnimations;
  47485. },
  47486. enumerable: true,
  47487. configurable: true
  47488. });
  47489. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47490. /**
  47491. * returning the list of animatables controlled by this animation group.
  47492. */
  47493. get: function () {
  47494. return this._animatables;
  47495. },
  47496. enumerable: true,
  47497. configurable: true
  47498. });
  47499. /**
  47500. * Add an animation (with its target) in the group
  47501. * @param animation defines the animation we want to add
  47502. * @param target defines the target of the animation
  47503. * @returns the {BABYLON.TargetedAnimation} object
  47504. */
  47505. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47506. var targetedAnimation = {
  47507. animation: animation,
  47508. target: target
  47509. };
  47510. var keys = animation.getKeys();
  47511. if (this._from > keys[0].frame) {
  47512. this._from = keys[0].frame;
  47513. }
  47514. if (this._to < keys[keys.length - 1].frame) {
  47515. this._to = keys[keys.length - 1].frame;
  47516. }
  47517. this._targetedAnimations.push(targetedAnimation);
  47518. return targetedAnimation;
  47519. };
  47520. /**
  47521. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47522. * It can add constant keys at begin or end
  47523. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47524. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47525. */
  47526. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47527. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47528. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47529. beginFrame = Math.max(beginFrame, this._from);
  47530. endFrame = Math.min(endFrame, this._to);
  47531. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47532. var targetedAnimation = this._targetedAnimations[index];
  47533. var keys = targetedAnimation.animation.getKeys();
  47534. var startKey = keys[0];
  47535. var endKey = keys[keys.length - 1];
  47536. if (startKey.frame > beginFrame) {
  47537. var newKey = {
  47538. frame: beginFrame,
  47539. value: startKey.value,
  47540. inTangent: startKey.inTangent,
  47541. outTangent: startKey.outTangent,
  47542. interpolation: startKey.interpolation
  47543. };
  47544. keys.splice(0, 0, newKey);
  47545. }
  47546. if (endKey.frame < endFrame) {
  47547. var newKey = {
  47548. frame: endFrame,
  47549. value: endKey.value,
  47550. inTangent: endKey.outTangent,
  47551. outTangent: endKey.outTangent,
  47552. interpolation: endKey.interpolation
  47553. };
  47554. keys.push(newKey);
  47555. }
  47556. }
  47557. return this;
  47558. };
  47559. /**
  47560. * Start all animations on given targets
  47561. * @param loop defines if animations must loop
  47562. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47563. * @param from defines the from key (optional)
  47564. * @param to defines the to key (optional)
  47565. * @returns the current animation group
  47566. */
  47567. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  47568. var _this = this;
  47569. if (loop === void 0) { loop = false; }
  47570. if (speedRatio === void 0) { speedRatio = 1; }
  47571. if (this._isStarted || this._targetedAnimations.length === 0) {
  47572. return this;
  47573. }
  47574. var _loop_1 = function () {
  47575. var targetedAnimation = this_1._targetedAnimations[index];
  47576. if (!targetedAnimation.target.animations) {
  47577. targetedAnimation.target.animations = [];
  47578. }
  47579. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  47580. targetedAnimation.target.animations.push(targetedAnimation.animation);
  47581. }
  47582. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  47583. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47584. }));
  47585. };
  47586. var this_1 = this;
  47587. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47588. _loop_1();
  47589. }
  47590. this._speedRatio = speedRatio;
  47591. this._isStarted = true;
  47592. return this;
  47593. };
  47594. /**
  47595. * Pause all animations
  47596. */
  47597. AnimationGroup.prototype.pause = function () {
  47598. if (!this._isStarted) {
  47599. return this;
  47600. }
  47601. for (var index = 0; index < this._animatables.length; index++) {
  47602. var animatable = this._animatables[index];
  47603. animatable.pause();
  47604. }
  47605. return this;
  47606. };
  47607. /**
  47608. * Play all animations to initial state
  47609. * This function will start() the animations if they were not started or will restart() them if they were paused
  47610. * @param loop defines if animations must loop
  47611. */
  47612. AnimationGroup.prototype.play = function (loop) {
  47613. if (this.isStarted) {
  47614. if (loop !== undefined) {
  47615. for (var index = 0; index < this._animatables.length; index++) {
  47616. var animatable = this._animatables[index];
  47617. animatable.loopAnimation = loop;
  47618. }
  47619. }
  47620. this.restart();
  47621. }
  47622. else {
  47623. this.start(loop, this._speedRatio);
  47624. }
  47625. return this;
  47626. };
  47627. /**
  47628. * Reset all animations to initial state
  47629. */
  47630. AnimationGroup.prototype.reset = function () {
  47631. if (!this._isStarted) {
  47632. return this;
  47633. }
  47634. for (var index = 0; index < this._animatables.length; index++) {
  47635. var animatable = this._animatables[index];
  47636. animatable.reset();
  47637. }
  47638. return this;
  47639. };
  47640. /**
  47641. * Restart animations from key 0
  47642. */
  47643. AnimationGroup.prototype.restart = function () {
  47644. if (!this._isStarted) {
  47645. return this;
  47646. }
  47647. for (var index = 0; index < this._animatables.length; index++) {
  47648. var animatable = this._animatables[index];
  47649. animatable.restart();
  47650. }
  47651. return this;
  47652. };
  47653. /**
  47654. * Stop all animations
  47655. */
  47656. AnimationGroup.prototype.stop = function () {
  47657. if (!this._isStarted) {
  47658. return this;
  47659. }
  47660. for (var index = 0; index < this._animatables.length; index++) {
  47661. var animatable = this._animatables[index];
  47662. animatable.stop();
  47663. }
  47664. this._isStarted = false;
  47665. return this;
  47666. };
  47667. /**
  47668. * Goes to a specific frame in this animation group
  47669. *
  47670. * @param frame the frame number to go to
  47671. * @return the animationGroup
  47672. */
  47673. AnimationGroup.prototype.goToFrame = function (frame) {
  47674. if (!this._isStarted) {
  47675. return this;
  47676. }
  47677. for (var index = 0; index < this._animatables.length; index++) {
  47678. var animatable = this._animatables[index];
  47679. animatable.goToFrame(frame);
  47680. }
  47681. return this;
  47682. };
  47683. /**
  47684. * Dispose all associated resources
  47685. */
  47686. AnimationGroup.prototype.dispose = function () {
  47687. this._targetedAnimations = [];
  47688. this._animatables = [];
  47689. var index = this._scene.animationGroups.indexOf(this);
  47690. if (index > -1) {
  47691. this._scene.animationGroups.splice(index, 1);
  47692. }
  47693. };
  47694. return AnimationGroup;
  47695. }());
  47696. BABYLON.AnimationGroup = AnimationGroup;
  47697. })(BABYLON || (BABYLON = {}));
  47698. //# sourceMappingURL=babylon.animationGroup.js.map
  47699. "use strict";
  47700. var BABYLON;
  47701. (function (BABYLON) {
  47702. var RuntimeAnimation = /** @class */ (function () {
  47703. /**
  47704. * Create a new RuntimeAnimation object
  47705. * @param target defines the target of the animation
  47706. * @param animation defines the source {BABYLON.Animation} object
  47707. * @param scene defines the hosting scene
  47708. * @param host defines the initiating Animatable
  47709. */
  47710. function RuntimeAnimation(target, animation, scene, host) {
  47711. this._currentFrame = 0;
  47712. this._offsetsCache = {};
  47713. this._highLimitsCache = {};
  47714. this._stopped = false;
  47715. this._blendingFactor = 0;
  47716. this._targetPath = "";
  47717. this._weight = 1.0;
  47718. this._ratioOffset = 0;
  47719. this._previousDelay = 0;
  47720. this._previousRatio = 0;
  47721. this._animation = animation;
  47722. this._target = target;
  47723. this._scene = scene;
  47724. this._host = host;
  47725. animation._runtimeAnimations.push(this);
  47726. }
  47727. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  47728. /**
  47729. * Gets the current frame
  47730. */
  47731. get: function () {
  47732. return this._currentFrame;
  47733. },
  47734. enumerable: true,
  47735. configurable: true
  47736. });
  47737. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47738. /**
  47739. * Gets the weight of the runtime animation
  47740. */
  47741. get: function () {
  47742. return this._weight;
  47743. },
  47744. enumerable: true,
  47745. configurable: true
  47746. });
  47747. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47748. /**
  47749. * Gets the original value of the runtime animation
  47750. */
  47751. get: function () {
  47752. return this._originalValue;
  47753. },
  47754. enumerable: true,
  47755. configurable: true
  47756. });
  47757. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47758. /**
  47759. * Gets the current value of the runtime animation
  47760. */
  47761. get: function () {
  47762. return this._currentValue;
  47763. },
  47764. enumerable: true,
  47765. configurable: true
  47766. });
  47767. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47768. /**
  47769. * Gets the path where to store the animated value in the target
  47770. */
  47771. get: function () {
  47772. return this._targetPath;
  47773. },
  47774. enumerable: true,
  47775. configurable: true
  47776. });
  47777. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47778. /**
  47779. * Gets the actual target of the runtime animation
  47780. */
  47781. get: function () {
  47782. return this._activeTarget;
  47783. },
  47784. enumerable: true,
  47785. configurable: true
  47786. });
  47787. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47788. get: function () {
  47789. return this._animation;
  47790. },
  47791. enumerable: true,
  47792. configurable: true
  47793. });
  47794. RuntimeAnimation.prototype.reset = function () {
  47795. this._offsetsCache = {};
  47796. this._highLimitsCache = {};
  47797. this._currentFrame = 0;
  47798. this._blendingFactor = 0;
  47799. this._originalValue = null;
  47800. };
  47801. RuntimeAnimation.prototype.isStopped = function () {
  47802. return this._stopped;
  47803. };
  47804. RuntimeAnimation.prototype.dispose = function () {
  47805. var index = this._animation.runtimeAnimations.indexOf(this);
  47806. if (index > -1) {
  47807. this._animation.runtimeAnimations.splice(index, 1);
  47808. }
  47809. };
  47810. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47811. if (typeof value === "function") {
  47812. return value();
  47813. }
  47814. return value;
  47815. };
  47816. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47817. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47818. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47819. }
  47820. this._currentFrame = currentFrame;
  47821. var keys = this._animation.getKeys();
  47822. // Try to get a hash to find the right key
  47823. 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));
  47824. if (keys[startKeyIndex].frame >= currentFrame) {
  47825. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47826. startKeyIndex--;
  47827. }
  47828. }
  47829. for (var key = startKeyIndex; key < keys.length; key++) {
  47830. var endKey = keys[key + 1];
  47831. if (endKey.frame >= currentFrame) {
  47832. var startKey = keys[key];
  47833. var startValue = this._getKeyValue(startKey.value);
  47834. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47835. return startValue;
  47836. }
  47837. var endValue = this._getKeyValue(endKey.value);
  47838. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47839. var frameDelta = endKey.frame - startKey.frame;
  47840. // gradient : percent of currentFrame between the frame inf and the frame sup
  47841. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47842. // check for easingFunction and correction of gradient
  47843. var easingFunction = this._animation.getEasingFunction();
  47844. if (easingFunction != null) {
  47845. gradient = easingFunction.ease(gradient);
  47846. }
  47847. switch (this._animation.dataType) {
  47848. // Float
  47849. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47850. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47851. switch (loopMode) {
  47852. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47853. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47854. return floatValue;
  47855. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47856. return offsetValue * repeatCount + floatValue;
  47857. }
  47858. break;
  47859. // Quaternion
  47860. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47861. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47862. switch (loopMode) {
  47863. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47864. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47865. return quatValue;
  47866. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47867. return quatValue.add(offsetValue.scale(repeatCount));
  47868. }
  47869. return quatValue;
  47870. // Vector3
  47871. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47872. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47873. switch (loopMode) {
  47874. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47875. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47876. return vec3Value;
  47877. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47878. return vec3Value.add(offsetValue.scale(repeatCount));
  47879. }
  47880. // Vector2
  47881. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47882. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47883. switch (loopMode) {
  47884. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47885. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47886. return vec2Value;
  47887. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47888. return vec2Value.add(offsetValue.scale(repeatCount));
  47889. }
  47890. // Size
  47891. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47892. switch (loopMode) {
  47893. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47894. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47895. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47896. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47897. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47898. }
  47899. // Color3
  47900. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47901. switch (loopMode) {
  47902. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47903. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47904. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47905. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47906. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47907. }
  47908. // Matrix
  47909. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47910. switch (loopMode) {
  47911. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47912. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47913. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47914. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47915. }
  47916. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47917. return startValue;
  47918. }
  47919. default:
  47920. break;
  47921. }
  47922. break;
  47923. }
  47924. }
  47925. return this._getKeyValue(keys[keys.length - 1].value);
  47926. };
  47927. /**
  47928. * Affect the interpolated value to the target
  47929. * @param currentValue defines the value computed by the animation
  47930. * @param weight defines the weight to apply to this value
  47931. */
  47932. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47933. if (weight === void 0) { weight = 1.0; }
  47934. // Set value
  47935. var path;
  47936. var destination;
  47937. var targetPropertyPath = this._animation.targetPropertyPath;
  47938. if (targetPropertyPath.length > 1) {
  47939. var property = this._target[targetPropertyPath[0]];
  47940. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47941. property = property[targetPropertyPath[index]];
  47942. }
  47943. path = targetPropertyPath[targetPropertyPath.length - 1];
  47944. destination = property;
  47945. }
  47946. else {
  47947. path = targetPropertyPath[0];
  47948. destination = this._target;
  47949. }
  47950. this._targetPath = path;
  47951. this._activeTarget = destination;
  47952. this._weight = weight;
  47953. // Blending
  47954. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47955. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47956. if (enableBlending && this._blendingFactor <= 1.0) {
  47957. if (!this._originalBlendValue) {
  47958. var originalValue = destination[path];
  47959. if (originalValue.clone) {
  47960. this._originalBlendValue = originalValue.clone();
  47961. }
  47962. else {
  47963. this._originalBlendValue = originalValue;
  47964. }
  47965. }
  47966. }
  47967. if (weight !== -1.0) {
  47968. if (!this._originalValue) {
  47969. var originalValue = void 0;
  47970. if (destination.getRestPose) {
  47971. originalValue = destination.getRestPose();
  47972. }
  47973. else {
  47974. originalValue = destination[path];
  47975. }
  47976. if (originalValue.clone) {
  47977. this._originalValue = originalValue.clone();
  47978. }
  47979. else {
  47980. this._originalValue = originalValue;
  47981. }
  47982. }
  47983. }
  47984. if (enableBlending && this._blendingFactor <= 1.0) {
  47985. if (this._originalBlendValue.prototype) {
  47986. if (this._originalBlendValue.prototype.Lerp) {
  47987. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47988. }
  47989. else {
  47990. this._currentValue = currentValue;
  47991. }
  47992. }
  47993. else if (this._originalBlendValue.m) {
  47994. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47995. }
  47996. else {
  47997. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47998. }
  47999. this._blendingFactor += blendingSpeed;
  48000. }
  48001. else {
  48002. this._currentValue = currentValue;
  48003. }
  48004. if (weight !== -1.0) {
  48005. this._scene._registerTargetForLateAnimationBinding(this);
  48006. }
  48007. else {
  48008. destination[path] = this._currentValue;
  48009. }
  48010. if (this._target.markAsDirty) {
  48011. this._target.markAsDirty(this._animation.targetProperty);
  48012. }
  48013. };
  48014. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  48015. if (this._target && this._target.animationPropertiesOverride) {
  48016. return this._target.animationPropertiesOverride.loopMode;
  48017. }
  48018. return this._animation.loopMode;
  48019. };
  48020. /**
  48021. * Move the current animation to a given frame
  48022. * @param frame defines the frame to move to
  48023. */
  48024. RuntimeAnimation.prototype.goToFrame = function (frame) {
  48025. var keys = this._animation.getKeys();
  48026. if (frame < keys[0].frame) {
  48027. frame = keys[0].frame;
  48028. }
  48029. else if (frame > keys[keys.length - 1].frame) {
  48030. frame = keys[keys.length - 1].frame;
  48031. }
  48032. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  48033. this.setValue(currentValue, -1);
  48034. };
  48035. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  48036. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  48037. this._ratioOffset = this._previousRatio - newRatio;
  48038. };
  48039. /**
  48040. * Execute the current animation
  48041. * @param delay defines the delay to add to the current frame
  48042. * @param from defines the lower bound of the animation range
  48043. * @param to defines the upper bound of the animation range
  48044. * @param loop defines if the current animation must loop
  48045. * @param speedRatio defines the current speed ratio
  48046. * @param weight defines the weight of the animation (default is -1 so no weight)
  48047. * @returns a boolean indicating if the animation has ended
  48048. */
  48049. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48050. if (weight === void 0) { weight = -1.0; }
  48051. var targetPropertyPath = this._animation.targetPropertyPath;
  48052. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48053. this._stopped = true;
  48054. return false;
  48055. }
  48056. var returnValue = true;
  48057. var keys = this._animation.getKeys();
  48058. // Adding a start key at frame 0 if missing
  48059. if (keys[0].frame !== 0) {
  48060. var newKey = { frame: 0, value: keys[0].value };
  48061. keys.splice(0, 0, newKey);
  48062. }
  48063. // Check limits
  48064. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48065. from = keys[0].frame;
  48066. }
  48067. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48068. to = keys[keys.length - 1].frame;
  48069. }
  48070. //to and from cannot be the same key
  48071. if (from === to) {
  48072. if (from > keys[0].frame) {
  48073. from--;
  48074. }
  48075. else if (to < keys[keys.length - 1].frame) {
  48076. to++;
  48077. }
  48078. }
  48079. // Compute ratio
  48080. var range = to - from;
  48081. var offsetValue;
  48082. // ratio represents the frame delta between from and to
  48083. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48084. var highLimitValue = 0;
  48085. this._previousDelay = delay;
  48086. this._previousRatio = ratio;
  48087. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48088. returnValue = false;
  48089. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48090. }
  48091. else {
  48092. // Get max value if required
  48093. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48094. var keyOffset = to.toString() + from.toString();
  48095. if (!this._offsetsCache[keyOffset]) {
  48096. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48097. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48098. switch (this._animation.dataType) {
  48099. // Float
  48100. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48101. this._offsetsCache[keyOffset] = toValue - fromValue;
  48102. break;
  48103. // Quaternion
  48104. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48105. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48106. break;
  48107. // Vector3
  48108. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48109. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48110. // Vector2
  48111. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48112. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48113. // Size
  48114. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48115. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48116. // Color3
  48117. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48118. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48119. default:
  48120. break;
  48121. }
  48122. this._highLimitsCache[keyOffset] = toValue;
  48123. }
  48124. highLimitValue = this._highLimitsCache[keyOffset];
  48125. offsetValue = this._offsetsCache[keyOffset];
  48126. }
  48127. }
  48128. if (offsetValue === undefined) {
  48129. switch (this._animation.dataType) {
  48130. // Float
  48131. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48132. offsetValue = 0;
  48133. break;
  48134. // Quaternion
  48135. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48136. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48137. break;
  48138. // Vector3
  48139. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48140. offsetValue = BABYLON.Vector3.Zero();
  48141. break;
  48142. // Vector2
  48143. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48144. offsetValue = BABYLON.Vector2.Zero();
  48145. break;
  48146. // Size
  48147. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48148. offsetValue = BABYLON.Size.Zero();
  48149. break;
  48150. // Color3
  48151. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48152. offsetValue = BABYLON.Color3.Black();
  48153. }
  48154. }
  48155. // Compute value
  48156. var repeatCount = (ratio / range) >> 0;
  48157. var currentFrame = returnValue ? from + ratio % range : to;
  48158. // Need to normalize?
  48159. if (this._host && this._host.syncRoot) {
  48160. var syncRoot = this._host.syncRoot;
  48161. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  48162. currentFrame = from + (to - from) * hostNormalizedFrame;
  48163. }
  48164. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48165. // Set value
  48166. this.setValue(currentValue, weight);
  48167. // Check events
  48168. var events = this._animation.getEvents();
  48169. for (var index = 0; index < events.length; index++) {
  48170. // Make sure current frame has passed event frame and that event frame is within the current range
  48171. // Also, handle both forward and reverse animations
  48172. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48173. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48174. var event = events[index];
  48175. if (!event.isDone) {
  48176. // If event should be done only once, remove it.
  48177. if (event.onlyOnce) {
  48178. events.splice(index, 1);
  48179. index--;
  48180. }
  48181. event.isDone = true;
  48182. event.action();
  48183. } // Don't do anything if the event has already be done.
  48184. }
  48185. else if (events[index].isDone && !events[index].onlyOnce) {
  48186. // reset event, the animation is looping
  48187. events[index].isDone = false;
  48188. }
  48189. }
  48190. if (!returnValue) {
  48191. this._stopped = true;
  48192. }
  48193. return returnValue;
  48194. };
  48195. return RuntimeAnimation;
  48196. }());
  48197. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48198. })(BABYLON || (BABYLON = {}));
  48199. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48200. "use strict";
  48201. var BABYLON;
  48202. (function (BABYLON) {
  48203. var Animatable = /** @class */ (function () {
  48204. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48205. if (fromFrame === void 0) { fromFrame = 0; }
  48206. if (toFrame === void 0) { toFrame = 100; }
  48207. if (loopAnimation === void 0) { loopAnimation = false; }
  48208. if (speedRatio === void 0) { speedRatio = 1.0; }
  48209. this.target = target;
  48210. this.fromFrame = fromFrame;
  48211. this.toFrame = toFrame;
  48212. this.loopAnimation = loopAnimation;
  48213. this.onAnimationEnd = onAnimationEnd;
  48214. this._localDelayOffset = null;
  48215. this._pausedDelay = null;
  48216. this._runtimeAnimations = new Array();
  48217. this._paused = false;
  48218. this._speedRatio = 1;
  48219. this._weight = -1.0;
  48220. this.animationStarted = false;
  48221. if (animations) {
  48222. this.appendAnimations(target, animations);
  48223. }
  48224. this._speedRatio = speedRatio;
  48225. this._scene = scene;
  48226. scene._activeAnimatables.push(this);
  48227. }
  48228. Object.defineProperty(Animatable.prototype, "syncRoot", {
  48229. /**
  48230. * Gets the root Animatable used to synchronize and normalize animations
  48231. */
  48232. get: function () {
  48233. return this._syncRoot;
  48234. },
  48235. enumerable: true,
  48236. configurable: true
  48237. });
  48238. Object.defineProperty(Animatable.prototype, "masterFrame", {
  48239. /**
  48240. * Gets the current frame of the first RuntimeAnimation
  48241. * Used to synchronize Animatables
  48242. */
  48243. get: function () {
  48244. if (this._runtimeAnimations.length === 0) {
  48245. return 0;
  48246. }
  48247. return this._runtimeAnimations[0].currentFrame;
  48248. },
  48249. enumerable: true,
  48250. configurable: true
  48251. });
  48252. Object.defineProperty(Animatable.prototype, "weight", {
  48253. /**
  48254. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48255. */
  48256. get: function () {
  48257. return this._weight;
  48258. },
  48259. set: function (value) {
  48260. if (value === -1) {
  48261. this._weight = -1;
  48262. return;
  48263. }
  48264. // Else weight must be in [0, 1] range
  48265. this._weight = Math.min(Math.max(value, 0), 1.0);
  48266. },
  48267. enumerable: true,
  48268. configurable: true
  48269. });
  48270. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48271. /**
  48272. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48273. */
  48274. get: function () {
  48275. return this._speedRatio;
  48276. },
  48277. set: function (value) {
  48278. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48279. var animation = this._runtimeAnimations[index];
  48280. animation._prepareForSpeedRatioChange(value);
  48281. }
  48282. this._speedRatio = value;
  48283. },
  48284. enumerable: true,
  48285. configurable: true
  48286. });
  48287. // Methods
  48288. /**
  48289. * Synchronize and normalize current Animatable with a source Animatable.
  48290. * This is useful when using animation weights and when animations are not of the same length
  48291. * @param root defines the root Animatable to synchronize with
  48292. * @returns the current Animatable
  48293. */
  48294. Animatable.prototype.syncWith = function (root) {
  48295. this._syncRoot = root;
  48296. if (root) {
  48297. // Make sure this animatable will animate after the root
  48298. var index = this._scene._activeAnimatables.indexOf(this);
  48299. if (index > -1) {
  48300. this._scene._activeAnimatables.splice(index, 1);
  48301. this._scene._activeAnimatables.push(this);
  48302. }
  48303. }
  48304. return this;
  48305. };
  48306. Animatable.prototype.getAnimations = function () {
  48307. return this._runtimeAnimations;
  48308. };
  48309. Animatable.prototype.appendAnimations = function (target, animations) {
  48310. for (var index = 0; index < animations.length; index++) {
  48311. var animation = animations[index];
  48312. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  48313. }
  48314. };
  48315. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48316. var runtimeAnimations = this._runtimeAnimations;
  48317. for (var index = 0; index < runtimeAnimations.length; index++) {
  48318. if (runtimeAnimations[index].animation.targetProperty === property) {
  48319. return runtimeAnimations[index].animation;
  48320. }
  48321. }
  48322. return null;
  48323. };
  48324. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48325. var runtimeAnimations = this._runtimeAnimations;
  48326. for (var index = 0; index < runtimeAnimations.length; index++) {
  48327. if (runtimeAnimations[index].animation.targetProperty === property) {
  48328. return runtimeAnimations[index];
  48329. }
  48330. }
  48331. return null;
  48332. };
  48333. Animatable.prototype.reset = function () {
  48334. var runtimeAnimations = this._runtimeAnimations;
  48335. for (var index = 0; index < runtimeAnimations.length; index++) {
  48336. runtimeAnimations[index].reset();
  48337. }
  48338. // Reset to original value
  48339. for (index = 0; index < runtimeAnimations.length; index++) {
  48340. var animation = runtimeAnimations[index];
  48341. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48342. }
  48343. this._localDelayOffset = null;
  48344. this._pausedDelay = null;
  48345. };
  48346. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48347. var runtimeAnimations = this._runtimeAnimations;
  48348. for (var index = 0; index < runtimeAnimations.length; index++) {
  48349. runtimeAnimations[index].animation.enableBlending = true;
  48350. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48351. }
  48352. };
  48353. Animatable.prototype.disableBlending = function () {
  48354. var runtimeAnimations = this._runtimeAnimations;
  48355. for (var index = 0; index < runtimeAnimations.length; index++) {
  48356. runtimeAnimations[index].animation.enableBlending = false;
  48357. }
  48358. };
  48359. Animatable.prototype.goToFrame = function (frame) {
  48360. var runtimeAnimations = this._runtimeAnimations;
  48361. if (runtimeAnimations[0]) {
  48362. var fps = runtimeAnimations[0].animation.framePerSecond;
  48363. var currentFrame = runtimeAnimations[0].currentFrame;
  48364. var adjustTime = frame - currentFrame;
  48365. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48366. if (this._localDelayOffset === null) {
  48367. this._localDelayOffset = 0;
  48368. }
  48369. this._localDelayOffset -= delay;
  48370. }
  48371. for (var index = 0; index < runtimeAnimations.length; index++) {
  48372. runtimeAnimations[index].goToFrame(frame);
  48373. }
  48374. };
  48375. Animatable.prototype.pause = function () {
  48376. if (this._paused) {
  48377. return;
  48378. }
  48379. this._paused = true;
  48380. };
  48381. Animatable.prototype.restart = function () {
  48382. this._paused = false;
  48383. };
  48384. Animatable.prototype.stop = function (animationName) {
  48385. if (animationName) {
  48386. var idx = this._scene._activeAnimatables.indexOf(this);
  48387. if (idx > -1) {
  48388. var runtimeAnimations = this._runtimeAnimations;
  48389. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48390. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48391. continue;
  48392. }
  48393. runtimeAnimations[index].dispose();
  48394. runtimeAnimations.splice(index, 1);
  48395. }
  48396. if (runtimeAnimations.length == 0) {
  48397. this._scene._activeAnimatables.splice(idx, 1);
  48398. if (this.onAnimationEnd) {
  48399. this.onAnimationEnd();
  48400. }
  48401. }
  48402. }
  48403. }
  48404. else {
  48405. var index = this._scene._activeAnimatables.indexOf(this);
  48406. if (index > -1) {
  48407. this._scene._activeAnimatables.splice(index, 1);
  48408. var runtimeAnimations = this._runtimeAnimations;
  48409. for (var index = 0; index < runtimeAnimations.length; index++) {
  48410. runtimeAnimations[index].dispose();
  48411. }
  48412. if (this.onAnimationEnd) {
  48413. this.onAnimationEnd();
  48414. }
  48415. }
  48416. }
  48417. };
  48418. Animatable.prototype._animate = function (delay) {
  48419. if (this._paused) {
  48420. this.animationStarted = false;
  48421. if (this._pausedDelay === null) {
  48422. this._pausedDelay = delay;
  48423. }
  48424. return true;
  48425. }
  48426. if (this._localDelayOffset === null) {
  48427. this._localDelayOffset = delay;
  48428. this._pausedDelay = null;
  48429. }
  48430. else if (this._pausedDelay !== null) {
  48431. this._localDelayOffset += delay - this._pausedDelay;
  48432. this._pausedDelay = null;
  48433. }
  48434. if (this._weight === 0) {
  48435. return true;
  48436. }
  48437. // Animating
  48438. var running = false;
  48439. var runtimeAnimations = this._runtimeAnimations;
  48440. var index;
  48441. for (index = 0; index < runtimeAnimations.length; index++) {
  48442. var animation = runtimeAnimations[index];
  48443. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48444. running = running || isRunning;
  48445. }
  48446. this.animationStarted = running;
  48447. if (!running) {
  48448. // Remove from active animatables
  48449. index = this._scene._activeAnimatables.indexOf(this);
  48450. this._scene._activeAnimatables.splice(index, 1);
  48451. // Dispose all runtime animations
  48452. for (index = 0; index < runtimeAnimations.length; index++) {
  48453. runtimeAnimations[index].dispose();
  48454. }
  48455. }
  48456. if (!running && this.onAnimationEnd) {
  48457. this.onAnimationEnd();
  48458. this.onAnimationEnd = null;
  48459. }
  48460. return running;
  48461. };
  48462. return Animatable;
  48463. }());
  48464. BABYLON.Animatable = Animatable;
  48465. })(BABYLON || (BABYLON = {}));
  48466. //# sourceMappingURL=babylon.animatable.js.map
  48467. "use strict";
  48468. var BABYLON;
  48469. (function (BABYLON) {
  48470. var EasingFunction = /** @class */ (function () {
  48471. function EasingFunction() {
  48472. // Properties
  48473. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48474. }
  48475. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48476. get: function () {
  48477. return EasingFunction._EASINGMODE_EASEIN;
  48478. },
  48479. enumerable: true,
  48480. configurable: true
  48481. });
  48482. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48483. get: function () {
  48484. return EasingFunction._EASINGMODE_EASEOUT;
  48485. },
  48486. enumerable: true,
  48487. configurable: true
  48488. });
  48489. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48490. get: function () {
  48491. return EasingFunction._EASINGMODE_EASEINOUT;
  48492. },
  48493. enumerable: true,
  48494. configurable: true
  48495. });
  48496. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48497. var n = Math.min(Math.max(easingMode, 0), 2);
  48498. this._easingMode = n;
  48499. };
  48500. EasingFunction.prototype.getEasingMode = function () {
  48501. return this._easingMode;
  48502. };
  48503. EasingFunction.prototype.easeInCore = function (gradient) {
  48504. throw new Error('You must implement this method');
  48505. };
  48506. EasingFunction.prototype.ease = function (gradient) {
  48507. switch (this._easingMode) {
  48508. case EasingFunction.EASINGMODE_EASEIN:
  48509. return this.easeInCore(gradient);
  48510. case EasingFunction.EASINGMODE_EASEOUT:
  48511. return (1 - this.easeInCore(1 - gradient));
  48512. }
  48513. if (gradient >= 0.5) {
  48514. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48515. }
  48516. return (this.easeInCore(gradient * 2) * 0.5);
  48517. };
  48518. //Statics
  48519. EasingFunction._EASINGMODE_EASEIN = 0;
  48520. EasingFunction._EASINGMODE_EASEOUT = 1;
  48521. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48522. return EasingFunction;
  48523. }());
  48524. BABYLON.EasingFunction = EasingFunction;
  48525. var CircleEase = /** @class */ (function (_super) {
  48526. __extends(CircleEase, _super);
  48527. function CircleEase() {
  48528. return _super !== null && _super.apply(this, arguments) || this;
  48529. }
  48530. CircleEase.prototype.easeInCore = function (gradient) {
  48531. gradient = Math.max(0, Math.min(1, gradient));
  48532. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48533. };
  48534. return CircleEase;
  48535. }(EasingFunction));
  48536. BABYLON.CircleEase = CircleEase;
  48537. var BackEase = /** @class */ (function (_super) {
  48538. __extends(BackEase, _super);
  48539. function BackEase(amplitude) {
  48540. if (amplitude === void 0) { amplitude = 1; }
  48541. var _this = _super.call(this) || this;
  48542. _this.amplitude = amplitude;
  48543. return _this;
  48544. }
  48545. BackEase.prototype.easeInCore = function (gradient) {
  48546. var num = Math.max(0, this.amplitude);
  48547. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48548. };
  48549. return BackEase;
  48550. }(EasingFunction));
  48551. BABYLON.BackEase = BackEase;
  48552. var BounceEase = /** @class */ (function (_super) {
  48553. __extends(BounceEase, _super);
  48554. function BounceEase(bounces, bounciness) {
  48555. if (bounces === void 0) { bounces = 3; }
  48556. if (bounciness === void 0) { bounciness = 2; }
  48557. var _this = _super.call(this) || this;
  48558. _this.bounces = bounces;
  48559. _this.bounciness = bounciness;
  48560. return _this;
  48561. }
  48562. BounceEase.prototype.easeInCore = function (gradient) {
  48563. var y = Math.max(0.0, this.bounces);
  48564. var bounciness = this.bounciness;
  48565. if (bounciness <= 1.0) {
  48566. bounciness = 1.001;
  48567. }
  48568. var num9 = Math.pow(bounciness, y);
  48569. var num5 = 1.0 - bounciness;
  48570. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48571. var num15 = gradient * num4;
  48572. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48573. var num3 = Math.floor(num65);
  48574. var num13 = num3 + 1.0;
  48575. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48576. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48577. var num7 = (num8 + num12) * 0.5;
  48578. var num6 = gradient - num7;
  48579. var num2 = num7 - num8;
  48580. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48581. };
  48582. return BounceEase;
  48583. }(EasingFunction));
  48584. BABYLON.BounceEase = BounceEase;
  48585. var CubicEase = /** @class */ (function (_super) {
  48586. __extends(CubicEase, _super);
  48587. function CubicEase() {
  48588. return _super !== null && _super.apply(this, arguments) || this;
  48589. }
  48590. CubicEase.prototype.easeInCore = function (gradient) {
  48591. return (gradient * gradient * gradient);
  48592. };
  48593. return CubicEase;
  48594. }(EasingFunction));
  48595. BABYLON.CubicEase = CubicEase;
  48596. var ElasticEase = /** @class */ (function (_super) {
  48597. __extends(ElasticEase, _super);
  48598. function ElasticEase(oscillations, springiness) {
  48599. if (oscillations === void 0) { oscillations = 3; }
  48600. if (springiness === void 0) { springiness = 3; }
  48601. var _this = _super.call(this) || this;
  48602. _this.oscillations = oscillations;
  48603. _this.springiness = springiness;
  48604. return _this;
  48605. }
  48606. ElasticEase.prototype.easeInCore = function (gradient) {
  48607. var num2;
  48608. var num3 = Math.max(0.0, this.oscillations);
  48609. var num = Math.max(0.0, this.springiness);
  48610. if (num == 0) {
  48611. num2 = gradient;
  48612. }
  48613. else {
  48614. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48615. }
  48616. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48617. };
  48618. return ElasticEase;
  48619. }(EasingFunction));
  48620. BABYLON.ElasticEase = ElasticEase;
  48621. var ExponentialEase = /** @class */ (function (_super) {
  48622. __extends(ExponentialEase, _super);
  48623. function ExponentialEase(exponent) {
  48624. if (exponent === void 0) { exponent = 2; }
  48625. var _this = _super.call(this) || this;
  48626. _this.exponent = exponent;
  48627. return _this;
  48628. }
  48629. ExponentialEase.prototype.easeInCore = function (gradient) {
  48630. if (this.exponent <= 0) {
  48631. return gradient;
  48632. }
  48633. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48634. };
  48635. return ExponentialEase;
  48636. }(EasingFunction));
  48637. BABYLON.ExponentialEase = ExponentialEase;
  48638. var PowerEase = /** @class */ (function (_super) {
  48639. __extends(PowerEase, _super);
  48640. function PowerEase(power) {
  48641. if (power === void 0) { power = 2; }
  48642. var _this = _super.call(this) || this;
  48643. _this.power = power;
  48644. return _this;
  48645. }
  48646. PowerEase.prototype.easeInCore = function (gradient) {
  48647. var y = Math.max(0.0, this.power);
  48648. return Math.pow(gradient, y);
  48649. };
  48650. return PowerEase;
  48651. }(EasingFunction));
  48652. BABYLON.PowerEase = PowerEase;
  48653. var QuadraticEase = /** @class */ (function (_super) {
  48654. __extends(QuadraticEase, _super);
  48655. function QuadraticEase() {
  48656. return _super !== null && _super.apply(this, arguments) || this;
  48657. }
  48658. QuadraticEase.prototype.easeInCore = function (gradient) {
  48659. return (gradient * gradient);
  48660. };
  48661. return QuadraticEase;
  48662. }(EasingFunction));
  48663. BABYLON.QuadraticEase = QuadraticEase;
  48664. var QuarticEase = /** @class */ (function (_super) {
  48665. __extends(QuarticEase, _super);
  48666. function QuarticEase() {
  48667. return _super !== null && _super.apply(this, arguments) || this;
  48668. }
  48669. QuarticEase.prototype.easeInCore = function (gradient) {
  48670. return (gradient * gradient * gradient * gradient);
  48671. };
  48672. return QuarticEase;
  48673. }(EasingFunction));
  48674. BABYLON.QuarticEase = QuarticEase;
  48675. var QuinticEase = /** @class */ (function (_super) {
  48676. __extends(QuinticEase, _super);
  48677. function QuinticEase() {
  48678. return _super !== null && _super.apply(this, arguments) || this;
  48679. }
  48680. QuinticEase.prototype.easeInCore = function (gradient) {
  48681. return (gradient * gradient * gradient * gradient * gradient);
  48682. };
  48683. return QuinticEase;
  48684. }(EasingFunction));
  48685. BABYLON.QuinticEase = QuinticEase;
  48686. var SineEase = /** @class */ (function (_super) {
  48687. __extends(SineEase, _super);
  48688. function SineEase() {
  48689. return _super !== null && _super.apply(this, arguments) || this;
  48690. }
  48691. SineEase.prototype.easeInCore = function (gradient) {
  48692. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48693. };
  48694. return SineEase;
  48695. }(EasingFunction));
  48696. BABYLON.SineEase = SineEase;
  48697. var BezierCurveEase = /** @class */ (function (_super) {
  48698. __extends(BezierCurveEase, _super);
  48699. function BezierCurveEase(x1, y1, x2, y2) {
  48700. if (x1 === void 0) { x1 = 0; }
  48701. if (y1 === void 0) { y1 = 0; }
  48702. if (x2 === void 0) { x2 = 1; }
  48703. if (y2 === void 0) { y2 = 1; }
  48704. var _this = _super.call(this) || this;
  48705. _this.x1 = x1;
  48706. _this.y1 = y1;
  48707. _this.x2 = x2;
  48708. _this.y2 = y2;
  48709. return _this;
  48710. }
  48711. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48712. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48713. };
  48714. return BezierCurveEase;
  48715. }(EasingFunction));
  48716. BABYLON.BezierCurveEase = BezierCurveEase;
  48717. })(BABYLON || (BABYLON = {}));
  48718. //# sourceMappingURL=babylon.easing.js.map
  48719. "use strict";
  48720. var BABYLON;
  48721. (function (BABYLON) {
  48722. /**
  48723. * A Condition applied to an Action
  48724. */
  48725. var Condition = /** @class */ (function () {
  48726. /**
  48727. * Creates a new Condition
  48728. * @param actionManager the manager of the action the condition is applied to
  48729. */
  48730. function Condition(actionManager) {
  48731. this._actionManager = actionManager;
  48732. }
  48733. /**
  48734. * Check if the current condition is valid
  48735. * @returns a boolean
  48736. */
  48737. Condition.prototype.isValid = function () {
  48738. return true;
  48739. };
  48740. /**
  48741. * Internal only
  48742. * @ignore
  48743. */
  48744. Condition.prototype._getProperty = function (propertyPath) {
  48745. return this._actionManager._getProperty(propertyPath);
  48746. };
  48747. /**
  48748. * Internal only
  48749. * @ignore
  48750. */
  48751. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48752. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48753. };
  48754. /**
  48755. * Serialize placeholder for child classes
  48756. * @returns the serialized object
  48757. */
  48758. Condition.prototype.serialize = function () {
  48759. };
  48760. /**
  48761. * Internal only
  48762. * @ignore
  48763. */
  48764. Condition.prototype._serialize = function (serializedCondition) {
  48765. return {
  48766. type: 2,
  48767. children: [],
  48768. name: serializedCondition.name,
  48769. properties: serializedCondition.properties
  48770. };
  48771. };
  48772. return Condition;
  48773. }());
  48774. BABYLON.Condition = Condition;
  48775. /**
  48776. * Defines specific conditional operators as extensions of Condition
  48777. */
  48778. var ValueCondition = /** @class */ (function (_super) {
  48779. __extends(ValueCondition, _super);
  48780. /**
  48781. * Creates a new ValueCondition
  48782. * @param actionManager manager for the action the condition applies to
  48783. * @param target for the action
  48784. * @param propertyPath path to specify the property of the target the conditional operator uses
  48785. * @param value the vale compared by the conditional operator against the current value of the property
  48786. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  48787. */
  48788. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48789. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48790. var _this = _super.call(this, actionManager) || this;
  48791. _this.propertyPath = propertyPath;
  48792. _this.value = value;
  48793. _this.operator = operator;
  48794. _this._target = target;
  48795. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48796. _this._property = _this._getProperty(_this.propertyPath);
  48797. return _this;
  48798. }
  48799. Object.defineProperty(ValueCondition, "IsEqual", {
  48800. /**
  48801. * returns the number for IsEqual
  48802. */
  48803. get: function () {
  48804. return ValueCondition._IsEqual;
  48805. },
  48806. enumerable: true,
  48807. configurable: true
  48808. });
  48809. Object.defineProperty(ValueCondition, "IsDifferent", {
  48810. /**
  48811. * Returns the number for IsDifferent
  48812. */
  48813. get: function () {
  48814. return ValueCondition._IsDifferent;
  48815. },
  48816. enumerable: true,
  48817. configurable: true
  48818. });
  48819. Object.defineProperty(ValueCondition, "IsGreater", {
  48820. /**
  48821. * Returns the number for IsGreater
  48822. */
  48823. get: function () {
  48824. return ValueCondition._IsGreater;
  48825. },
  48826. enumerable: true,
  48827. configurable: true
  48828. });
  48829. Object.defineProperty(ValueCondition, "IsLesser", {
  48830. /**
  48831. * Returns the number for IsLesser
  48832. */
  48833. get: function () {
  48834. return ValueCondition._IsLesser;
  48835. },
  48836. enumerable: true,
  48837. configurable: true
  48838. });
  48839. /**
  48840. * Compares the given value with the property value for the specified conditional operator
  48841. * @returns the result of the comparison
  48842. */
  48843. ValueCondition.prototype.isValid = function () {
  48844. switch (this.operator) {
  48845. case ValueCondition.IsGreater:
  48846. return this._effectiveTarget[this._property] > this.value;
  48847. case ValueCondition.IsLesser:
  48848. return this._effectiveTarget[this._property] < this.value;
  48849. case ValueCondition.IsEqual:
  48850. case ValueCondition.IsDifferent:
  48851. var check;
  48852. if (this.value.equals) {
  48853. check = this.value.equals(this._effectiveTarget[this._property]);
  48854. }
  48855. else {
  48856. check = this.value === this._effectiveTarget[this._property];
  48857. }
  48858. return this.operator === ValueCondition.IsEqual ? check : !check;
  48859. }
  48860. return false;
  48861. };
  48862. /**
  48863. * Serialize the ValueCondition into a JSON compatible object
  48864. * @returns serialization object
  48865. */
  48866. ValueCondition.prototype.serialize = function () {
  48867. return this._serialize({
  48868. name: "ValueCondition",
  48869. properties: [
  48870. BABYLON.Action._GetTargetProperty(this._target),
  48871. { name: "propertyPath", value: this.propertyPath },
  48872. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48873. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48874. ]
  48875. });
  48876. };
  48877. /**
  48878. * Gets the name of the conditional operator for the ValueCondition
  48879. * @param operator the conditional operator
  48880. * @returns the name
  48881. */
  48882. ValueCondition.GetOperatorName = function (operator) {
  48883. switch (operator) {
  48884. case ValueCondition._IsEqual: return "IsEqual";
  48885. case ValueCondition._IsDifferent: return "IsDifferent";
  48886. case ValueCondition._IsGreater: return "IsGreater";
  48887. case ValueCondition._IsLesser: return "IsLesser";
  48888. default: return "";
  48889. }
  48890. };
  48891. /**
  48892. * Internal only
  48893. * @ignore
  48894. */
  48895. ValueCondition._IsEqual = 0;
  48896. /**
  48897. * Internal only
  48898. * @ignore
  48899. */
  48900. ValueCondition._IsDifferent = 1;
  48901. /**
  48902. * Internal only
  48903. * @ignore
  48904. */
  48905. ValueCondition._IsGreater = 2;
  48906. /**
  48907. * Internal only
  48908. * @ignore
  48909. */
  48910. ValueCondition._IsLesser = 3;
  48911. return ValueCondition;
  48912. }(Condition));
  48913. BABYLON.ValueCondition = ValueCondition;
  48914. /**
  48915. * Defines a predicate condition as an extension of Condition
  48916. */
  48917. var PredicateCondition = /** @class */ (function (_super) {
  48918. __extends(PredicateCondition, _super);
  48919. /**
  48920. * Creates a new {BABYLON.PredicateCondition}
  48921. * @param actionManager manager for the action the condition applies to
  48922. * @param predicate
  48923. */
  48924. function PredicateCondition(actionManager, predicate) {
  48925. var _this = _super.call(this, actionManager) || this;
  48926. _this.predicate = predicate;
  48927. return _this;
  48928. }
  48929. /**
  48930. * @returns the validity of the predicate condition
  48931. */
  48932. PredicateCondition.prototype.isValid = function () {
  48933. return this.predicate();
  48934. };
  48935. return PredicateCondition;
  48936. }(Condition));
  48937. BABYLON.PredicateCondition = PredicateCondition;
  48938. /**
  48939. * Defines a state condition as an extension of {BABYLON.Condition}
  48940. */
  48941. var StateCondition = /** @class */ (function (_super) {
  48942. __extends(StateCondition, _super);
  48943. /**
  48944. * Creates a new {BABYLON.StateCondition}
  48945. * @param actionManager manager for the action the condition applies to
  48946. * @param target of the condition
  48947. * @param value to compare with target state
  48948. */
  48949. function StateCondition(actionManager, target, value) {
  48950. var _this = _super.call(this, actionManager) || this;
  48951. _this.value = value;
  48952. _this._target = target;
  48953. return _this;
  48954. }
  48955. /**
  48956. * @returns the validity of the state
  48957. */
  48958. StateCondition.prototype.isValid = function () {
  48959. return this._target.state === this.value;
  48960. };
  48961. /**
  48962. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  48963. * @returns serialization object
  48964. */
  48965. StateCondition.prototype.serialize = function () {
  48966. return this._serialize({
  48967. name: "StateCondition",
  48968. properties: [
  48969. BABYLON.Action._GetTargetProperty(this._target),
  48970. { name: "value", value: this.value }
  48971. ]
  48972. });
  48973. };
  48974. return StateCondition;
  48975. }(Condition));
  48976. BABYLON.StateCondition = StateCondition;
  48977. })(BABYLON || (BABYLON = {}));
  48978. //# sourceMappingURL=babylon.condition.js.map
  48979. "use strict";
  48980. var BABYLON;
  48981. (function (BABYLON) {
  48982. /**
  48983. * The action to be carried out following a trigger
  48984. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  48985. */
  48986. var Action = /** @class */ (function () {
  48987. /**
  48988. * Creates a new Action
  48989. * @param triggerOptions the trigger, with or without parameters, for the action
  48990. * @param condition an optional determinant of action
  48991. */
  48992. function Action(triggerOptions, condition) {
  48993. this.triggerOptions = triggerOptions;
  48994. /**
  48995. * An event triggered prior to action being executed.
  48996. * @type Observable
  48997. */
  48998. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48999. if (triggerOptions.parameter) {
  49000. this.trigger = triggerOptions.trigger;
  49001. this._triggerParameter = triggerOptions.parameter;
  49002. }
  49003. else {
  49004. this.trigger = triggerOptions;
  49005. }
  49006. this._nextActiveAction = this;
  49007. this._condition = condition;
  49008. }
  49009. /**
  49010. * Internal only
  49011. * @ignore
  49012. */
  49013. Action.prototype._prepare = function () {
  49014. };
  49015. /**
  49016. * Gets the trigger parameters
  49017. * @returns the trigger parameters
  49018. */
  49019. Action.prototype.getTriggerParameter = function () {
  49020. return this._triggerParameter;
  49021. };
  49022. /**
  49023. * Internal only - executes current action event
  49024. * @ignore
  49025. */
  49026. Action.prototype._executeCurrent = function (evt) {
  49027. if (this._nextActiveAction._condition) {
  49028. var condition = this._nextActiveAction._condition;
  49029. var currentRenderId = this._actionManager.getScene().getRenderId();
  49030. // We cache the current evaluation for the current frame
  49031. if (condition._evaluationId === currentRenderId) {
  49032. if (!condition._currentResult) {
  49033. return;
  49034. }
  49035. }
  49036. else {
  49037. condition._evaluationId = currentRenderId;
  49038. if (!condition.isValid()) {
  49039. condition._currentResult = false;
  49040. return;
  49041. }
  49042. condition._currentResult = true;
  49043. }
  49044. }
  49045. this.onBeforeExecuteObservable.notifyObservers(this);
  49046. this._nextActiveAction.execute(evt);
  49047. this.skipToNextActiveAction();
  49048. };
  49049. /**
  49050. * Execute placeholder for child classes
  49051. * @param evt optional action event
  49052. */
  49053. Action.prototype.execute = function (evt) {
  49054. };
  49055. /**
  49056. * Skips to next active action
  49057. */
  49058. Action.prototype.skipToNextActiveAction = function () {
  49059. if (this._nextActiveAction._child) {
  49060. if (!this._nextActiveAction._child._actionManager) {
  49061. this._nextActiveAction._child._actionManager = this._actionManager;
  49062. }
  49063. this._nextActiveAction = this._nextActiveAction._child;
  49064. }
  49065. else {
  49066. this._nextActiveAction = this;
  49067. }
  49068. };
  49069. /**
  49070. * Adds action to chain of actions, may be a DoNothingAction
  49071. * @param index The index of the attribute.
  49072. * @returns The action passed in
  49073. * @see https://www.babylonjs-playground.com/#1T30HR#0
  49074. */
  49075. Action.prototype.then = function (action) {
  49076. this._child = action;
  49077. action._actionManager = this._actionManager;
  49078. action._prepare();
  49079. return action;
  49080. };
  49081. /**
  49082. * Internal only
  49083. * @ignore
  49084. */
  49085. Action.prototype._getProperty = function (propertyPath) {
  49086. return this._actionManager._getProperty(propertyPath);
  49087. };
  49088. /**
  49089. * Internal only
  49090. * @ignore
  49091. */
  49092. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  49093. return this._actionManager._getEffectiveTarget(target, propertyPath);
  49094. };
  49095. /**
  49096. * Serialize placeholder for child classes
  49097. * @param parent of child
  49098. * @returns the serialized object
  49099. */
  49100. Action.prototype.serialize = function (parent) {
  49101. };
  49102. /**
  49103. * Internal only called by serialize
  49104. * @ignore
  49105. */
  49106. Action.prototype._serialize = function (serializedAction, parent) {
  49107. var serializationObject = {
  49108. type: 1,
  49109. children: [],
  49110. name: serializedAction.name,
  49111. properties: serializedAction.properties || []
  49112. };
  49113. // Serialize child
  49114. if (this._child) {
  49115. this._child.serialize(serializationObject);
  49116. }
  49117. // Check if "this" has a condition
  49118. if (this._condition) {
  49119. var serializedCondition = this._condition.serialize();
  49120. serializedCondition.children.push(serializationObject);
  49121. if (parent) {
  49122. parent.children.push(serializedCondition);
  49123. }
  49124. return serializedCondition;
  49125. }
  49126. if (parent) {
  49127. parent.children.push(serializationObject);
  49128. }
  49129. return serializationObject;
  49130. };
  49131. /**
  49132. * Internal only
  49133. * @ignore
  49134. */
  49135. Action._SerializeValueAsString = function (value) {
  49136. if (typeof value === "number") {
  49137. return value.toString();
  49138. }
  49139. if (typeof value === "boolean") {
  49140. return value ? "true" : "false";
  49141. }
  49142. if (value instanceof BABYLON.Vector2) {
  49143. return value.x + ", " + value.y;
  49144. }
  49145. if (value instanceof BABYLON.Vector3) {
  49146. return value.x + ", " + value.y + ", " + value.z;
  49147. }
  49148. if (value instanceof BABYLON.Color3) {
  49149. return value.r + ", " + value.g + ", " + value.b;
  49150. }
  49151. if (value instanceof BABYLON.Color4) {
  49152. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  49153. }
  49154. return value; // string
  49155. };
  49156. /**
  49157. * Internal only
  49158. * @ignore
  49159. */
  49160. Action._GetTargetProperty = function (target) {
  49161. return {
  49162. name: "target",
  49163. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  49164. : target instanceof BABYLON.Light ? "LightProperties"
  49165. : target instanceof BABYLON.Camera ? "CameraProperties"
  49166. : "SceneProperties",
  49167. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  49168. };
  49169. };
  49170. return Action;
  49171. }());
  49172. BABYLON.Action = Action;
  49173. })(BABYLON || (BABYLON = {}));
  49174. //# sourceMappingURL=babylon.action.js.map
  49175. "use strict";
  49176. var BABYLON;
  49177. (function (BABYLON) {
  49178. /**
  49179. * ActionEvent is the event being sent when an action is triggered.
  49180. */
  49181. var ActionEvent = /** @class */ (function () {
  49182. /**
  49183. * @param source The mesh or sprite that triggered the action.
  49184. * @param pointerX The X mouse cursor position at the time of the event
  49185. * @param pointerY The Y mouse cursor position at the time of the event
  49186. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  49187. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  49188. */
  49189. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  49190. this.source = source;
  49191. this.pointerX = pointerX;
  49192. this.pointerY = pointerY;
  49193. this.meshUnderPointer = meshUnderPointer;
  49194. this.sourceEvent = sourceEvent;
  49195. this.additionalData = additionalData;
  49196. }
  49197. /**
  49198. * Helper function to auto-create an ActionEvent from a source mesh.
  49199. * @param source The source mesh that triggered the event
  49200. * @param evt {Event} The original (browser) event
  49201. */
  49202. ActionEvent.CreateNew = function (source, evt, additionalData) {
  49203. var scene = source.getScene();
  49204. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49205. };
  49206. /**
  49207. * Helper function to auto-create an ActionEvent from a source mesh.
  49208. * @param source The source sprite that triggered the event
  49209. * @param scene Scene associated with the sprite
  49210. * @param evt {Event} The original (browser) event
  49211. */
  49212. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  49213. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49214. };
  49215. /**
  49216. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  49217. * @param scene the scene where the event occurred
  49218. * @param evt {Event} The original (browser) event
  49219. */
  49220. ActionEvent.CreateNewFromScene = function (scene, evt) {
  49221. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  49222. };
  49223. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  49224. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  49225. };
  49226. return ActionEvent;
  49227. }());
  49228. BABYLON.ActionEvent = ActionEvent;
  49229. /**
  49230. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  49231. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  49232. */
  49233. var ActionManager = /** @class */ (function () {
  49234. function ActionManager(scene) {
  49235. // Members
  49236. this.actions = new Array();
  49237. this.hoverCursor = '';
  49238. this._scene = scene;
  49239. scene._actionManagers.push(this);
  49240. }
  49241. Object.defineProperty(ActionManager, "NothingTrigger", {
  49242. get: function () {
  49243. return ActionManager._NothingTrigger;
  49244. },
  49245. enumerable: true,
  49246. configurable: true
  49247. });
  49248. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49249. get: function () {
  49250. return ActionManager._OnPickTrigger;
  49251. },
  49252. enumerable: true,
  49253. configurable: true
  49254. });
  49255. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49256. get: function () {
  49257. return ActionManager._OnLeftPickTrigger;
  49258. },
  49259. enumerable: true,
  49260. configurable: true
  49261. });
  49262. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49263. get: function () {
  49264. return ActionManager._OnRightPickTrigger;
  49265. },
  49266. enumerable: true,
  49267. configurable: true
  49268. });
  49269. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49270. get: function () {
  49271. return ActionManager._OnCenterPickTrigger;
  49272. },
  49273. enumerable: true,
  49274. configurable: true
  49275. });
  49276. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49277. get: function () {
  49278. return ActionManager._OnPickDownTrigger;
  49279. },
  49280. enumerable: true,
  49281. configurable: true
  49282. });
  49283. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49284. get: function () {
  49285. return ActionManager._OnDoublePickTrigger;
  49286. },
  49287. enumerable: true,
  49288. configurable: true
  49289. });
  49290. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49291. get: function () {
  49292. return ActionManager._OnPickUpTrigger;
  49293. },
  49294. enumerable: true,
  49295. configurable: true
  49296. });
  49297. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49298. /// This trigger will only be raised if you also declared a OnPickDown
  49299. get: function () {
  49300. return ActionManager._OnPickOutTrigger;
  49301. },
  49302. enumerable: true,
  49303. configurable: true
  49304. });
  49305. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49306. get: function () {
  49307. return ActionManager._OnLongPressTrigger;
  49308. },
  49309. enumerable: true,
  49310. configurable: true
  49311. });
  49312. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49313. get: function () {
  49314. return ActionManager._OnPointerOverTrigger;
  49315. },
  49316. enumerable: true,
  49317. configurable: true
  49318. });
  49319. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49320. get: function () {
  49321. return ActionManager._OnPointerOutTrigger;
  49322. },
  49323. enumerable: true,
  49324. configurable: true
  49325. });
  49326. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49327. get: function () {
  49328. return ActionManager._OnEveryFrameTrigger;
  49329. },
  49330. enumerable: true,
  49331. configurable: true
  49332. });
  49333. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49334. get: function () {
  49335. return ActionManager._OnIntersectionEnterTrigger;
  49336. },
  49337. enumerable: true,
  49338. configurable: true
  49339. });
  49340. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49341. get: function () {
  49342. return ActionManager._OnIntersectionExitTrigger;
  49343. },
  49344. enumerable: true,
  49345. configurable: true
  49346. });
  49347. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49348. get: function () {
  49349. return ActionManager._OnKeyDownTrigger;
  49350. },
  49351. enumerable: true,
  49352. configurable: true
  49353. });
  49354. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49355. get: function () {
  49356. return ActionManager._OnKeyUpTrigger;
  49357. },
  49358. enumerable: true,
  49359. configurable: true
  49360. });
  49361. // Methods
  49362. ActionManager.prototype.dispose = function () {
  49363. var index = this._scene._actionManagers.indexOf(this);
  49364. for (var i = 0; i < this.actions.length; i++) {
  49365. var action = this.actions[i];
  49366. ActionManager.Triggers[action.trigger]--;
  49367. if (ActionManager.Triggers[action.trigger] === 0) {
  49368. delete ActionManager.Triggers[action.trigger];
  49369. }
  49370. }
  49371. if (index > -1) {
  49372. this._scene._actionManagers.splice(index, 1);
  49373. }
  49374. };
  49375. ActionManager.prototype.getScene = function () {
  49376. return this._scene;
  49377. };
  49378. /**
  49379. * Does this action manager handles actions of any of the given triggers
  49380. * @param {number[]} triggers - the triggers to be tested
  49381. * @return {boolean} whether one (or more) of the triggers is handeled
  49382. */
  49383. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49384. for (var index = 0; index < this.actions.length; index++) {
  49385. var action = this.actions[index];
  49386. if (triggers.indexOf(action.trigger) > -1) {
  49387. return true;
  49388. }
  49389. }
  49390. return false;
  49391. };
  49392. /**
  49393. * Does this action manager handles actions of a given trigger
  49394. * @param {number} trigger - the trigger to be tested
  49395. * @return {boolean} whether the trigger is handeled
  49396. */
  49397. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49398. for (var index = 0; index < this.actions.length; index++) {
  49399. var action = this.actions[index];
  49400. if (action.trigger === trigger) {
  49401. return true;
  49402. }
  49403. }
  49404. return false;
  49405. };
  49406. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49407. /**
  49408. * Does this action manager has pointer triggers
  49409. * @return {boolean} whether or not it has pointer triggers
  49410. */
  49411. get: function () {
  49412. for (var index = 0; index < this.actions.length; index++) {
  49413. var action = this.actions[index];
  49414. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49415. return true;
  49416. }
  49417. }
  49418. return false;
  49419. },
  49420. enumerable: true,
  49421. configurable: true
  49422. });
  49423. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49424. /**
  49425. * Does this action manager has pick triggers
  49426. * @return {boolean} whether or not it has pick triggers
  49427. */
  49428. get: function () {
  49429. for (var index = 0; index < this.actions.length; index++) {
  49430. var action = this.actions[index];
  49431. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49432. return true;
  49433. }
  49434. }
  49435. return false;
  49436. },
  49437. enumerable: true,
  49438. configurable: true
  49439. });
  49440. Object.defineProperty(ActionManager, "HasTriggers", {
  49441. /**
  49442. * Does exist one action manager with at least one trigger
  49443. * @return {boolean} whether or not it exists one action manager with one trigger
  49444. **/
  49445. get: function () {
  49446. for (var t in ActionManager.Triggers) {
  49447. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49448. return true;
  49449. }
  49450. }
  49451. return false;
  49452. },
  49453. enumerable: true,
  49454. configurable: true
  49455. });
  49456. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49457. /**
  49458. * Does exist one action manager with at least one pick trigger
  49459. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49460. **/
  49461. get: function () {
  49462. for (var t in ActionManager.Triggers) {
  49463. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49464. var t_int = parseInt(t);
  49465. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49466. return true;
  49467. }
  49468. }
  49469. }
  49470. return false;
  49471. },
  49472. enumerable: true,
  49473. configurable: true
  49474. });
  49475. /**
  49476. * Does exist one action manager that handles actions of a given trigger
  49477. * @param {number} trigger - the trigger to be tested
  49478. * @return {boolean} whether the trigger is handeled by at least one action manager
  49479. **/
  49480. ActionManager.HasSpecificTrigger = function (trigger) {
  49481. for (var t in ActionManager.Triggers) {
  49482. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49483. var t_int = parseInt(t);
  49484. if (t_int === trigger) {
  49485. return true;
  49486. }
  49487. }
  49488. }
  49489. return false;
  49490. };
  49491. /**
  49492. * Registers an action to this action manager
  49493. * @param {BABYLON.Action} action - the action to be registered
  49494. * @return {BABYLON.Action} the action amended (prepared) after registration
  49495. */
  49496. ActionManager.prototype.registerAction = function (action) {
  49497. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49498. if (this.getScene().actionManager !== this) {
  49499. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49500. return null;
  49501. }
  49502. }
  49503. this.actions.push(action);
  49504. if (ActionManager.Triggers[action.trigger]) {
  49505. ActionManager.Triggers[action.trigger]++;
  49506. }
  49507. else {
  49508. ActionManager.Triggers[action.trigger] = 1;
  49509. }
  49510. action._actionManager = this;
  49511. action._prepare();
  49512. return action;
  49513. };
  49514. /**
  49515. * Unregisters an action to this action manager
  49516. * @param action The action to be unregistered
  49517. * @return whether the action has been unregistered
  49518. */
  49519. ActionManager.prototype.unregisterAction = function (action) {
  49520. var index = this.actions.indexOf(action);
  49521. if (index !== -1) {
  49522. this.actions.splice(index, 1);
  49523. ActionManager.Triggers[action.trigger] -= 1;
  49524. if (ActionManager.Triggers[action.trigger] === 0) {
  49525. delete ActionManager.Triggers[action.trigger];
  49526. }
  49527. delete action._actionManager;
  49528. return true;
  49529. }
  49530. return false;
  49531. };
  49532. /**
  49533. * Process a specific trigger
  49534. * @param {number} trigger - the trigger to process
  49535. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49536. */
  49537. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49538. for (var index = 0; index < this.actions.length; index++) {
  49539. var action = this.actions[index];
  49540. if (action.trigger === trigger) {
  49541. if (evt) {
  49542. if (trigger === ActionManager.OnKeyUpTrigger
  49543. || trigger === ActionManager.OnKeyDownTrigger) {
  49544. var parameter = action.getTriggerParameter();
  49545. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49546. if (!parameter.toLowerCase) {
  49547. continue;
  49548. }
  49549. var lowerCase = parameter.toLowerCase();
  49550. if (lowerCase !== evt.sourceEvent.key) {
  49551. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49552. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49553. if (actualkey !== lowerCase) {
  49554. continue;
  49555. }
  49556. }
  49557. }
  49558. }
  49559. }
  49560. action._executeCurrent(evt);
  49561. }
  49562. }
  49563. };
  49564. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49565. var properties = propertyPath.split(".");
  49566. for (var index = 0; index < properties.length - 1; index++) {
  49567. target = target[properties[index]];
  49568. }
  49569. return target;
  49570. };
  49571. ActionManager.prototype._getProperty = function (propertyPath) {
  49572. var properties = propertyPath.split(".");
  49573. return properties[properties.length - 1];
  49574. };
  49575. ActionManager.prototype.serialize = function (name) {
  49576. var root = {
  49577. children: new Array(),
  49578. name: name,
  49579. type: 3,
  49580. properties: new Array() // Empty for root but required
  49581. };
  49582. for (var i = 0; i < this.actions.length; i++) {
  49583. var triggerObject = {
  49584. type: 0,
  49585. children: new Array(),
  49586. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49587. properties: new Array()
  49588. };
  49589. var triggerOptions = this.actions[i].triggerOptions;
  49590. if (triggerOptions && typeof triggerOptions !== "number") {
  49591. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49592. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49593. }
  49594. else {
  49595. var parameter = {};
  49596. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49597. if (triggerOptions.parameter.mesh) {
  49598. parameter._meshId = triggerOptions.parameter.mesh.id;
  49599. }
  49600. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49601. }
  49602. }
  49603. // Serialize child action, recursively
  49604. this.actions[i].serialize(triggerObject);
  49605. // Add serialized trigger
  49606. root.children.push(triggerObject);
  49607. }
  49608. return root;
  49609. };
  49610. ActionManager.Parse = function (parsedActions, object, scene) {
  49611. var actionManager = new ActionManager(scene);
  49612. if (object === null)
  49613. scene.actionManager = actionManager;
  49614. else
  49615. object.actionManager = actionManager;
  49616. // instanciate a new object
  49617. var instanciate = function (name, params) {
  49618. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49619. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49620. newInstance.constructor.apply(newInstance, params);
  49621. return newInstance;
  49622. };
  49623. var parseParameter = function (name, value, target, propertyPath) {
  49624. if (propertyPath === null) {
  49625. // String, boolean or float
  49626. var floatValue = parseFloat(value);
  49627. if (value === "true" || value === "false")
  49628. return value === "true";
  49629. else
  49630. return isNaN(floatValue) ? value : floatValue;
  49631. }
  49632. var effectiveTarget = propertyPath.split(".");
  49633. var values = value.split(",");
  49634. // Get effective Target
  49635. for (var i = 0; i < effectiveTarget.length; i++) {
  49636. target = target[effectiveTarget[i]];
  49637. }
  49638. // Return appropriate value with its type
  49639. if (typeof (target) === "boolean")
  49640. return values[0] === "true";
  49641. if (typeof (target) === "string")
  49642. return values[0];
  49643. // Parameters with multiple values such as Vector3 etc.
  49644. var split = new Array();
  49645. for (var i = 0; i < values.length; i++)
  49646. split.push(parseFloat(values[i]));
  49647. if (target instanceof BABYLON.Vector3)
  49648. return BABYLON.Vector3.FromArray(split);
  49649. if (target instanceof BABYLON.Vector4)
  49650. return BABYLON.Vector4.FromArray(split);
  49651. if (target instanceof BABYLON.Color3)
  49652. return BABYLON.Color3.FromArray(split);
  49653. if (target instanceof BABYLON.Color4)
  49654. return BABYLON.Color4.FromArray(split);
  49655. return parseFloat(values[0]);
  49656. };
  49657. // traverse graph per trigger
  49658. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49659. if (combineArray === void 0) { combineArray = null; }
  49660. if (parsedAction.detached)
  49661. return;
  49662. var parameters = new Array();
  49663. var target = null;
  49664. var propertyPath = null;
  49665. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49666. // Parameters
  49667. if (parsedAction.type === 2)
  49668. parameters.push(actionManager);
  49669. else
  49670. parameters.push(trigger);
  49671. if (combine) {
  49672. var actions = new Array();
  49673. for (var j = 0; j < parsedAction.combine.length; j++) {
  49674. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49675. }
  49676. parameters.push(actions);
  49677. }
  49678. else {
  49679. for (var i = 0; i < parsedAction.properties.length; i++) {
  49680. var value = parsedAction.properties[i].value;
  49681. var name = parsedAction.properties[i].name;
  49682. var targetType = parsedAction.properties[i].targetType;
  49683. if (name === "target")
  49684. if (targetType !== null && targetType === "SceneProperties")
  49685. value = target = scene;
  49686. else
  49687. value = target = scene.getNodeByName(value);
  49688. else if (name === "parent")
  49689. value = scene.getNodeByName(value);
  49690. else if (name === "sound")
  49691. value = scene.getSoundByName(value);
  49692. else if (name !== "propertyPath") {
  49693. if (parsedAction.type === 2 && name === "operator")
  49694. value = BABYLON.ValueCondition[value];
  49695. else
  49696. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49697. }
  49698. else {
  49699. propertyPath = value;
  49700. }
  49701. parameters.push(value);
  49702. }
  49703. }
  49704. if (combineArray === null) {
  49705. parameters.push(condition);
  49706. }
  49707. else {
  49708. parameters.push(null);
  49709. }
  49710. // If interpolate value action
  49711. if (parsedAction.name === "InterpolateValueAction") {
  49712. var param = parameters[parameters.length - 2];
  49713. parameters[parameters.length - 1] = param;
  49714. parameters[parameters.length - 2] = condition;
  49715. }
  49716. // Action or condition(s) and not CombineAction
  49717. var newAction = instanciate(parsedAction.name, parameters);
  49718. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49719. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49720. if (action)
  49721. action.then(nothing);
  49722. else
  49723. actionManager.registerAction(nothing);
  49724. action = nothing;
  49725. }
  49726. if (combineArray === null) {
  49727. if (newAction instanceof BABYLON.Condition) {
  49728. condition = newAction;
  49729. newAction = action;
  49730. }
  49731. else {
  49732. condition = null;
  49733. if (action)
  49734. action.then(newAction);
  49735. else
  49736. actionManager.registerAction(newAction);
  49737. }
  49738. }
  49739. else {
  49740. combineArray.push(newAction);
  49741. }
  49742. for (var i = 0; i < parsedAction.children.length; i++)
  49743. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49744. };
  49745. // triggers
  49746. for (var i = 0; i < parsedActions.children.length; i++) {
  49747. var triggerParams;
  49748. var trigger = parsedActions.children[i];
  49749. if (trigger.properties.length > 0) {
  49750. var param = trigger.properties[0].value;
  49751. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49752. if (value._meshId) {
  49753. value.mesh = scene.getMeshByID(value._meshId);
  49754. }
  49755. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49756. }
  49757. else
  49758. triggerParams = ActionManager[trigger.name];
  49759. for (var j = 0; j < trigger.children.length; j++) {
  49760. if (!trigger.detached)
  49761. traverse(trigger.children[j], triggerParams, null, null);
  49762. }
  49763. }
  49764. };
  49765. ActionManager.GetTriggerName = function (trigger) {
  49766. switch (trigger) {
  49767. case 0: return "NothingTrigger";
  49768. case 1: return "OnPickTrigger";
  49769. case 2: return "OnLeftPickTrigger";
  49770. case 3: return "OnRightPickTrigger";
  49771. case 4: return "OnCenterPickTrigger";
  49772. case 5: return "OnPickDownTrigger";
  49773. case 6: return "OnPickUpTrigger";
  49774. case 7: return "OnLongPressTrigger";
  49775. case 8: return "OnPointerOverTrigger";
  49776. case 9: return "OnPointerOutTrigger";
  49777. case 10: return "OnEveryFrameTrigger";
  49778. case 11: return "OnIntersectionEnterTrigger";
  49779. case 12: return "OnIntersectionExitTrigger";
  49780. case 13: return "OnKeyDownTrigger";
  49781. case 14: return "OnKeyUpTrigger";
  49782. case 15: return "OnPickOutTrigger";
  49783. default: return "";
  49784. }
  49785. };
  49786. // Statics
  49787. ActionManager._NothingTrigger = 0;
  49788. ActionManager._OnPickTrigger = 1;
  49789. ActionManager._OnLeftPickTrigger = 2;
  49790. ActionManager._OnRightPickTrigger = 3;
  49791. ActionManager._OnCenterPickTrigger = 4;
  49792. ActionManager._OnPickDownTrigger = 5;
  49793. ActionManager._OnDoublePickTrigger = 6;
  49794. ActionManager._OnPickUpTrigger = 7;
  49795. ActionManager._OnLongPressTrigger = 8;
  49796. ActionManager._OnPointerOverTrigger = 9;
  49797. ActionManager._OnPointerOutTrigger = 10;
  49798. ActionManager._OnEveryFrameTrigger = 11;
  49799. ActionManager._OnIntersectionEnterTrigger = 12;
  49800. ActionManager._OnIntersectionExitTrigger = 13;
  49801. ActionManager._OnKeyDownTrigger = 14;
  49802. ActionManager._OnKeyUpTrigger = 15;
  49803. ActionManager._OnPickOutTrigger = 16;
  49804. ActionManager.Triggers = {};
  49805. return ActionManager;
  49806. }());
  49807. BABYLON.ActionManager = ActionManager;
  49808. })(BABYLON || (BABYLON = {}));
  49809. //# sourceMappingURL=babylon.actionManager.js.map
  49810. "use strict";
  49811. var BABYLON;
  49812. (function (BABYLON) {
  49813. var InterpolateValueAction = /** @class */ (function (_super) {
  49814. __extends(InterpolateValueAction, _super);
  49815. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49816. if (duration === void 0) { duration = 1000; }
  49817. var _this = _super.call(this, triggerOptions, condition) || this;
  49818. _this.propertyPath = propertyPath;
  49819. _this.value = value;
  49820. _this.duration = duration;
  49821. _this.stopOtherAnimations = stopOtherAnimations;
  49822. _this.onInterpolationDone = onInterpolationDone;
  49823. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49824. _this._target = _this._effectiveTarget = target;
  49825. return _this;
  49826. }
  49827. InterpolateValueAction.prototype._prepare = function () {
  49828. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49829. this._property = this._getProperty(this.propertyPath);
  49830. };
  49831. InterpolateValueAction.prototype.execute = function () {
  49832. var _this = this;
  49833. var scene = this._actionManager.getScene();
  49834. var keys = [
  49835. {
  49836. frame: 0,
  49837. value: this._effectiveTarget[this._property]
  49838. }, {
  49839. frame: 100,
  49840. value: this.value
  49841. }
  49842. ];
  49843. var dataType;
  49844. if (typeof this.value === "number") {
  49845. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49846. }
  49847. else if (this.value instanceof BABYLON.Color3) {
  49848. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49849. }
  49850. else if (this.value instanceof BABYLON.Vector3) {
  49851. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49852. }
  49853. else if (this.value instanceof BABYLON.Matrix) {
  49854. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49855. }
  49856. else if (this.value instanceof BABYLON.Quaternion) {
  49857. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49858. }
  49859. else {
  49860. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49861. return;
  49862. }
  49863. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49864. animation.setKeys(keys);
  49865. if (this.stopOtherAnimations) {
  49866. scene.stopAnimation(this._effectiveTarget);
  49867. }
  49868. var wrapper = function () {
  49869. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49870. if (_this.onInterpolationDone) {
  49871. _this.onInterpolationDone();
  49872. }
  49873. };
  49874. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49875. };
  49876. InterpolateValueAction.prototype.serialize = function (parent) {
  49877. return _super.prototype._serialize.call(this, {
  49878. name: "InterpolateValueAction",
  49879. properties: [
  49880. BABYLON.Action._GetTargetProperty(this._target),
  49881. { name: "propertyPath", value: this.propertyPath },
  49882. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49883. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49884. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49885. ]
  49886. }, parent);
  49887. };
  49888. return InterpolateValueAction;
  49889. }(BABYLON.Action));
  49890. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49891. })(BABYLON || (BABYLON = {}));
  49892. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49893. "use strict";
  49894. var BABYLON;
  49895. (function (BABYLON) {
  49896. var SwitchBooleanAction = /** @class */ (function (_super) {
  49897. __extends(SwitchBooleanAction, _super);
  49898. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49899. var _this = _super.call(this, triggerOptions, condition) || this;
  49900. _this.propertyPath = propertyPath;
  49901. _this._target = _this._effectiveTarget = target;
  49902. return _this;
  49903. }
  49904. SwitchBooleanAction.prototype._prepare = function () {
  49905. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49906. this._property = this._getProperty(this.propertyPath);
  49907. };
  49908. SwitchBooleanAction.prototype.execute = function () {
  49909. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49910. };
  49911. SwitchBooleanAction.prototype.serialize = function (parent) {
  49912. return _super.prototype._serialize.call(this, {
  49913. name: "SwitchBooleanAction",
  49914. properties: [
  49915. BABYLON.Action._GetTargetProperty(this._target),
  49916. { name: "propertyPath", value: this.propertyPath }
  49917. ]
  49918. }, parent);
  49919. };
  49920. return SwitchBooleanAction;
  49921. }(BABYLON.Action));
  49922. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49923. var SetStateAction = /** @class */ (function (_super) {
  49924. __extends(SetStateAction, _super);
  49925. function SetStateAction(triggerOptions, target, value, condition) {
  49926. var _this = _super.call(this, triggerOptions, condition) || this;
  49927. _this.value = value;
  49928. _this._target = target;
  49929. return _this;
  49930. }
  49931. SetStateAction.prototype.execute = function () {
  49932. this._target.state = this.value;
  49933. };
  49934. SetStateAction.prototype.serialize = function (parent) {
  49935. return _super.prototype._serialize.call(this, {
  49936. name: "SetStateAction",
  49937. properties: [
  49938. BABYLON.Action._GetTargetProperty(this._target),
  49939. { name: "value", value: this.value }
  49940. ]
  49941. }, parent);
  49942. };
  49943. return SetStateAction;
  49944. }(BABYLON.Action));
  49945. BABYLON.SetStateAction = SetStateAction;
  49946. var SetValueAction = /** @class */ (function (_super) {
  49947. __extends(SetValueAction, _super);
  49948. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49949. var _this = _super.call(this, triggerOptions, condition) || this;
  49950. _this.propertyPath = propertyPath;
  49951. _this.value = value;
  49952. _this._target = _this._effectiveTarget = target;
  49953. return _this;
  49954. }
  49955. SetValueAction.prototype._prepare = function () {
  49956. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49957. this._property = this._getProperty(this.propertyPath);
  49958. };
  49959. SetValueAction.prototype.execute = function () {
  49960. this._effectiveTarget[this._property] = this.value;
  49961. if (this._target.markAsDirty) {
  49962. this._target.markAsDirty(this._property);
  49963. }
  49964. };
  49965. SetValueAction.prototype.serialize = function (parent) {
  49966. return _super.prototype._serialize.call(this, {
  49967. name: "SetValueAction",
  49968. properties: [
  49969. BABYLON.Action._GetTargetProperty(this._target),
  49970. { name: "propertyPath", value: this.propertyPath },
  49971. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49972. ]
  49973. }, parent);
  49974. };
  49975. return SetValueAction;
  49976. }(BABYLON.Action));
  49977. BABYLON.SetValueAction = SetValueAction;
  49978. var IncrementValueAction = /** @class */ (function (_super) {
  49979. __extends(IncrementValueAction, _super);
  49980. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49981. var _this = _super.call(this, triggerOptions, condition) || this;
  49982. _this.propertyPath = propertyPath;
  49983. _this.value = value;
  49984. _this._target = _this._effectiveTarget = target;
  49985. return _this;
  49986. }
  49987. IncrementValueAction.prototype._prepare = function () {
  49988. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49989. this._property = this._getProperty(this.propertyPath);
  49990. if (typeof this._effectiveTarget[this._property] !== "number") {
  49991. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49992. }
  49993. };
  49994. IncrementValueAction.prototype.execute = function () {
  49995. this._effectiveTarget[this._property] += this.value;
  49996. if (this._target.markAsDirty) {
  49997. this._target.markAsDirty(this._property);
  49998. }
  49999. };
  50000. IncrementValueAction.prototype.serialize = function (parent) {
  50001. return _super.prototype._serialize.call(this, {
  50002. name: "IncrementValueAction",
  50003. properties: [
  50004. BABYLON.Action._GetTargetProperty(this._target),
  50005. { name: "propertyPath", value: this.propertyPath },
  50006. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  50007. ]
  50008. }, parent);
  50009. };
  50010. return IncrementValueAction;
  50011. }(BABYLON.Action));
  50012. BABYLON.IncrementValueAction = IncrementValueAction;
  50013. var PlayAnimationAction = /** @class */ (function (_super) {
  50014. __extends(PlayAnimationAction, _super);
  50015. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  50016. var _this = _super.call(this, triggerOptions, condition) || this;
  50017. _this.from = from;
  50018. _this.to = to;
  50019. _this.loop = loop;
  50020. _this._target = target;
  50021. return _this;
  50022. }
  50023. PlayAnimationAction.prototype._prepare = function () {
  50024. };
  50025. PlayAnimationAction.prototype.execute = function () {
  50026. var scene = this._actionManager.getScene();
  50027. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  50028. };
  50029. PlayAnimationAction.prototype.serialize = function (parent) {
  50030. return _super.prototype._serialize.call(this, {
  50031. name: "PlayAnimationAction",
  50032. properties: [
  50033. BABYLON.Action._GetTargetProperty(this._target),
  50034. { name: "from", value: String(this.from) },
  50035. { name: "to", value: String(this.to) },
  50036. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  50037. ]
  50038. }, parent);
  50039. };
  50040. return PlayAnimationAction;
  50041. }(BABYLON.Action));
  50042. BABYLON.PlayAnimationAction = PlayAnimationAction;
  50043. var StopAnimationAction = /** @class */ (function (_super) {
  50044. __extends(StopAnimationAction, _super);
  50045. function StopAnimationAction(triggerOptions, target, condition) {
  50046. var _this = _super.call(this, triggerOptions, condition) || this;
  50047. _this._target = target;
  50048. return _this;
  50049. }
  50050. StopAnimationAction.prototype._prepare = function () {
  50051. };
  50052. StopAnimationAction.prototype.execute = function () {
  50053. var scene = this._actionManager.getScene();
  50054. scene.stopAnimation(this._target);
  50055. };
  50056. StopAnimationAction.prototype.serialize = function (parent) {
  50057. return _super.prototype._serialize.call(this, {
  50058. name: "StopAnimationAction",
  50059. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  50060. }, parent);
  50061. };
  50062. return StopAnimationAction;
  50063. }(BABYLON.Action));
  50064. BABYLON.StopAnimationAction = StopAnimationAction;
  50065. var DoNothingAction = /** @class */ (function (_super) {
  50066. __extends(DoNothingAction, _super);
  50067. function DoNothingAction(triggerOptions, condition) {
  50068. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  50069. return _super.call(this, triggerOptions, condition) || this;
  50070. }
  50071. DoNothingAction.prototype.execute = function () {
  50072. };
  50073. DoNothingAction.prototype.serialize = function (parent) {
  50074. return _super.prototype._serialize.call(this, {
  50075. name: "DoNothingAction",
  50076. properties: []
  50077. }, parent);
  50078. };
  50079. return DoNothingAction;
  50080. }(BABYLON.Action));
  50081. BABYLON.DoNothingAction = DoNothingAction;
  50082. var CombineAction = /** @class */ (function (_super) {
  50083. __extends(CombineAction, _super);
  50084. function CombineAction(triggerOptions, children, condition) {
  50085. var _this = _super.call(this, triggerOptions, condition) || this;
  50086. _this.children = children;
  50087. return _this;
  50088. }
  50089. CombineAction.prototype._prepare = function () {
  50090. for (var index = 0; index < this.children.length; index++) {
  50091. this.children[index]._actionManager = this._actionManager;
  50092. this.children[index]._prepare();
  50093. }
  50094. };
  50095. CombineAction.prototype.execute = function (evt) {
  50096. for (var index = 0; index < this.children.length; index++) {
  50097. this.children[index].execute(evt);
  50098. }
  50099. };
  50100. CombineAction.prototype.serialize = function (parent) {
  50101. var serializationObject = _super.prototype._serialize.call(this, {
  50102. name: "CombineAction",
  50103. properties: [],
  50104. combine: []
  50105. }, parent);
  50106. for (var i = 0; i < this.children.length; i++) {
  50107. serializationObject.combine.push(this.children[i].serialize(null));
  50108. }
  50109. return serializationObject;
  50110. };
  50111. return CombineAction;
  50112. }(BABYLON.Action));
  50113. BABYLON.CombineAction = CombineAction;
  50114. var ExecuteCodeAction = /** @class */ (function (_super) {
  50115. __extends(ExecuteCodeAction, _super);
  50116. function ExecuteCodeAction(triggerOptions, func, condition) {
  50117. var _this = _super.call(this, triggerOptions, condition) || this;
  50118. _this.func = func;
  50119. return _this;
  50120. }
  50121. ExecuteCodeAction.prototype.execute = function (evt) {
  50122. this.func(evt);
  50123. };
  50124. return ExecuteCodeAction;
  50125. }(BABYLON.Action));
  50126. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  50127. var SetParentAction = /** @class */ (function (_super) {
  50128. __extends(SetParentAction, _super);
  50129. function SetParentAction(triggerOptions, target, parent, condition) {
  50130. var _this = _super.call(this, triggerOptions, condition) || this;
  50131. _this._target = target;
  50132. _this._parent = parent;
  50133. return _this;
  50134. }
  50135. SetParentAction.prototype._prepare = function () {
  50136. };
  50137. SetParentAction.prototype.execute = function () {
  50138. if (this._target.parent === this._parent) {
  50139. return;
  50140. }
  50141. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  50142. invertParentWorldMatrix.invert();
  50143. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  50144. this._target.parent = this._parent;
  50145. };
  50146. SetParentAction.prototype.serialize = function (parent) {
  50147. return _super.prototype._serialize.call(this, {
  50148. name: "SetParentAction",
  50149. properties: [
  50150. BABYLON.Action._GetTargetProperty(this._target),
  50151. BABYLON.Action._GetTargetProperty(this._parent),
  50152. ]
  50153. }, parent);
  50154. };
  50155. return SetParentAction;
  50156. }(BABYLON.Action));
  50157. BABYLON.SetParentAction = SetParentAction;
  50158. var PlaySoundAction = /** @class */ (function (_super) {
  50159. __extends(PlaySoundAction, _super);
  50160. function PlaySoundAction(triggerOptions, sound, condition) {
  50161. var _this = _super.call(this, triggerOptions, condition) || this;
  50162. _this._sound = sound;
  50163. return _this;
  50164. }
  50165. PlaySoundAction.prototype._prepare = function () {
  50166. };
  50167. PlaySoundAction.prototype.execute = function () {
  50168. if (this._sound !== undefined)
  50169. this._sound.play();
  50170. };
  50171. PlaySoundAction.prototype.serialize = function (parent) {
  50172. return _super.prototype._serialize.call(this, {
  50173. name: "PlaySoundAction",
  50174. properties: [{ name: "sound", value: this._sound.name }]
  50175. }, parent);
  50176. };
  50177. return PlaySoundAction;
  50178. }(BABYLON.Action));
  50179. BABYLON.PlaySoundAction = PlaySoundAction;
  50180. var StopSoundAction = /** @class */ (function (_super) {
  50181. __extends(StopSoundAction, _super);
  50182. function StopSoundAction(triggerOptions, sound, condition) {
  50183. var _this = _super.call(this, triggerOptions, condition) || this;
  50184. _this._sound = sound;
  50185. return _this;
  50186. }
  50187. StopSoundAction.prototype._prepare = function () {
  50188. };
  50189. StopSoundAction.prototype.execute = function () {
  50190. if (this._sound !== undefined)
  50191. this._sound.stop();
  50192. };
  50193. StopSoundAction.prototype.serialize = function (parent) {
  50194. return _super.prototype._serialize.call(this, {
  50195. name: "StopSoundAction",
  50196. properties: [{ name: "sound", value: this._sound.name }]
  50197. }, parent);
  50198. };
  50199. return StopSoundAction;
  50200. }(BABYLON.Action));
  50201. BABYLON.StopSoundAction = StopSoundAction;
  50202. })(BABYLON || (BABYLON = {}));
  50203. //# sourceMappingURL=babylon.directActions.js.map
  50204. "use strict";
  50205. var BABYLON;
  50206. (function (BABYLON) {
  50207. var SpriteManager = /** @class */ (function () {
  50208. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  50209. if (epsilon === void 0) { epsilon = 0.01; }
  50210. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50211. this.name = name;
  50212. this.sprites = new Array();
  50213. this.renderingGroupId = 0;
  50214. this.layerMask = 0x0FFFFFFF;
  50215. this.fogEnabled = true;
  50216. this.isPickable = false;
  50217. /**
  50218. * An event triggered when the manager is disposed.
  50219. * @type {BABYLON.Observable}
  50220. */
  50221. this.onDisposeObservable = new BABYLON.Observable();
  50222. this._vertexBuffers = {};
  50223. this._capacity = capacity;
  50224. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  50225. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50226. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50227. if (cellSize.width && cellSize.height) {
  50228. this.cellWidth = cellSize.width;
  50229. this.cellHeight = cellSize.height;
  50230. }
  50231. else if (cellSize !== undefined) {
  50232. this.cellWidth = cellSize;
  50233. this.cellHeight = cellSize;
  50234. }
  50235. else {
  50236. return;
  50237. }
  50238. this._epsilon = epsilon;
  50239. this._scene = scene;
  50240. this._scene.spriteManagers.push(this);
  50241. var indices = [];
  50242. var index = 0;
  50243. for (var count = 0; count < capacity; count++) {
  50244. indices.push(index);
  50245. indices.push(index + 1);
  50246. indices.push(index + 2);
  50247. indices.push(index);
  50248. indices.push(index + 2);
  50249. indices.push(index + 3);
  50250. index += 4;
  50251. }
  50252. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50253. // VBO
  50254. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50255. this._vertexData = new Float32Array(capacity * 16 * 4);
  50256. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50257. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50258. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50259. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50260. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50261. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50262. this._vertexBuffers["options"] = options;
  50263. this._vertexBuffers["cellInfo"] = cellInfo;
  50264. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50265. // Effects
  50266. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50267. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50268. }
  50269. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50270. set: function (callback) {
  50271. if (this._onDisposeObserver) {
  50272. this.onDisposeObservable.remove(this._onDisposeObserver);
  50273. }
  50274. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50275. },
  50276. enumerable: true,
  50277. configurable: true
  50278. });
  50279. Object.defineProperty(SpriteManager.prototype, "texture", {
  50280. get: function () {
  50281. return this._spriteTexture;
  50282. },
  50283. set: function (value) {
  50284. this._spriteTexture = value;
  50285. },
  50286. enumerable: true,
  50287. configurable: true
  50288. });
  50289. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50290. var arrayOffset = index * 16;
  50291. if (offsetX === 0)
  50292. offsetX = this._epsilon;
  50293. else if (offsetX === 1)
  50294. offsetX = 1 - this._epsilon;
  50295. if (offsetY === 0)
  50296. offsetY = this._epsilon;
  50297. else if (offsetY === 1)
  50298. offsetY = 1 - this._epsilon;
  50299. this._vertexData[arrayOffset] = sprite.position.x;
  50300. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50301. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50302. this._vertexData[arrayOffset + 3] = sprite.angle;
  50303. this._vertexData[arrayOffset + 4] = sprite.width;
  50304. this._vertexData[arrayOffset + 5] = sprite.height;
  50305. this._vertexData[arrayOffset + 6] = offsetX;
  50306. this._vertexData[arrayOffset + 7] = offsetY;
  50307. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50308. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50309. var offset = (sprite.cellIndex / rowSize) >> 0;
  50310. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50311. this._vertexData[arrayOffset + 11] = offset;
  50312. // Color
  50313. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50314. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50315. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50316. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50317. };
  50318. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50319. var count = Math.min(this._capacity, this.sprites.length);
  50320. var min = BABYLON.Vector3.Zero();
  50321. var max = BABYLON.Vector3.Zero();
  50322. var distance = Number.MAX_VALUE;
  50323. var currentSprite = null;
  50324. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50325. var cameraView = camera.getViewMatrix();
  50326. for (var index = 0; index < count; index++) {
  50327. var sprite = this.sprites[index];
  50328. if (!sprite) {
  50329. continue;
  50330. }
  50331. if (predicate) {
  50332. if (!predicate(sprite)) {
  50333. continue;
  50334. }
  50335. }
  50336. else if (!sprite.isPickable) {
  50337. continue;
  50338. }
  50339. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50340. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50341. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50342. if (ray.intersectsBoxMinMax(min, max)) {
  50343. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50344. if (distance > currentDistance) {
  50345. distance = currentDistance;
  50346. currentSprite = sprite;
  50347. if (fastCheck) {
  50348. break;
  50349. }
  50350. }
  50351. }
  50352. }
  50353. if (currentSprite) {
  50354. var result = new BABYLON.PickingInfo();
  50355. result.hit = true;
  50356. result.pickedSprite = currentSprite;
  50357. result.distance = distance;
  50358. return result;
  50359. }
  50360. return null;
  50361. };
  50362. SpriteManager.prototype.render = function () {
  50363. // Check
  50364. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50365. return;
  50366. var engine = this._scene.getEngine();
  50367. var baseSize = this._spriteTexture.getBaseSize();
  50368. // Sprites
  50369. var deltaTime = engine.getDeltaTime();
  50370. var max = Math.min(this._capacity, this.sprites.length);
  50371. var rowSize = baseSize.width / this.cellWidth;
  50372. var offset = 0;
  50373. for (var index = 0; index < max; index++) {
  50374. var sprite = this.sprites[index];
  50375. if (!sprite) {
  50376. continue;
  50377. }
  50378. sprite._animate(deltaTime);
  50379. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50380. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50381. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50382. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50383. }
  50384. this._buffer.update(this._vertexData);
  50385. // Render
  50386. var effect = this._effectBase;
  50387. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50388. effect = this._effectFog;
  50389. }
  50390. engine.enableEffect(effect);
  50391. var viewMatrix = this._scene.getViewMatrix();
  50392. effect.setTexture("diffuseSampler", this._spriteTexture);
  50393. effect.setMatrix("view", viewMatrix);
  50394. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50395. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50396. // Fog
  50397. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50398. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50399. effect.setColor3("vFogColor", this._scene.fogColor);
  50400. }
  50401. // VBOs
  50402. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50403. // Draw order
  50404. engine.setDepthFunctionToLessOrEqual();
  50405. effect.setBool("alphaTest", true);
  50406. engine.setColorWrite(false);
  50407. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50408. engine.setColorWrite(true);
  50409. effect.setBool("alphaTest", false);
  50410. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50411. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50412. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50413. };
  50414. SpriteManager.prototype.dispose = function () {
  50415. if (this._buffer) {
  50416. this._buffer.dispose();
  50417. this._buffer = null;
  50418. }
  50419. if (this._indexBuffer) {
  50420. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50421. this._indexBuffer = null;
  50422. }
  50423. if (this._spriteTexture) {
  50424. this._spriteTexture.dispose();
  50425. this._spriteTexture = null;
  50426. }
  50427. // Remove from scene
  50428. var index = this._scene.spriteManagers.indexOf(this);
  50429. this._scene.spriteManagers.splice(index, 1);
  50430. // Callback
  50431. this.onDisposeObservable.notifyObservers(this);
  50432. this.onDisposeObservable.clear();
  50433. };
  50434. return SpriteManager;
  50435. }());
  50436. BABYLON.SpriteManager = SpriteManager;
  50437. })(BABYLON || (BABYLON = {}));
  50438. //# sourceMappingURL=babylon.spriteManager.js.map
  50439. "use strict";
  50440. var BABYLON;
  50441. (function (BABYLON) {
  50442. var Sprite = /** @class */ (function () {
  50443. function Sprite(name, manager) {
  50444. this.name = name;
  50445. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50446. this.width = 1.0;
  50447. this.height = 1.0;
  50448. this.angle = 0;
  50449. this.cellIndex = 0;
  50450. this.invertU = 0;
  50451. this.invertV = 0;
  50452. this.animations = new Array();
  50453. this.isPickable = false;
  50454. this._animationStarted = false;
  50455. this._loopAnimation = false;
  50456. this._fromIndex = 0;
  50457. this._toIndex = 0;
  50458. this._delay = 0;
  50459. this._direction = 1;
  50460. this._time = 0;
  50461. this._manager = manager;
  50462. this._manager.sprites.push(this);
  50463. this.position = BABYLON.Vector3.Zero();
  50464. }
  50465. Object.defineProperty(Sprite.prototype, "size", {
  50466. get: function () {
  50467. return this.width;
  50468. },
  50469. set: function (value) {
  50470. this.width = value;
  50471. this.height = value;
  50472. },
  50473. enumerable: true,
  50474. configurable: true
  50475. });
  50476. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50477. this._fromIndex = from;
  50478. this._toIndex = to;
  50479. this._loopAnimation = loop;
  50480. this._delay = delay;
  50481. this._animationStarted = true;
  50482. this._direction = from < to ? 1 : -1;
  50483. this.cellIndex = from;
  50484. this._time = 0;
  50485. this._onAnimationEnd = onAnimationEnd;
  50486. };
  50487. Sprite.prototype.stopAnimation = function () {
  50488. this._animationStarted = false;
  50489. };
  50490. Sprite.prototype._animate = function (deltaTime) {
  50491. if (!this._animationStarted)
  50492. return;
  50493. this._time += deltaTime;
  50494. if (this._time > this._delay) {
  50495. this._time = this._time % this._delay;
  50496. this.cellIndex += this._direction;
  50497. if (this.cellIndex > this._toIndex) {
  50498. if (this._loopAnimation) {
  50499. this.cellIndex = this._fromIndex;
  50500. }
  50501. else {
  50502. this.cellIndex = this._toIndex;
  50503. this._animationStarted = false;
  50504. if (this._onAnimationEnd) {
  50505. this._onAnimationEnd();
  50506. }
  50507. if (this.disposeWhenFinishedAnimating) {
  50508. this.dispose();
  50509. }
  50510. }
  50511. }
  50512. }
  50513. };
  50514. Sprite.prototype.dispose = function () {
  50515. for (var i = 0; i < this._manager.sprites.length; i++) {
  50516. if (this._manager.sprites[i] == this) {
  50517. this._manager.sprites.splice(i, 1);
  50518. }
  50519. }
  50520. };
  50521. return Sprite;
  50522. }());
  50523. BABYLON.Sprite = Sprite;
  50524. })(BABYLON || (BABYLON = {}));
  50525. //# sourceMappingURL=babylon.sprite.js.map
  50526. "use strict";
  50527. var BABYLON;
  50528. (function (BABYLON) {
  50529. var IntersectionInfo = /** @class */ (function () {
  50530. function IntersectionInfo(bu, bv, distance) {
  50531. this.bu = bu;
  50532. this.bv = bv;
  50533. this.distance = distance;
  50534. this.faceId = 0;
  50535. this.subMeshId = 0;
  50536. }
  50537. return IntersectionInfo;
  50538. }());
  50539. BABYLON.IntersectionInfo = IntersectionInfo;
  50540. var PickingInfo = /** @class */ (function () {
  50541. function PickingInfo() {
  50542. this.hit = false;
  50543. this.distance = 0;
  50544. this.pickedPoint = null;
  50545. this.pickedMesh = null;
  50546. this.bu = 0;
  50547. this.bv = 0;
  50548. this.faceId = -1;
  50549. this.subMeshId = 0;
  50550. this.pickedSprite = null;
  50551. }
  50552. // Methods
  50553. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50554. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50555. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50556. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50557. return null;
  50558. }
  50559. var indices = this.pickedMesh.getIndices();
  50560. if (!indices) {
  50561. return null;
  50562. }
  50563. var result;
  50564. if (useVerticesNormals) {
  50565. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50566. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50567. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50568. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50569. normal0 = normal0.scale(this.bu);
  50570. normal1 = normal1.scale(this.bv);
  50571. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50572. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50573. }
  50574. else {
  50575. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50576. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50577. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50578. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50579. var p1p2 = vertex1.subtract(vertex2);
  50580. var p3p2 = vertex3.subtract(vertex2);
  50581. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50582. }
  50583. if (useWorldCoordinates) {
  50584. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50585. }
  50586. return BABYLON.Vector3.Normalize(result);
  50587. };
  50588. PickingInfo.prototype.getTextureCoordinates = function () {
  50589. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50590. return null;
  50591. }
  50592. var indices = this.pickedMesh.getIndices();
  50593. if (!indices) {
  50594. return null;
  50595. }
  50596. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50597. if (!uvs) {
  50598. return null;
  50599. }
  50600. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50601. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50602. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50603. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50604. uv1 = uv1.scale(this.bu);
  50605. uv2 = uv2.scale(this.bv);
  50606. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50607. };
  50608. return PickingInfo;
  50609. }());
  50610. BABYLON.PickingInfo = PickingInfo;
  50611. })(BABYLON || (BABYLON = {}));
  50612. //# sourceMappingURL=babylon.pickingInfo.js.map
  50613. "use strict";
  50614. var BABYLON;
  50615. (function (BABYLON) {
  50616. var Ray = /** @class */ (function () {
  50617. function Ray(origin, direction, length) {
  50618. if (length === void 0) { length = Number.MAX_VALUE; }
  50619. this.origin = origin;
  50620. this.direction = direction;
  50621. this.length = length;
  50622. }
  50623. // Methods
  50624. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50625. var d = 0.0;
  50626. var maxValue = Number.MAX_VALUE;
  50627. var inv;
  50628. var min;
  50629. var max;
  50630. var temp;
  50631. if (Math.abs(this.direction.x) < 0.0000001) {
  50632. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50633. return false;
  50634. }
  50635. }
  50636. else {
  50637. inv = 1.0 / this.direction.x;
  50638. min = (minimum.x - this.origin.x) * inv;
  50639. max = (maximum.x - this.origin.x) * inv;
  50640. if (max === -Infinity) {
  50641. max = Infinity;
  50642. }
  50643. if (min > max) {
  50644. temp = min;
  50645. min = max;
  50646. max = temp;
  50647. }
  50648. d = Math.max(min, d);
  50649. maxValue = Math.min(max, maxValue);
  50650. if (d > maxValue) {
  50651. return false;
  50652. }
  50653. }
  50654. if (Math.abs(this.direction.y) < 0.0000001) {
  50655. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50656. return false;
  50657. }
  50658. }
  50659. else {
  50660. inv = 1.0 / this.direction.y;
  50661. min = (minimum.y - this.origin.y) * inv;
  50662. max = (maximum.y - this.origin.y) * inv;
  50663. if (max === -Infinity) {
  50664. max = Infinity;
  50665. }
  50666. if (min > max) {
  50667. temp = min;
  50668. min = max;
  50669. max = temp;
  50670. }
  50671. d = Math.max(min, d);
  50672. maxValue = Math.min(max, maxValue);
  50673. if (d > maxValue) {
  50674. return false;
  50675. }
  50676. }
  50677. if (Math.abs(this.direction.z) < 0.0000001) {
  50678. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50679. return false;
  50680. }
  50681. }
  50682. else {
  50683. inv = 1.0 / this.direction.z;
  50684. min = (minimum.z - this.origin.z) * inv;
  50685. max = (maximum.z - this.origin.z) * inv;
  50686. if (max === -Infinity) {
  50687. max = Infinity;
  50688. }
  50689. if (min > max) {
  50690. temp = min;
  50691. min = max;
  50692. max = temp;
  50693. }
  50694. d = Math.max(min, d);
  50695. maxValue = Math.min(max, maxValue);
  50696. if (d > maxValue) {
  50697. return false;
  50698. }
  50699. }
  50700. return true;
  50701. };
  50702. Ray.prototype.intersectsBox = function (box) {
  50703. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50704. };
  50705. Ray.prototype.intersectsSphere = function (sphere) {
  50706. var x = sphere.center.x - this.origin.x;
  50707. var y = sphere.center.y - this.origin.y;
  50708. var z = sphere.center.z - this.origin.z;
  50709. var pyth = (x * x) + (y * y) + (z * z);
  50710. var rr = sphere.radius * sphere.radius;
  50711. if (pyth <= rr) {
  50712. return true;
  50713. }
  50714. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50715. if (dot < 0.0) {
  50716. return false;
  50717. }
  50718. var temp = pyth - (dot * dot);
  50719. return temp <= rr;
  50720. };
  50721. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50722. if (!this._edge1) {
  50723. this._edge1 = BABYLON.Vector3.Zero();
  50724. this._edge2 = BABYLON.Vector3.Zero();
  50725. this._pvec = BABYLON.Vector3.Zero();
  50726. this._tvec = BABYLON.Vector3.Zero();
  50727. this._qvec = BABYLON.Vector3.Zero();
  50728. }
  50729. vertex1.subtractToRef(vertex0, this._edge1);
  50730. vertex2.subtractToRef(vertex0, this._edge2);
  50731. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50732. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50733. if (det === 0) {
  50734. return null;
  50735. }
  50736. var invdet = 1 / det;
  50737. this.origin.subtractToRef(vertex0, this._tvec);
  50738. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50739. if (bu < 0 || bu > 1.0) {
  50740. return null;
  50741. }
  50742. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50743. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50744. if (bv < 0 || bu + bv > 1.0) {
  50745. return null;
  50746. }
  50747. //check if the distance is longer than the predefined length.
  50748. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50749. if (distance > this.length) {
  50750. return null;
  50751. }
  50752. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50753. };
  50754. Ray.prototype.intersectsPlane = function (plane) {
  50755. var distance;
  50756. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50757. if (Math.abs(result1) < 9.99999997475243E-07) {
  50758. return null;
  50759. }
  50760. else {
  50761. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50762. distance = (-plane.d - result2) / result1;
  50763. if (distance < 0.0) {
  50764. if (distance < -9.99999997475243E-07) {
  50765. return null;
  50766. }
  50767. else {
  50768. return 0;
  50769. }
  50770. }
  50771. return distance;
  50772. }
  50773. };
  50774. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50775. var tm = BABYLON.Tmp.Matrix[0];
  50776. mesh.getWorldMatrix().invertToRef(tm);
  50777. if (this._tmpRay) {
  50778. Ray.TransformToRef(this, tm, this._tmpRay);
  50779. }
  50780. else {
  50781. this._tmpRay = Ray.Transform(this, tm);
  50782. }
  50783. return mesh.intersects(this._tmpRay, fastCheck);
  50784. };
  50785. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50786. if (results) {
  50787. results.length = 0;
  50788. }
  50789. else {
  50790. results = [];
  50791. }
  50792. for (var i = 0; i < meshes.length; i++) {
  50793. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50794. if (pickInfo.hit) {
  50795. results.push(pickInfo);
  50796. }
  50797. }
  50798. results.sort(this._comparePickingInfo);
  50799. return results;
  50800. };
  50801. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50802. if (pickingInfoA.distance < pickingInfoB.distance) {
  50803. return -1;
  50804. }
  50805. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50806. return 1;
  50807. }
  50808. else {
  50809. return 0;
  50810. }
  50811. };
  50812. /**
  50813. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50814. * @param sega the first point of the segment to test the intersection against
  50815. * @param segb the second point of the segment to test the intersection against
  50816. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50817. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50818. */
  50819. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50820. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50821. var u = segb.subtract(sega);
  50822. var v = rsegb.subtract(this.origin);
  50823. var w = sega.subtract(this.origin);
  50824. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50825. var b = BABYLON.Vector3.Dot(u, v);
  50826. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50827. var d = BABYLON.Vector3.Dot(u, w);
  50828. var e = BABYLON.Vector3.Dot(v, w);
  50829. var D = a * c - b * b; // always >= 0
  50830. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50831. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50832. // compute the line parameters of the two closest points
  50833. if (D < Ray.smallnum) {
  50834. sN = 0.0; // force using point P0 on segment S1
  50835. sD = 1.0; // to prevent possible division by 0.0 later
  50836. tN = e;
  50837. tD = c;
  50838. }
  50839. else {
  50840. sN = (b * e - c * d);
  50841. tN = (a * e - b * d);
  50842. if (sN < 0.0) {
  50843. sN = 0.0;
  50844. tN = e;
  50845. tD = c;
  50846. }
  50847. else if (sN > sD) {
  50848. sN = sD;
  50849. tN = e + b;
  50850. tD = c;
  50851. }
  50852. }
  50853. if (tN < 0.0) {
  50854. tN = 0.0;
  50855. // recompute sc for this edge
  50856. if (-d < 0.0) {
  50857. sN = 0.0;
  50858. }
  50859. else if (-d > a)
  50860. sN = sD;
  50861. else {
  50862. sN = -d;
  50863. sD = a;
  50864. }
  50865. }
  50866. else if (tN > tD) {
  50867. tN = tD;
  50868. // recompute sc for this edge
  50869. if ((-d + b) < 0.0) {
  50870. sN = 0;
  50871. }
  50872. else if ((-d + b) > a) {
  50873. sN = sD;
  50874. }
  50875. else {
  50876. sN = (-d + b);
  50877. sD = a;
  50878. }
  50879. }
  50880. // finally do the division to get sc and tc
  50881. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50882. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50883. // get the difference of the two closest points
  50884. var qtc = v.multiplyByFloats(tc, tc, tc);
  50885. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50886. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50887. if (isIntersected) {
  50888. return qtc.length();
  50889. }
  50890. return -1;
  50891. };
  50892. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50893. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50894. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50895. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50896. this.direction.normalize();
  50897. return this;
  50898. };
  50899. // Statics
  50900. Ray.Zero = function () {
  50901. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50902. };
  50903. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50904. var result = Ray.Zero();
  50905. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50906. };
  50907. /**
  50908. * 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
  50909. * transformed to the given world matrix.
  50910. * @param origin The origin point
  50911. * @param end The end point
  50912. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50913. */
  50914. Ray.CreateNewFromTo = function (origin, end, world) {
  50915. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50916. var direction = end.subtract(origin);
  50917. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50918. direction.normalize();
  50919. return Ray.Transform(new Ray(origin, direction, length), world);
  50920. };
  50921. Ray.Transform = function (ray, matrix) {
  50922. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50923. Ray.TransformToRef(ray, matrix, result);
  50924. return result;
  50925. };
  50926. Ray.TransformToRef = function (ray, matrix, result) {
  50927. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50928. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50929. result.length = ray.length;
  50930. var dir = result.direction;
  50931. var len = dir.length();
  50932. if (!(len === 0 || len === 1)) {
  50933. var num = 1.0 / len;
  50934. dir.x *= num;
  50935. dir.y *= num;
  50936. dir.z *= num;
  50937. result.length *= len;
  50938. }
  50939. };
  50940. Ray.smallnum = 0.00000001;
  50941. Ray.rayl = 10e8;
  50942. return Ray;
  50943. }());
  50944. BABYLON.Ray = Ray;
  50945. })(BABYLON || (BABYLON = {}));
  50946. //# sourceMappingURL=babylon.ray.js.map
  50947. "use strict";
  50948. var BABYLON;
  50949. (function (BABYLON) {
  50950. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50951. if (boxMin.x > sphereCenter.x + sphereRadius)
  50952. return false;
  50953. if (sphereCenter.x - sphereRadius > boxMax.x)
  50954. return false;
  50955. if (boxMin.y > sphereCenter.y + sphereRadius)
  50956. return false;
  50957. if (sphereCenter.y - sphereRadius > boxMax.y)
  50958. return false;
  50959. if (boxMin.z > sphereCenter.z + sphereRadius)
  50960. return false;
  50961. if (sphereCenter.z - sphereRadius > boxMax.z)
  50962. return false;
  50963. return true;
  50964. };
  50965. var getLowestRoot = (function () {
  50966. var result = { root: 0, found: false };
  50967. return function (a, b, c, maxR) {
  50968. result.root = 0;
  50969. result.found = false;
  50970. var determinant = b * b - 4.0 * a * c;
  50971. if (determinant < 0)
  50972. return result;
  50973. var sqrtD = Math.sqrt(determinant);
  50974. var r1 = (-b - sqrtD) / (2.0 * a);
  50975. var r2 = (-b + sqrtD) / (2.0 * a);
  50976. if (r1 > r2) {
  50977. var temp = r2;
  50978. r2 = r1;
  50979. r1 = temp;
  50980. }
  50981. if (r1 > 0 && r1 < maxR) {
  50982. result.root = r1;
  50983. result.found = true;
  50984. return result;
  50985. }
  50986. if (r2 > 0 && r2 < maxR) {
  50987. result.root = r2;
  50988. result.found = true;
  50989. return result;
  50990. }
  50991. return result;
  50992. };
  50993. })();
  50994. var Collider = /** @class */ (function () {
  50995. function Collider() {
  50996. this._collisionPoint = BABYLON.Vector3.Zero();
  50997. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50998. this._tempVector = BABYLON.Vector3.Zero();
  50999. this._tempVector2 = BABYLON.Vector3.Zero();
  51000. this._tempVector3 = BABYLON.Vector3.Zero();
  51001. this._tempVector4 = BABYLON.Vector3.Zero();
  51002. this._edge = BABYLON.Vector3.Zero();
  51003. this._baseToVertex = BABYLON.Vector3.Zero();
  51004. this._destinationPoint = BABYLON.Vector3.Zero();
  51005. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  51006. this._displacementVector = BABYLON.Vector3.Zero();
  51007. this._radius = BABYLON.Vector3.One();
  51008. this._retry = 0;
  51009. this._basePointWorld = BABYLON.Vector3.Zero();
  51010. this._velocityWorld = BABYLON.Vector3.Zero();
  51011. this._normalizedVelocity = BABYLON.Vector3.Zero();
  51012. this._collisionMask = -1;
  51013. }
  51014. Object.defineProperty(Collider.prototype, "collisionMask", {
  51015. get: function () {
  51016. return this._collisionMask;
  51017. },
  51018. set: function (mask) {
  51019. this._collisionMask = !isNaN(mask) ? mask : -1;
  51020. },
  51021. enumerable: true,
  51022. configurable: true
  51023. });
  51024. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  51025. /**
  51026. * Gets the plane normal used to compute the sliding response (in local space)
  51027. */
  51028. get: function () {
  51029. return this._slidePlaneNormal;
  51030. },
  51031. enumerable: true,
  51032. configurable: true
  51033. });
  51034. // Methods
  51035. Collider.prototype._initialize = function (source, dir, e) {
  51036. this._velocity = dir;
  51037. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  51038. this._basePoint = source;
  51039. source.multiplyToRef(this._radius, this._basePointWorld);
  51040. dir.multiplyToRef(this._radius, this._velocityWorld);
  51041. this._velocityWorldLength = this._velocityWorld.length();
  51042. this._epsilon = e;
  51043. this.collisionFound = false;
  51044. };
  51045. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  51046. pa.subtractToRef(point, this._tempVector);
  51047. pb.subtractToRef(point, this._tempVector2);
  51048. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  51049. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51050. if (d < 0)
  51051. return false;
  51052. pc.subtractToRef(point, this._tempVector3);
  51053. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  51054. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51055. if (d < 0)
  51056. return false;
  51057. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  51058. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51059. return d >= 0;
  51060. };
  51061. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  51062. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  51063. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  51064. if (distance > this._velocityWorldLength + max + sphereRadius) {
  51065. return false;
  51066. }
  51067. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  51068. return false;
  51069. return true;
  51070. };
  51071. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  51072. var t0;
  51073. var embeddedInPlane = false;
  51074. //defensive programming, actually not needed.
  51075. if (!trianglePlaneArray) {
  51076. trianglePlaneArray = [];
  51077. }
  51078. if (!trianglePlaneArray[faceIndex]) {
  51079. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  51080. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  51081. }
  51082. var trianglePlane = trianglePlaneArray[faceIndex];
  51083. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  51084. return;
  51085. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  51086. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  51087. if (normalDotVelocity == 0) {
  51088. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  51089. return;
  51090. embeddedInPlane = true;
  51091. t0 = 0;
  51092. }
  51093. else {
  51094. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51095. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51096. if (t0 > t1) {
  51097. var temp = t1;
  51098. t1 = t0;
  51099. t0 = temp;
  51100. }
  51101. if (t0 > 1.0 || t1 < 0.0)
  51102. return;
  51103. if (t0 < 0)
  51104. t0 = 0;
  51105. if (t0 > 1.0)
  51106. t0 = 1.0;
  51107. }
  51108. this._collisionPoint.copyFromFloats(0, 0, 0);
  51109. var found = false;
  51110. var t = 1.0;
  51111. if (!embeddedInPlane) {
  51112. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  51113. this._velocity.scaleToRef(t0, this._tempVector);
  51114. this._planeIntersectionPoint.addInPlace(this._tempVector);
  51115. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  51116. found = true;
  51117. t = t0;
  51118. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  51119. }
  51120. }
  51121. if (!found) {
  51122. var velocitySquaredLength = this._velocity.lengthSquared();
  51123. var a = velocitySquaredLength;
  51124. this._basePoint.subtractToRef(p1, this._tempVector);
  51125. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51126. var c = this._tempVector.lengthSquared() - 1.0;
  51127. var lowestRoot = getLowestRoot(a, b, c, t);
  51128. if (lowestRoot.found) {
  51129. t = lowestRoot.root;
  51130. found = true;
  51131. this._collisionPoint.copyFrom(p1);
  51132. }
  51133. this._basePoint.subtractToRef(p2, this._tempVector);
  51134. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51135. c = this._tempVector.lengthSquared() - 1.0;
  51136. lowestRoot = getLowestRoot(a, b, c, t);
  51137. if (lowestRoot.found) {
  51138. t = lowestRoot.root;
  51139. found = true;
  51140. this._collisionPoint.copyFrom(p2);
  51141. }
  51142. this._basePoint.subtractToRef(p3, this._tempVector);
  51143. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51144. c = this._tempVector.lengthSquared() - 1.0;
  51145. lowestRoot = getLowestRoot(a, b, c, t);
  51146. if (lowestRoot.found) {
  51147. t = lowestRoot.root;
  51148. found = true;
  51149. this._collisionPoint.copyFrom(p3);
  51150. }
  51151. p2.subtractToRef(p1, this._edge);
  51152. p1.subtractToRef(this._basePoint, this._baseToVertex);
  51153. var edgeSquaredLength = this._edge.lengthSquared();
  51154. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51155. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51156. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51157. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51158. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51159. lowestRoot = getLowestRoot(a, b, c, t);
  51160. if (lowestRoot.found) {
  51161. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51162. if (f >= 0.0 && f <= 1.0) {
  51163. t = lowestRoot.root;
  51164. found = true;
  51165. this._edge.scaleInPlace(f);
  51166. p1.addToRef(this._edge, this._collisionPoint);
  51167. }
  51168. }
  51169. p3.subtractToRef(p2, this._edge);
  51170. p2.subtractToRef(this._basePoint, this._baseToVertex);
  51171. edgeSquaredLength = this._edge.lengthSquared();
  51172. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51173. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51174. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51175. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51176. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51177. lowestRoot = getLowestRoot(a, b, c, t);
  51178. if (lowestRoot.found) {
  51179. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51180. if (f >= 0.0 && f <= 1.0) {
  51181. t = lowestRoot.root;
  51182. found = true;
  51183. this._edge.scaleInPlace(f);
  51184. p2.addToRef(this._edge, this._collisionPoint);
  51185. }
  51186. }
  51187. p1.subtractToRef(p3, this._edge);
  51188. p3.subtractToRef(this._basePoint, this._baseToVertex);
  51189. edgeSquaredLength = this._edge.lengthSquared();
  51190. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51191. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51192. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51193. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51194. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51195. lowestRoot = getLowestRoot(a, b, c, t);
  51196. if (lowestRoot.found) {
  51197. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51198. if (f >= 0.0 && f <= 1.0) {
  51199. t = lowestRoot.root;
  51200. found = true;
  51201. this._edge.scaleInPlace(f);
  51202. p3.addToRef(this._edge, this._collisionPoint);
  51203. }
  51204. }
  51205. }
  51206. if (found) {
  51207. var distToCollision = t * this._velocity.length();
  51208. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  51209. if (!this.intersectionPoint) {
  51210. this.intersectionPoint = this._collisionPoint.clone();
  51211. }
  51212. else {
  51213. this.intersectionPoint.copyFrom(this._collisionPoint);
  51214. }
  51215. this._nearestDistance = distToCollision;
  51216. this.collisionFound = true;
  51217. }
  51218. }
  51219. };
  51220. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  51221. for (var i = indexStart; i < indexEnd; i += 3) {
  51222. var p1 = pts[indices[i] - decal];
  51223. var p2 = pts[indices[i + 1] - decal];
  51224. var p3 = pts[indices[i + 2] - decal];
  51225. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  51226. }
  51227. };
  51228. Collider.prototype._getResponse = function (pos, vel) {
  51229. pos.addToRef(vel, this._destinationPoint);
  51230. vel.scaleInPlace((this._nearestDistance / vel.length()));
  51231. this._basePoint.addToRef(vel, pos);
  51232. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  51233. this._slidePlaneNormal.normalize();
  51234. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51235. pos.addInPlace(this._displacementVector);
  51236. this.intersectionPoint.addInPlace(this._displacementVector);
  51237. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51238. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51239. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51240. };
  51241. return Collider;
  51242. }());
  51243. BABYLON.Collider = Collider;
  51244. })(BABYLON || (BABYLON = {}));
  51245. //# sourceMappingURL=babylon.collider.js.map
  51246. "use strict";
  51247. var BABYLON;
  51248. (function (BABYLON) {
  51249. //WebWorker code will be inserted to this variable.
  51250. BABYLON.CollisionWorker = "";
  51251. var WorkerTaskType;
  51252. (function (WorkerTaskType) {
  51253. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51254. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51255. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51256. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51257. var WorkerReplyType;
  51258. (function (WorkerReplyType) {
  51259. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51260. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51261. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51262. var CollisionCoordinatorWorker = /** @class */ (function () {
  51263. function CollisionCoordinatorWorker() {
  51264. var _this = this;
  51265. this._scaledPosition = BABYLON.Vector3.Zero();
  51266. this._scaledVelocity = BABYLON.Vector3.Zero();
  51267. this.onMeshUpdated = function (transformNode) {
  51268. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51269. };
  51270. this.onGeometryUpdated = function (geometry) {
  51271. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51272. };
  51273. this._afterRender = function () {
  51274. if (!_this._init)
  51275. return;
  51276. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51277. return;
  51278. }
  51279. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51280. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51281. if (_this._runningUpdated > 4) {
  51282. return;
  51283. }
  51284. ++_this._runningUpdated;
  51285. var payload = {
  51286. updatedMeshes: _this._addUpdateMeshesList,
  51287. updatedGeometries: _this._addUpdateGeometriesList,
  51288. removedGeometries: _this._toRemoveGeometryArray,
  51289. removedMeshes: _this._toRemoveMeshesArray
  51290. };
  51291. var message = {
  51292. payload: payload,
  51293. taskType: WorkerTaskType.UPDATE
  51294. };
  51295. var serializable = [];
  51296. for (var id in payload.updatedGeometries) {
  51297. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51298. //prepare transferables
  51299. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51300. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51301. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51302. }
  51303. }
  51304. _this._worker.postMessage(message, serializable);
  51305. _this._addUpdateMeshesList = {};
  51306. _this._addUpdateGeometriesList = {};
  51307. _this._toRemoveGeometryArray = [];
  51308. _this._toRemoveMeshesArray = [];
  51309. };
  51310. this._onMessageFromWorker = function (e) {
  51311. var returnData = e.data;
  51312. if (returnData.error != WorkerReplyType.SUCCESS) {
  51313. //TODO what errors can be returned from the worker?
  51314. BABYLON.Tools.Warn("error returned from worker!");
  51315. return;
  51316. }
  51317. switch (returnData.taskType) {
  51318. case WorkerTaskType.INIT:
  51319. _this._init = true;
  51320. //Update the worked with ALL of the scene's current state
  51321. _this._scene.meshes.forEach(function (mesh) {
  51322. _this.onMeshAdded(mesh);
  51323. });
  51324. _this._scene.getGeometries().forEach(function (geometry) {
  51325. _this.onGeometryAdded(geometry);
  51326. });
  51327. break;
  51328. case WorkerTaskType.UPDATE:
  51329. _this._runningUpdated--;
  51330. break;
  51331. case WorkerTaskType.COLLIDE:
  51332. var returnPayload = returnData.payload;
  51333. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51334. return;
  51335. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51336. if (callback) {
  51337. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51338. if (mesh) {
  51339. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51340. }
  51341. }
  51342. //cleanup
  51343. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51344. break;
  51345. }
  51346. };
  51347. this._collisionsCallbackArray = [];
  51348. this._init = false;
  51349. this._runningUpdated = 0;
  51350. this._addUpdateMeshesList = {};
  51351. this._addUpdateGeometriesList = {};
  51352. this._toRemoveGeometryArray = [];
  51353. this._toRemoveMeshesArray = [];
  51354. }
  51355. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51356. if (!this._init)
  51357. return;
  51358. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51359. return;
  51360. position.divideToRef(collider._radius, this._scaledPosition);
  51361. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51362. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51363. var payload = {
  51364. collider: {
  51365. position: this._scaledPosition.asArray(),
  51366. velocity: this._scaledVelocity.asArray(),
  51367. radius: collider._radius.asArray()
  51368. },
  51369. collisionId: collisionIndex,
  51370. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51371. maximumRetry: maximumRetry
  51372. };
  51373. var message = {
  51374. payload: payload,
  51375. taskType: WorkerTaskType.COLLIDE
  51376. };
  51377. this._worker.postMessage(message);
  51378. };
  51379. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51380. this._scene = scene;
  51381. this._scene.registerAfterRender(this._afterRender);
  51382. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51383. this._worker = new Worker(workerUrl);
  51384. this._worker.onmessage = this._onMessageFromWorker;
  51385. var message = {
  51386. payload: {},
  51387. taskType: WorkerTaskType.INIT
  51388. };
  51389. this._worker.postMessage(message);
  51390. };
  51391. CollisionCoordinatorWorker.prototype.destroy = function () {
  51392. this._scene.unregisterAfterRender(this._afterRender);
  51393. this._worker.terminate();
  51394. };
  51395. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51396. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51397. this.onMeshUpdated(mesh);
  51398. };
  51399. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51400. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51401. };
  51402. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51403. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51404. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51405. this.onGeometryUpdated(geometry);
  51406. };
  51407. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51408. this._toRemoveGeometryArray.push(geometry.id);
  51409. };
  51410. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51411. var submeshes = [];
  51412. if (mesh.subMeshes) {
  51413. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51414. var boundingInfo = sm.getBoundingInfo();
  51415. return {
  51416. position: idx,
  51417. verticesStart: sm.verticesStart,
  51418. verticesCount: sm.verticesCount,
  51419. indexStart: sm.indexStart,
  51420. indexCount: sm.indexCount,
  51421. hasMaterial: !!sm.getMaterial(),
  51422. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51423. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51424. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51425. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51426. };
  51427. });
  51428. }
  51429. var geometryId = null;
  51430. if (mesh instanceof BABYLON.Mesh) {
  51431. var geometry = mesh.geometry;
  51432. geometryId = geometry ? geometry.id : null;
  51433. }
  51434. else if (mesh instanceof BABYLON.InstancedMesh) {
  51435. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51436. geometryId = geometry ? geometry.id : null;
  51437. }
  51438. var boundingInfo = mesh.getBoundingInfo();
  51439. return {
  51440. uniqueId: mesh.uniqueId,
  51441. id: mesh.id,
  51442. name: mesh.name,
  51443. geometryId: geometryId,
  51444. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51445. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51446. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51447. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51448. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51449. subMeshes: submeshes,
  51450. checkCollisions: mesh.checkCollisions
  51451. };
  51452. };
  51453. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51454. return {
  51455. id: geometry.id,
  51456. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51457. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51458. indices: new Uint32Array(geometry.getIndices() || []),
  51459. };
  51460. };
  51461. return CollisionCoordinatorWorker;
  51462. }());
  51463. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51464. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51465. function CollisionCoordinatorLegacy() {
  51466. this._scaledPosition = BABYLON.Vector3.Zero();
  51467. this._scaledVelocity = BABYLON.Vector3.Zero();
  51468. this._finalPosition = BABYLON.Vector3.Zero();
  51469. }
  51470. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51471. position.divideToRef(collider._radius, this._scaledPosition);
  51472. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51473. collider.collidedMesh = null;
  51474. collider._retry = 0;
  51475. collider._initialVelocity = this._scaledVelocity;
  51476. collider._initialPosition = this._scaledPosition;
  51477. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51478. this._finalPosition.multiplyInPlace(collider._radius);
  51479. //run the callback
  51480. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51481. };
  51482. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51483. this._scene = scene;
  51484. };
  51485. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51486. //Legacy need no destruction method.
  51487. };
  51488. //No update in legacy mode
  51489. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51490. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51491. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51492. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51493. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51494. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51495. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51496. if (excludedMesh === void 0) { excludedMesh = null; }
  51497. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51498. if (collider._retry >= maximumRetry) {
  51499. finalPosition.copyFrom(position);
  51500. return;
  51501. }
  51502. // Check if this is a mesh else camera or -1
  51503. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51504. collider._initialize(position, velocity, closeDistance);
  51505. // Check all meshes
  51506. for (var index = 0; index < this._scene.meshes.length; index++) {
  51507. var mesh = this._scene.meshes[index];
  51508. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51509. mesh._checkCollision(collider);
  51510. }
  51511. }
  51512. if (!collider.collisionFound) {
  51513. position.addToRef(velocity, finalPosition);
  51514. return;
  51515. }
  51516. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51517. collider._getResponse(position, velocity);
  51518. }
  51519. if (velocity.length() <= closeDistance) {
  51520. finalPosition.copyFrom(position);
  51521. return;
  51522. }
  51523. collider._retry++;
  51524. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51525. };
  51526. return CollisionCoordinatorLegacy;
  51527. }());
  51528. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51529. })(BABYLON || (BABYLON = {}));
  51530. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51531. "use strict";
  51532. var BABYLON;
  51533. (function (BABYLON) {
  51534. /**
  51535. * A particle represents one of the element emitted by a particle system.
  51536. * This is mainly define by its coordinates, direction, velocity and age.
  51537. */
  51538. var Particle = /** @class */ (function () {
  51539. /**
  51540. * Creates a new instance of @see Particle
  51541. * @param particleSystem the particle system the particle belongs to
  51542. */
  51543. function Particle(
  51544. /**
  51545. * particleSystem the particle system the particle belongs to.
  51546. */
  51547. particleSystem) {
  51548. this.particleSystem = particleSystem;
  51549. /**
  51550. * The world position of the particle in the scene.
  51551. */
  51552. this.position = BABYLON.Vector3.Zero();
  51553. /**
  51554. * The world direction of the particle in the scene.
  51555. */
  51556. this.direction = BABYLON.Vector3.Zero();
  51557. /**
  51558. * The color of the particle.
  51559. */
  51560. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51561. /**
  51562. * The color change of the particle per step.
  51563. */
  51564. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51565. /**
  51566. * Defines how long will the life of the particle be.
  51567. */
  51568. this.lifeTime = 1.0;
  51569. /**
  51570. * The current age of the particle.
  51571. */
  51572. this.age = 0;
  51573. /**
  51574. * The current size of the particle.
  51575. */
  51576. this.size = 0;
  51577. /**
  51578. * The current angle of the particle.
  51579. */
  51580. this.angle = 0;
  51581. /**
  51582. * Defines how fast is the angle changing.
  51583. */
  51584. this.angularSpeed = 0;
  51585. /**
  51586. * Defines the cell index used by the particle to be rendered from a sprite.
  51587. */
  51588. this.cellIndex = 0;
  51589. this._currentFrameCounter = 0;
  51590. if (!this.particleSystem.isAnimationSheetEnabled) {
  51591. return;
  51592. }
  51593. this.updateCellInfoFromSystem();
  51594. }
  51595. Particle.prototype.updateCellInfoFromSystem = function () {
  51596. this.cellIndex = this.particleSystem.startSpriteCellID;
  51597. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51598. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51599. }
  51600. else {
  51601. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51602. }
  51603. };
  51604. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51605. // (ageOffset / scaledUpdateSpeed) / available cells
  51606. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51607. this._currentFrameCounter += scaledUpdateSpeed;
  51608. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51609. this._currentFrameCounter = 0;
  51610. this.cellIndex++;
  51611. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51612. this.cellIndex = this.particleSystem.endSpriteCellID;
  51613. }
  51614. }
  51615. };
  51616. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51617. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51618. this.cellIndex++;
  51619. this._currentFrameCounter = 0;
  51620. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51621. if (this.particleSystem.spriteCellLoop) {
  51622. this.cellIndex = this.particleSystem.startSpriteCellID;
  51623. }
  51624. else {
  51625. this.cellIndex = this.particleSystem.endSpriteCellID;
  51626. }
  51627. }
  51628. }
  51629. else {
  51630. this._currentFrameCounter++;
  51631. }
  51632. };
  51633. /**
  51634. * Copy the properties of particle to another one.
  51635. * @param other the particle to copy the information to.
  51636. */
  51637. Particle.prototype.copyTo = function (other) {
  51638. other.position.copyFrom(this.position);
  51639. other.direction.copyFrom(this.direction);
  51640. other.color.copyFrom(this.color);
  51641. other.colorStep.copyFrom(this.colorStep);
  51642. other.lifeTime = this.lifeTime;
  51643. other.age = this.age;
  51644. other.size = this.size;
  51645. other.angle = this.angle;
  51646. other.angularSpeed = this.angularSpeed;
  51647. other.particleSystem = this.particleSystem;
  51648. other.cellIndex = this.cellIndex;
  51649. };
  51650. return Particle;
  51651. }());
  51652. BABYLON.Particle = Particle;
  51653. })(BABYLON || (BABYLON = {}));
  51654. //# sourceMappingURL=babylon.particle.js.map
  51655. "use strict";
  51656. var BABYLON;
  51657. (function (BABYLON) {
  51658. /**
  51659. * This represents a particle system in Babylon.
  51660. * 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.
  51661. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51662. * @example https://doc.babylonjs.com/babylon101/particles
  51663. */
  51664. var ParticleSystem = /** @class */ (function () {
  51665. /**
  51666. * Instantiates a particle system.
  51667. * 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.
  51668. * @param name The name of the particle system
  51669. * @param capacity The max number of particles alive at the same time
  51670. * @param scene The scene the particle system belongs to
  51671. * @param customEffect a custom effect used to change the way particles are rendered by default
  51672. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51673. * @param epsilon Offset used to render the particles
  51674. */
  51675. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51676. if (customEffect === void 0) { customEffect = null; }
  51677. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51678. if (epsilon === void 0) { epsilon = 0.01; }
  51679. var _this = this;
  51680. /**
  51681. * List of animations used by the particle system.
  51682. */
  51683. this.animations = [];
  51684. /**
  51685. * The rendering group used by the Particle system to chose when to render.
  51686. */
  51687. this.renderingGroupId = 0;
  51688. /**
  51689. * The emitter represents the Mesh or position we are attaching the particle system to.
  51690. */
  51691. this.emitter = null;
  51692. /**
  51693. * The maximum number of particles to emit per frame
  51694. */
  51695. this.emitRate = 10;
  51696. /**
  51697. * If you want to launch only a few particles at once, that can be done, as well.
  51698. */
  51699. this.manualEmitCount = -1;
  51700. /**
  51701. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51702. */
  51703. this.updateSpeed = 0.01;
  51704. /**
  51705. * The amount of time the particle system is running (depends of the overall update speed).
  51706. */
  51707. this.targetStopDuration = 0;
  51708. /**
  51709. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51710. */
  51711. this.disposeOnStop = false;
  51712. /**
  51713. * Minimum power of emitting particles.
  51714. */
  51715. this.minEmitPower = 1;
  51716. /**
  51717. * Maximum power of emitting particles.
  51718. */
  51719. this.maxEmitPower = 1;
  51720. /**
  51721. * Minimum life time of emitting particles.
  51722. */
  51723. this.minLifeTime = 1;
  51724. /**
  51725. * Maximum life time of emitting particles.
  51726. */
  51727. this.maxLifeTime = 1;
  51728. /**
  51729. * Minimum Size of emitting particles.
  51730. */
  51731. this.minSize = 1;
  51732. /**
  51733. * Maximum Size of emitting particles.
  51734. */
  51735. this.maxSize = 1;
  51736. /**
  51737. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51738. */
  51739. this.minAngularSpeed = 0;
  51740. /**
  51741. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51742. */
  51743. this.maxAngularSpeed = 0;
  51744. /**
  51745. * The layer mask we are rendering the particles through.
  51746. */
  51747. this.layerMask = 0x0FFFFFFF;
  51748. /**
  51749. * This can help using your own shader to render the particle system.
  51750. * The according effect will be created
  51751. */
  51752. this.customShader = null;
  51753. /**
  51754. * By default particle system starts as soon as they are created. This prevents the
  51755. * automatic start to happen and let you decide when to start emitting particles.
  51756. */
  51757. this.preventAutoStart = false;
  51758. /**
  51759. * Callback triggered when the particle animation is ending.
  51760. */
  51761. this.onAnimationEnd = null;
  51762. /**
  51763. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51764. */
  51765. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51766. /**
  51767. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51768. * to override the particles.
  51769. */
  51770. this.forceDepthWrite = false;
  51771. /**
  51772. * You can use gravity if you want to give an orientation to your particles.
  51773. */
  51774. this.gravity = BABYLON.Vector3.Zero();
  51775. /**
  51776. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51777. */
  51778. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51779. /**
  51780. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51781. */
  51782. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51783. /**
  51784. * Color the particle will have at the end of its lifetime.
  51785. */
  51786. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51787. /**
  51788. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51789. */
  51790. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51791. /**
  51792. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51793. */
  51794. this.spriteCellLoop = true;
  51795. /**
  51796. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51797. */
  51798. this.spriteCellChangeSpeed = 0;
  51799. /**
  51800. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51801. */
  51802. this.startSpriteCellID = 0;
  51803. /**
  51804. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51805. */
  51806. this.endSpriteCellID = 0;
  51807. /**
  51808. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51809. */
  51810. this.spriteCellWidth = 0;
  51811. /**
  51812. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51813. */
  51814. this.spriteCellHeight = 0;
  51815. /**
  51816. * An event triggered when the system is disposed.
  51817. */
  51818. this.onDisposeObservable = new BABYLON.Observable();
  51819. this._particles = new Array();
  51820. this._stockParticles = new Array();
  51821. this._newPartsExcess = 0;
  51822. this._vertexBuffers = {};
  51823. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51824. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51825. this._scaledDirection = BABYLON.Vector3.Zero();
  51826. this._scaledGravity = BABYLON.Vector3.Zero();
  51827. this._currentRenderId = -1;
  51828. this._started = false;
  51829. this._stopped = false;
  51830. this._actualFrame = 0;
  51831. this._vertexBufferSize = 11;
  51832. // start of sub system methods
  51833. /**
  51834. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51835. * Its lifetime will start back at 0.
  51836. */
  51837. this.recycleParticle = function (particle) {
  51838. var lastParticle = _this._particles.pop();
  51839. if (lastParticle !== particle) {
  51840. lastParticle.copyTo(particle);
  51841. }
  51842. _this._stockParticles.push(lastParticle);
  51843. };
  51844. this._createParticle = function () {
  51845. var particle;
  51846. if (_this._stockParticles.length !== 0) {
  51847. particle = _this._stockParticles.pop();
  51848. particle.age = 0;
  51849. particle.cellIndex = _this.startSpriteCellID;
  51850. }
  51851. else {
  51852. particle = new BABYLON.Particle(_this);
  51853. }
  51854. return particle;
  51855. };
  51856. this._emitFromParticle = function (particle) {
  51857. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51858. return;
  51859. }
  51860. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51861. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51862. subSystem._rootParticleSystem = _this;
  51863. _this.activeSubSystems.push(subSystem);
  51864. subSystem.start();
  51865. };
  51866. this._appendParticleVertexes = null;
  51867. this.id = name;
  51868. this.name = name;
  51869. this._capacity = capacity;
  51870. this._epsilon = epsilon;
  51871. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51872. if (isAnimationSheetEnabled) {
  51873. this._vertexBufferSize = 12;
  51874. }
  51875. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51876. this._customEffect = customEffect;
  51877. scene.particleSystems.push(this);
  51878. this._createIndexBuffer();
  51879. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51880. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51881. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51882. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51883. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51884. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51885. if (this._isAnimationSheetEnabled) {
  51886. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51887. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51888. }
  51889. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51890. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51891. this._vertexBuffers["options"] = options;
  51892. // Default emitter type
  51893. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51894. this.updateFunction = function (particles) {
  51895. for (var index = 0; index < particles.length; index++) {
  51896. var particle = particles[index];
  51897. particle.age += _this._scaledUpdateSpeed;
  51898. if (particle.age >= particle.lifeTime) {
  51899. _this._emitFromParticle(particle);
  51900. _this.recycleParticle(particle);
  51901. index--;
  51902. continue;
  51903. }
  51904. else {
  51905. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51906. particle.color.addInPlace(_this._scaledColorStep);
  51907. if (particle.color.a < 0)
  51908. particle.color.a = 0;
  51909. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51910. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51911. particle.position.addInPlace(_this._scaledDirection);
  51912. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51913. particle.direction.addInPlace(_this._scaledGravity);
  51914. if (_this._isAnimationSheetEnabled) {
  51915. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51916. }
  51917. }
  51918. }
  51919. };
  51920. }
  51921. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51922. /**
  51923. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51924. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51925. */
  51926. get: function () {
  51927. if (this.particleEmitterType.direction1) {
  51928. return this.particleEmitterType.direction1;
  51929. }
  51930. return BABYLON.Vector3.Zero();
  51931. },
  51932. set: function (value) {
  51933. if (this.particleEmitterType.direction1) {
  51934. this.particleEmitterType.direction1 = value;
  51935. }
  51936. },
  51937. enumerable: true,
  51938. configurable: true
  51939. });
  51940. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51941. /**
  51942. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51943. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51944. */
  51945. get: function () {
  51946. if (this.particleEmitterType.direction2) {
  51947. return this.particleEmitterType.direction2;
  51948. }
  51949. return BABYLON.Vector3.Zero();
  51950. },
  51951. set: function (value) {
  51952. if (this.particleEmitterType.direction2) {
  51953. this.particleEmitterType.direction2 = value;
  51954. }
  51955. },
  51956. enumerable: true,
  51957. configurable: true
  51958. });
  51959. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51960. /**
  51961. * 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.
  51962. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51963. */
  51964. get: function () {
  51965. if (this.particleEmitterType.minEmitBox) {
  51966. return this.particleEmitterType.minEmitBox;
  51967. }
  51968. return BABYLON.Vector3.Zero();
  51969. },
  51970. set: function (value) {
  51971. if (this.particleEmitterType.minEmitBox) {
  51972. this.particleEmitterType.minEmitBox = value;
  51973. }
  51974. },
  51975. enumerable: true,
  51976. configurable: true
  51977. });
  51978. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51979. /**
  51980. * 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.
  51981. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51982. */
  51983. get: function () {
  51984. if (this.particleEmitterType.maxEmitBox) {
  51985. return this.particleEmitterType.maxEmitBox;
  51986. }
  51987. return BABYLON.Vector3.Zero();
  51988. },
  51989. set: function (value) {
  51990. if (this.particleEmitterType.maxEmitBox) {
  51991. this.particleEmitterType.maxEmitBox = value;
  51992. }
  51993. },
  51994. enumerable: true,
  51995. configurable: true
  51996. });
  51997. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51998. /**
  51999. * Sets a callback that will be triggered when the system is disposed.
  52000. */
  52001. set: function (callback) {
  52002. if (this._onDisposeObserver) {
  52003. this.onDisposeObservable.remove(this._onDisposeObserver);
  52004. }
  52005. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  52006. },
  52007. enumerable: true,
  52008. configurable: true
  52009. });
  52010. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  52011. /**
  52012. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  52013. */
  52014. get: function () {
  52015. return this._isAnimationSheetEnabled;
  52016. },
  52017. enumerable: true,
  52018. configurable: true
  52019. });
  52020. Object.defineProperty(ParticleSystem.prototype, "particles", {
  52021. //end of Sub-emitter
  52022. /**
  52023. * Gets the current list of active particles
  52024. */
  52025. get: function () {
  52026. return this._particles;
  52027. },
  52028. enumerable: true,
  52029. configurable: true
  52030. });
  52031. /**
  52032. * Returns the string "ParticleSystem"
  52033. * @returns a string containing the class name
  52034. */
  52035. ParticleSystem.prototype.getClassName = function () {
  52036. return "ParticleSystem";
  52037. };
  52038. ParticleSystem.prototype._createIndexBuffer = function () {
  52039. var indices = [];
  52040. var index = 0;
  52041. for (var count = 0; count < this._capacity; count++) {
  52042. indices.push(index);
  52043. indices.push(index + 1);
  52044. indices.push(index + 2);
  52045. indices.push(index);
  52046. indices.push(index + 2);
  52047. indices.push(index + 3);
  52048. index += 4;
  52049. }
  52050. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  52051. };
  52052. /**
  52053. * Gets the maximum number of particles active at the same time.
  52054. * @returns The max number of active particles.
  52055. */
  52056. ParticleSystem.prototype.getCapacity = function () {
  52057. return this._capacity;
  52058. };
  52059. /**
  52060. * Gets Wether there are still active particles in the system.
  52061. * @returns True if it is alive, otherwise false.
  52062. */
  52063. ParticleSystem.prototype.isAlive = function () {
  52064. return this._alive;
  52065. };
  52066. /**
  52067. * Gets Wether the system has been started.
  52068. * @returns True if it has been started, otherwise false.
  52069. */
  52070. ParticleSystem.prototype.isStarted = function () {
  52071. return this._started;
  52072. };
  52073. /**
  52074. * Starts the particle system and begins to emit.
  52075. */
  52076. ParticleSystem.prototype.start = function () {
  52077. this._started = true;
  52078. this._stopped = false;
  52079. this._actualFrame = 0;
  52080. if (this.subEmitters && this.subEmitters.length != 0) {
  52081. this.activeSubSystems = new Array();
  52082. }
  52083. };
  52084. /**
  52085. * Stops the particle system.
  52086. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  52087. */
  52088. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  52089. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  52090. this._stopped = true;
  52091. if (stopSubEmitters) {
  52092. this._stopSubEmitters();
  52093. }
  52094. };
  52095. // animation sheet
  52096. /**
  52097. * Remove all active particles
  52098. */
  52099. ParticleSystem.prototype.reset = function () {
  52100. this._stockParticles = [];
  52101. this._particles = [];
  52102. };
  52103. /**
  52104. * @ignore (for internal use only)
  52105. */
  52106. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  52107. var offset = index * this._vertexBufferSize;
  52108. this._vertexData[offset] = particle.position.x;
  52109. this._vertexData[offset + 1] = particle.position.y;
  52110. this._vertexData[offset + 2] = particle.position.z;
  52111. this._vertexData[offset + 3] = particle.color.r;
  52112. this._vertexData[offset + 4] = particle.color.g;
  52113. this._vertexData[offset + 5] = particle.color.b;
  52114. this._vertexData[offset + 6] = particle.color.a;
  52115. this._vertexData[offset + 7] = particle.angle;
  52116. this._vertexData[offset + 8] = particle.size;
  52117. this._vertexData[offset + 9] = offsetX;
  52118. this._vertexData[offset + 10] = offsetY;
  52119. };
  52120. /**
  52121. * @ignore (for internal use only)
  52122. */
  52123. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  52124. if (offsetX === 0)
  52125. offsetX = this._epsilon;
  52126. else if (offsetX === 1)
  52127. offsetX = 1 - this._epsilon;
  52128. if (offsetY === 0)
  52129. offsetY = this._epsilon;
  52130. else if (offsetY === 1)
  52131. offsetY = 1 - this._epsilon;
  52132. var offset = index * this._vertexBufferSize;
  52133. this._vertexData[offset] = particle.position.x;
  52134. this._vertexData[offset + 1] = particle.position.y;
  52135. this._vertexData[offset + 2] = particle.position.z;
  52136. this._vertexData[offset + 3] = particle.color.r;
  52137. this._vertexData[offset + 4] = particle.color.g;
  52138. this._vertexData[offset + 5] = particle.color.b;
  52139. this._vertexData[offset + 6] = particle.color.a;
  52140. this._vertexData[offset + 7] = particle.angle;
  52141. this._vertexData[offset + 8] = particle.size;
  52142. this._vertexData[offset + 9] = offsetX;
  52143. this._vertexData[offset + 10] = offsetY;
  52144. this._vertexData[offset + 11] = particle.cellIndex;
  52145. };
  52146. ParticleSystem.prototype._stopSubEmitters = function () {
  52147. if (!this.activeSubSystems) {
  52148. return;
  52149. }
  52150. this.activeSubSystems.forEach(function (subSystem) {
  52151. subSystem.stop(true);
  52152. });
  52153. this.activeSubSystems = new Array();
  52154. };
  52155. ParticleSystem.prototype._removeFromRoot = function () {
  52156. if (!this._rootParticleSystem) {
  52157. return;
  52158. }
  52159. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  52160. if (index !== -1) {
  52161. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  52162. }
  52163. };
  52164. // end of sub system methods
  52165. ParticleSystem.prototype._update = function (newParticles) {
  52166. // Update current
  52167. this._alive = this._particles.length > 0;
  52168. this.updateFunction(this._particles);
  52169. // Add new ones
  52170. var worldMatrix;
  52171. if (this.emitter.position) {
  52172. var emitterMesh = this.emitter;
  52173. worldMatrix = emitterMesh.getWorldMatrix();
  52174. }
  52175. else {
  52176. var emitterPosition = this.emitter;
  52177. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52178. }
  52179. var particle;
  52180. for (var index = 0; index < newParticles; index++) {
  52181. if (this._particles.length === this._capacity) {
  52182. break;
  52183. }
  52184. particle = this._createParticle();
  52185. this._particles.push(particle);
  52186. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  52187. if (this.startPositionFunction) {
  52188. this.startPositionFunction(worldMatrix, particle.position, particle);
  52189. }
  52190. else {
  52191. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  52192. }
  52193. if (this.startDirectionFunction) {
  52194. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52195. }
  52196. else {
  52197. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52198. }
  52199. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  52200. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  52201. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  52202. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  52203. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  52204. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  52205. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  52206. }
  52207. };
  52208. ParticleSystem.prototype._getEffect = function () {
  52209. if (this._customEffect) {
  52210. return this._customEffect;
  52211. }
  52212. ;
  52213. var defines = [];
  52214. if (this._scene.clipPlane) {
  52215. defines.push("#define CLIPPLANE");
  52216. }
  52217. if (this._isAnimationSheetEnabled) {
  52218. defines.push("#define ANIMATESHEET");
  52219. }
  52220. // Effect
  52221. var join = defines.join("\n");
  52222. if (this._cachedDefines !== join) {
  52223. this._cachedDefines = join;
  52224. var attributesNamesOrOptions;
  52225. var effectCreationOption;
  52226. if (this._isAnimationSheetEnabled) {
  52227. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  52228. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  52229. }
  52230. else {
  52231. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  52232. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  52233. }
  52234. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52235. }
  52236. return this._effect;
  52237. };
  52238. /**
  52239. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52240. */
  52241. ParticleSystem.prototype.animate = function () {
  52242. if (!this._started)
  52243. return;
  52244. var effect = this._getEffect();
  52245. // Check
  52246. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52247. return;
  52248. if (this._currentRenderId === this._scene.getRenderId()) {
  52249. return;
  52250. }
  52251. this._currentRenderId = this._scene.getRenderId();
  52252. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52253. // determine the number of particles we need to create
  52254. var newParticles;
  52255. if (this.manualEmitCount > -1) {
  52256. newParticles = this.manualEmitCount;
  52257. this._newPartsExcess = 0;
  52258. this.manualEmitCount = 0;
  52259. }
  52260. else {
  52261. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52262. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52263. }
  52264. if (this._newPartsExcess > 1.0) {
  52265. newParticles += this._newPartsExcess >> 0;
  52266. this._newPartsExcess -= this._newPartsExcess >> 0;
  52267. }
  52268. this._alive = false;
  52269. if (!this._stopped) {
  52270. this._actualFrame += this._scaledUpdateSpeed;
  52271. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52272. this.stop();
  52273. }
  52274. else {
  52275. newParticles = 0;
  52276. }
  52277. this._update(newParticles);
  52278. // Stopped?
  52279. if (this._stopped) {
  52280. if (!this._alive) {
  52281. this._started = false;
  52282. if (this.onAnimationEnd) {
  52283. this.onAnimationEnd();
  52284. }
  52285. if (this.disposeOnStop) {
  52286. this._scene._toBeDisposed.push(this);
  52287. }
  52288. }
  52289. }
  52290. // Animation sheet
  52291. if (this._isAnimationSheetEnabled) {
  52292. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52293. }
  52294. else {
  52295. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52296. }
  52297. // Update VBO
  52298. var offset = 0;
  52299. for (var index = 0; index < this._particles.length; index++) {
  52300. var particle = this._particles[index];
  52301. this._appendParticleVertexes(offset, particle);
  52302. offset += 4;
  52303. }
  52304. if (this._vertexBuffer) {
  52305. this._vertexBuffer.update(this._vertexData);
  52306. }
  52307. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52308. this.stop();
  52309. }
  52310. };
  52311. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52312. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52313. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52314. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52315. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52316. };
  52317. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52318. this._appendParticleVertex(offset++, particle, 0, 0);
  52319. this._appendParticleVertex(offset++, particle, 1, 0);
  52320. this._appendParticleVertex(offset++, particle, 1, 1);
  52321. this._appendParticleVertex(offset++, particle, 0, 1);
  52322. };
  52323. /**
  52324. * Rebuilds the particle system.
  52325. */
  52326. ParticleSystem.prototype.rebuild = function () {
  52327. this._createIndexBuffer();
  52328. if (this._vertexBuffer) {
  52329. this._vertexBuffer._rebuild();
  52330. }
  52331. };
  52332. /**
  52333. * Is this system ready to be used/rendered
  52334. * @return true if the system is ready
  52335. */
  52336. ParticleSystem.prototype.isReady = function () {
  52337. var effect = this._getEffect();
  52338. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52339. return false;
  52340. }
  52341. return true;
  52342. };
  52343. /**
  52344. * Renders the particle system in its current state.
  52345. * @returns the current number of particles
  52346. */
  52347. ParticleSystem.prototype.render = function () {
  52348. var effect = this._getEffect();
  52349. // Check
  52350. if (!this.isReady() || !this._particles.length) {
  52351. return 0;
  52352. }
  52353. var engine = this._scene.getEngine();
  52354. // Render
  52355. engine.enableEffect(effect);
  52356. engine.setState(false);
  52357. var viewMatrix = this._scene.getViewMatrix();
  52358. effect.setTexture("diffuseSampler", this.particleTexture);
  52359. effect.setMatrix("view", viewMatrix);
  52360. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52361. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52362. var baseSize = this.particleTexture.getBaseSize();
  52363. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52364. }
  52365. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52366. if (this._scene.clipPlane) {
  52367. var clipPlane = this._scene.clipPlane;
  52368. var invView = viewMatrix.clone();
  52369. invView.invert();
  52370. effect.setMatrix("invView", invView);
  52371. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52372. }
  52373. // VBOs
  52374. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52375. // Draw order
  52376. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52377. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52378. }
  52379. else {
  52380. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52381. }
  52382. if (this.forceDepthWrite) {
  52383. engine.setDepthWrite(true);
  52384. }
  52385. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52386. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52387. return this._particles.length;
  52388. };
  52389. /**
  52390. * Disposes the particle system and free the associated resources
  52391. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52392. */
  52393. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52394. if (disposeTexture === void 0) { disposeTexture = true; }
  52395. if (this._vertexBuffer) {
  52396. this._vertexBuffer.dispose();
  52397. this._vertexBuffer = null;
  52398. }
  52399. if (this._indexBuffer) {
  52400. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52401. this._indexBuffer = null;
  52402. }
  52403. if (disposeTexture && this.particleTexture) {
  52404. this.particleTexture.dispose();
  52405. this.particleTexture = null;
  52406. }
  52407. this._removeFromRoot();
  52408. // Remove from scene
  52409. var index = this._scene.particleSystems.indexOf(this);
  52410. if (index > -1) {
  52411. this._scene.particleSystems.splice(index, 1);
  52412. }
  52413. // Callback
  52414. this.onDisposeObservable.notifyObservers(this);
  52415. this.onDisposeObservable.clear();
  52416. };
  52417. /**
  52418. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52419. * @param radius The radius of the sphere to emit from
  52420. * @returns the emitter
  52421. */
  52422. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52423. if (radius === void 0) { radius = 1; }
  52424. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52425. this.particleEmitterType = particleEmitter;
  52426. return particleEmitter;
  52427. };
  52428. /**
  52429. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52430. * @param radius The radius of the sphere to emit from
  52431. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52432. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52433. * @returns the emitter
  52434. */
  52435. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52436. if (radius === void 0) { radius = 1; }
  52437. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52438. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52439. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52440. this.particleEmitterType = particleEmitter;
  52441. return particleEmitter;
  52442. };
  52443. /**
  52444. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52445. * @param radius The radius of the cone to emit from
  52446. * @param angle The base angle of the cone
  52447. * @returns the emitter
  52448. */
  52449. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52450. if (radius === void 0) { radius = 1; }
  52451. if (angle === void 0) { angle = Math.PI / 4; }
  52452. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52453. this.particleEmitterType = particleEmitter;
  52454. return particleEmitter;
  52455. };
  52456. // 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.
  52457. /**
  52458. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52459. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52460. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52461. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52462. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52463. * @returns the emitter
  52464. */
  52465. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52466. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52467. this.particleEmitterType = particleEmitter;
  52468. this.direction1 = direction1;
  52469. this.direction2 = direction2;
  52470. this.minEmitBox = minEmitBox;
  52471. this.maxEmitBox = maxEmitBox;
  52472. return particleEmitter;
  52473. };
  52474. // Clone
  52475. /**
  52476. * Clones the particle system.
  52477. * @param name The name of the cloned object
  52478. * @param newEmitter The new emitter to use
  52479. * @returns the cloned particle system
  52480. */
  52481. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52482. var custom = null;
  52483. var program = null;
  52484. if (this.customShader != null) {
  52485. program = this.customShader;
  52486. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52487. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52488. }
  52489. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52490. result.customShader = program;
  52491. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52492. if (newEmitter === undefined) {
  52493. newEmitter = this.emitter;
  52494. }
  52495. result.emitter = newEmitter;
  52496. if (this.particleTexture) {
  52497. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52498. }
  52499. if (!this.preventAutoStart) {
  52500. result.start();
  52501. }
  52502. return result;
  52503. };
  52504. /**
  52505. * Serializes the particle system to a JSON object.
  52506. * @returns the JSON object
  52507. */
  52508. ParticleSystem.prototype.serialize = function () {
  52509. var serializationObject = {};
  52510. serializationObject.name = this.name;
  52511. serializationObject.id = this.id;
  52512. // Emitter
  52513. if (this.emitter.position) {
  52514. var emitterMesh = this.emitter;
  52515. serializationObject.emitterId = emitterMesh.id;
  52516. }
  52517. else {
  52518. var emitterPosition = this.emitter;
  52519. serializationObject.emitter = emitterPosition.asArray();
  52520. }
  52521. serializationObject.capacity = this.getCapacity();
  52522. if (this.particleTexture) {
  52523. serializationObject.textureName = this.particleTexture.name;
  52524. }
  52525. // Animations
  52526. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52527. // Particle system
  52528. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52529. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52530. serializationObject.minSize = this.minSize;
  52531. serializationObject.maxSize = this.maxSize;
  52532. serializationObject.minEmitPower = this.minEmitPower;
  52533. serializationObject.maxEmitPower = this.maxEmitPower;
  52534. serializationObject.minLifeTime = this.minLifeTime;
  52535. serializationObject.maxLifeTime = this.maxLifeTime;
  52536. serializationObject.emitRate = this.emitRate;
  52537. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52538. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52539. serializationObject.gravity = this.gravity.asArray();
  52540. serializationObject.direction1 = this.direction1.asArray();
  52541. serializationObject.direction2 = this.direction2.asArray();
  52542. serializationObject.color1 = this.color1.asArray();
  52543. serializationObject.color2 = this.color2.asArray();
  52544. serializationObject.colorDead = this.colorDead.asArray();
  52545. serializationObject.updateSpeed = this.updateSpeed;
  52546. serializationObject.targetStopDuration = this.targetStopDuration;
  52547. serializationObject.textureMask = this.textureMask.asArray();
  52548. serializationObject.blendMode = this.blendMode;
  52549. serializationObject.customShader = this.customShader;
  52550. serializationObject.preventAutoStart = this.preventAutoStart;
  52551. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52552. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52553. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52554. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52555. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52556. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52557. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52558. // Emitter
  52559. if (this.particleEmitterType) {
  52560. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52561. }
  52562. return serializationObject;
  52563. };
  52564. /**
  52565. * Parses a JSON object to create a particle system.
  52566. * @param parsedParticleSystem The JSON object to parse
  52567. * @param scene The scene to create the particle system in
  52568. * @param rootUrl The root url to use to load external dependencies like texture
  52569. * @returns the Parsed particle system
  52570. */
  52571. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52572. var name = parsedParticleSystem.name;
  52573. var custom = null;
  52574. var program = null;
  52575. if (parsedParticleSystem.customShader) {
  52576. program = parsedParticleSystem.customShader;
  52577. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52578. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52579. }
  52580. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52581. particleSystem.customShader = program;
  52582. if (parsedParticleSystem.id) {
  52583. particleSystem.id = parsedParticleSystem.id;
  52584. }
  52585. // Auto start
  52586. if (parsedParticleSystem.preventAutoStart) {
  52587. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52588. }
  52589. // Texture
  52590. if (parsedParticleSystem.textureName) {
  52591. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52592. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52593. }
  52594. // Emitter
  52595. if (parsedParticleSystem.emitterId) {
  52596. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52597. }
  52598. else {
  52599. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52600. }
  52601. // Animations
  52602. if (parsedParticleSystem.animations) {
  52603. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52604. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52605. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52606. }
  52607. }
  52608. if (parsedParticleSystem.autoAnimate) {
  52609. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52610. }
  52611. // Particle system
  52612. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52613. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52614. particleSystem.minSize = parsedParticleSystem.minSize;
  52615. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52616. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52617. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52618. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52619. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52620. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52621. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52622. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52623. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52624. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52625. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52626. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52627. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52628. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52629. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52630. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52631. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52632. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52633. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52634. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52635. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52636. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52637. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52638. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52639. if (!particleSystem.preventAutoStart) {
  52640. particleSystem.start();
  52641. }
  52642. return particleSystem;
  52643. };
  52644. /**
  52645. * Source color is added to the destination color without alpha affecting the result.
  52646. */
  52647. ParticleSystem.BLENDMODE_ONEONE = 0;
  52648. /**
  52649. * Blend current color and particle color using particle’s alpha.
  52650. */
  52651. ParticleSystem.BLENDMODE_STANDARD = 1;
  52652. return ParticleSystem;
  52653. }());
  52654. BABYLON.ParticleSystem = ParticleSystem;
  52655. })(BABYLON || (BABYLON = {}));
  52656. //# sourceMappingURL=babylon.particleSystem.js.map
  52657. "use strict";
  52658. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52659. "use strict";
  52660. var BABYLON;
  52661. (function (BABYLON) {
  52662. /**
  52663. * Particle emitter emitting particles from the inside of a box.
  52664. * It emits the particles randomly between 2 given directions.
  52665. */
  52666. var BoxParticleEmitter = /** @class */ (function () {
  52667. /**
  52668. * Creates a new instance of @see BoxParticleEmitter
  52669. */
  52670. function BoxParticleEmitter() {
  52671. /**
  52672. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52673. */
  52674. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52675. /**
  52676. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52677. */
  52678. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52679. /**
  52680. * 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.
  52681. */
  52682. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52683. /**
  52684. * 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.
  52685. */
  52686. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52687. }
  52688. /**
  52689. * Called by the particle System when the direction is computed for the created particle.
  52690. * @param emitPower is the power of the particle (speed)
  52691. * @param worldMatrix is the world matrix of the particle system
  52692. * @param directionToUpdate is the direction vector to update with the result
  52693. * @param particle is the particle we are computed the direction for
  52694. */
  52695. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52696. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52697. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52698. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52699. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52700. };
  52701. /**
  52702. * Called by the particle System when the position is computed for the created particle.
  52703. * @param worldMatrix is the world matrix of the particle system
  52704. * @param positionToUpdate is the position vector to update with the result
  52705. * @param particle is the particle we are computed the position for
  52706. */
  52707. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52708. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52709. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52710. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52711. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52712. };
  52713. /**
  52714. * Clones the current emitter and returns a copy of it
  52715. * @returns the new emitter
  52716. */
  52717. BoxParticleEmitter.prototype.clone = function () {
  52718. var newOne = new BoxParticleEmitter();
  52719. BABYLON.Tools.DeepCopy(this, newOne);
  52720. return newOne;
  52721. };
  52722. /**
  52723. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52724. * @param effect defines the update shader
  52725. */
  52726. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52727. effect.setVector3("direction1", this.direction1);
  52728. effect.setVector3("direction2", this.direction2);
  52729. effect.setVector3("minEmitBox", this.minEmitBox);
  52730. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52731. };
  52732. /**
  52733. * Returns a string to use to update the GPU particles update shader
  52734. * @returns a string containng the defines string
  52735. */
  52736. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52737. return "#define BOXEMITTER";
  52738. };
  52739. /**
  52740. * Returns the string "BoxEmitter"
  52741. * @returns a string containing the class name
  52742. */
  52743. BoxParticleEmitter.prototype.getClassName = function () {
  52744. return "BoxEmitter";
  52745. };
  52746. /**
  52747. * Serializes the particle system to a JSON object.
  52748. * @returns the JSON object
  52749. */
  52750. BoxParticleEmitter.prototype.serialize = function () {
  52751. var serializationObject = {};
  52752. serializationObject.type = this.getClassName();
  52753. serializationObject.direction1 = this.direction1.asArray();
  52754. ;
  52755. serializationObject.direction2 = this.direction2.asArray();
  52756. ;
  52757. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52758. ;
  52759. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52760. ;
  52761. return serializationObject;
  52762. };
  52763. /**
  52764. * Parse properties from a JSON object
  52765. * @param serializationObject defines the JSON object
  52766. */
  52767. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52768. this.direction1.copyFrom(serializationObject.direction1);
  52769. this.direction2.copyFrom(serializationObject.direction2);
  52770. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52771. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52772. };
  52773. return BoxParticleEmitter;
  52774. }());
  52775. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52776. })(BABYLON || (BABYLON = {}));
  52777. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52778. "use strict";
  52779. var BABYLON;
  52780. (function (BABYLON) {
  52781. /**
  52782. * Particle emitter emitting particles from the inside of a cone.
  52783. * It emits the particles alongside the cone volume from the base to the particle.
  52784. * The emission direction might be randomized.
  52785. */
  52786. var ConeParticleEmitter = /** @class */ (function () {
  52787. /**
  52788. * Creates a new instance of @see ConeParticleEmitter
  52789. * @param radius the radius of the emission cone (1 by default)
  52790. * @param angles the cone base angle (PI by default)
  52791. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52792. */
  52793. function ConeParticleEmitter(radius,
  52794. /**
  52795. * The radius of the emission cone.
  52796. */
  52797. angle,
  52798. /**
  52799. * The cone base angle.
  52800. */
  52801. directionRandomizer) {
  52802. if (radius === void 0) { radius = 1; }
  52803. if (angle === void 0) { angle = Math.PI; }
  52804. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52805. this.angle = angle;
  52806. this.directionRandomizer = directionRandomizer;
  52807. this.radius = radius;
  52808. }
  52809. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52810. /**
  52811. * Gets the radius of the emission cone.
  52812. */
  52813. get: function () {
  52814. return this._radius;
  52815. },
  52816. /**
  52817. * Sets the radius of the emission cone.
  52818. */
  52819. set: function (value) {
  52820. this._radius = value;
  52821. if (this.angle !== 0) {
  52822. this._height = value / Math.tan(this.angle / 2);
  52823. }
  52824. else {
  52825. this._height = 1;
  52826. }
  52827. },
  52828. enumerable: true,
  52829. configurable: true
  52830. });
  52831. /**
  52832. * Called by the particle System when the direction is computed for the created particle.
  52833. * @param emitPower is the power of the particle (speed)
  52834. * @param worldMatrix is the world matrix of the particle system
  52835. * @param directionToUpdate is the direction vector to update with the result
  52836. * @param particle is the particle we are computed the direction for
  52837. */
  52838. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52839. if (this.angle === 0) {
  52840. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52841. }
  52842. else {
  52843. // measure the direction Vector from the emitter to the particle.
  52844. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52845. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52846. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52847. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52848. direction.x += randX;
  52849. direction.y += randY;
  52850. direction.z += randZ;
  52851. direction.normalize();
  52852. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52853. }
  52854. };
  52855. /**
  52856. * Called by the particle System when the position is computed for the created particle.
  52857. * @param worldMatrix is the world matrix of the particle system
  52858. * @param positionToUpdate is the position vector to update with the result
  52859. * @param particle is the particle we are computed the position for
  52860. */
  52861. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52862. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52863. var h = BABYLON.Scalar.RandomRange(0, 1);
  52864. // Better distribution in a cone at normal angles.
  52865. h = 1 - h * h;
  52866. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52867. radius = radius * h;
  52868. var randX = radius * Math.sin(s);
  52869. var randZ = radius * Math.cos(s);
  52870. var randY = h * this._height;
  52871. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52872. };
  52873. /**
  52874. * Clones the current emitter and returns a copy of it
  52875. * @returns the new emitter
  52876. */
  52877. ConeParticleEmitter.prototype.clone = function () {
  52878. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52879. BABYLON.Tools.DeepCopy(this, newOne);
  52880. return newOne;
  52881. };
  52882. /**
  52883. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52884. * @param effect defines the update shader
  52885. */
  52886. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52887. effect.setFloat("radius", this.radius);
  52888. effect.setFloat("angle", this.angle);
  52889. effect.setFloat("height", this._height);
  52890. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52891. };
  52892. /**
  52893. * Returns a string to use to update the GPU particles update shader
  52894. * @returns a string containng the defines string
  52895. */
  52896. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52897. return "#define CONEEMITTER";
  52898. };
  52899. /**
  52900. * Returns the string "BoxEmitter"
  52901. * @returns a string containing the class name
  52902. */
  52903. ConeParticleEmitter.prototype.getClassName = function () {
  52904. return "ConeEmitter";
  52905. };
  52906. /**
  52907. * Serializes the particle system to a JSON object.
  52908. * @returns the JSON object
  52909. */
  52910. ConeParticleEmitter.prototype.serialize = function () {
  52911. var serializationObject = {};
  52912. serializationObject.type = this.getClassName();
  52913. serializationObject.radius = this.radius;
  52914. serializationObject.angle = this.angle;
  52915. serializationObject.directionRandomizer = this.directionRandomizer;
  52916. return serializationObject;
  52917. };
  52918. /**
  52919. * Parse properties from a JSON object
  52920. * @param serializationObject defines the JSON object
  52921. */
  52922. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52923. this.radius = serializationObject.radius;
  52924. this.angle = serializationObject.angle;
  52925. this.directionRandomizer = serializationObject.directionRandomizer;
  52926. };
  52927. return ConeParticleEmitter;
  52928. }());
  52929. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52930. })(BABYLON || (BABYLON = {}));
  52931. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52932. "use strict";
  52933. var BABYLON;
  52934. (function (BABYLON) {
  52935. /**
  52936. * Particle emitter emitting particles from the inside of a sphere.
  52937. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52938. */
  52939. var SphereParticleEmitter = /** @class */ (function () {
  52940. /**
  52941. * Creates a new instance of @see SphereParticleEmitter
  52942. * @param radius the radius of the emission sphere (1 by default)
  52943. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52944. */
  52945. function SphereParticleEmitter(
  52946. /**
  52947. * The radius of the emission sphere.
  52948. */
  52949. radius,
  52950. /**
  52951. * How much to randomize the particle direction [0-1].
  52952. */
  52953. directionRandomizer) {
  52954. if (radius === void 0) { radius = 1; }
  52955. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52956. this.radius = radius;
  52957. this.directionRandomizer = directionRandomizer;
  52958. }
  52959. /**
  52960. * Called by the particle System when the direction is computed for the created particle.
  52961. * @param emitPower is the power of the particle (speed)
  52962. * @param worldMatrix is the world matrix of the particle system
  52963. * @param directionToUpdate is the direction vector to update with the result
  52964. * @param particle is the particle we are computed the direction for
  52965. */
  52966. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52967. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52968. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52969. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52970. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52971. direction.x += randX;
  52972. direction.y += randY;
  52973. direction.z += randZ;
  52974. direction.normalize();
  52975. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52976. };
  52977. /**
  52978. * Called by the particle System when the position is computed for the created particle.
  52979. * @param worldMatrix is the world matrix of the particle system
  52980. * @param positionToUpdate is the position vector to update with the result
  52981. * @param particle is the particle we are computed the position for
  52982. */
  52983. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52984. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52985. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52986. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52987. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52988. var randY = randRadius * Math.cos(theta);
  52989. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52990. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52991. };
  52992. /**
  52993. * Clones the current emitter and returns a copy of it
  52994. * @returns the new emitter
  52995. */
  52996. SphereParticleEmitter.prototype.clone = function () {
  52997. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52998. BABYLON.Tools.DeepCopy(this, newOne);
  52999. return newOne;
  53000. };
  53001. /**
  53002. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53003. * @param effect defines the update shader
  53004. */
  53005. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  53006. effect.setFloat("radius", this.radius);
  53007. effect.setFloat("directionRandomizer", this.directionRandomizer);
  53008. };
  53009. /**
  53010. * Returns a string to use to update the GPU particles update shader
  53011. * @returns a string containng the defines string
  53012. */
  53013. SphereParticleEmitter.prototype.getEffectDefines = function () {
  53014. return "#define SPHEREEMITTER";
  53015. };
  53016. /**
  53017. * Returns the string "SphereParticleEmitter"
  53018. * @returns a string containing the class name
  53019. */
  53020. SphereParticleEmitter.prototype.getClassName = function () {
  53021. return "SphereParticleEmitter";
  53022. };
  53023. /**
  53024. * Serializes the particle system to a JSON object.
  53025. * @returns the JSON object
  53026. */
  53027. SphereParticleEmitter.prototype.serialize = function () {
  53028. var serializationObject = {};
  53029. serializationObject.type = this.getClassName();
  53030. serializationObject.radius = this.radius;
  53031. serializationObject.directionRandomizer = this.directionRandomizer;
  53032. return serializationObject;
  53033. };
  53034. /**
  53035. * Parse properties from a JSON object
  53036. * @param serializationObject defines the JSON object
  53037. */
  53038. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  53039. this.radius = serializationObject.radius;
  53040. this.directionRandomizer = serializationObject.directionRandomizer;
  53041. };
  53042. return SphereParticleEmitter;
  53043. }());
  53044. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  53045. /**
  53046. * Particle emitter emitting particles from the inside of a sphere.
  53047. * It emits the particles randomly between two vectors.
  53048. */
  53049. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  53050. __extends(SphereDirectedParticleEmitter, _super);
  53051. /**
  53052. * Creates a new instance of @see SphereDirectedParticleEmitter
  53053. * @param radius the radius of the emission sphere (1 by default)
  53054. * @param direction1 the min limit of the emission direction (up vector by default)
  53055. * @param direction2 the max limit of the emission direction (up vector by default)
  53056. */
  53057. function SphereDirectedParticleEmitter(radius,
  53058. /**
  53059. * The min limit of the emission direction.
  53060. */
  53061. direction1,
  53062. /**
  53063. * The max limit of the emission direction.
  53064. */
  53065. direction2) {
  53066. if (radius === void 0) { radius = 1; }
  53067. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  53068. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  53069. var _this = _super.call(this, radius) || this;
  53070. _this.direction1 = direction1;
  53071. _this.direction2 = direction2;
  53072. return _this;
  53073. }
  53074. /**
  53075. * Called by the particle System when the direction is computed for the created particle.
  53076. * @param emitPower is the power of the particle (speed)
  53077. * @param worldMatrix is the world matrix of the particle system
  53078. * @param directionToUpdate is the direction vector to update with the result
  53079. * @param particle is the particle we are computed the direction for
  53080. */
  53081. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53082. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  53083. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  53084. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  53085. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  53086. };
  53087. /**
  53088. * Clones the current emitter and returns a copy of it
  53089. * @returns the new emitter
  53090. */
  53091. SphereDirectedParticleEmitter.prototype.clone = function () {
  53092. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  53093. BABYLON.Tools.DeepCopy(this, newOne);
  53094. return newOne;
  53095. };
  53096. /**
  53097. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53098. * @param effect defines the update shader
  53099. */
  53100. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  53101. effect.setFloat("radius", this.radius);
  53102. effect.setVector3("direction1", this.direction1);
  53103. effect.setVector3("direction2", this.direction2);
  53104. };
  53105. /**
  53106. * Returns a string to use to update the GPU particles update shader
  53107. * @returns a string containng the defines string
  53108. */
  53109. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  53110. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  53111. };
  53112. /**
  53113. * Returns the string "SphereDirectedParticleEmitter"
  53114. * @returns a string containing the class name
  53115. */
  53116. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  53117. return "SphereDirectedParticleEmitter";
  53118. };
  53119. /**
  53120. * Serializes the particle system to a JSON object.
  53121. * @returns the JSON object
  53122. */
  53123. SphereDirectedParticleEmitter.prototype.serialize = function () {
  53124. var serializationObject = _super.prototype.serialize.call(this);
  53125. ;
  53126. serializationObject.direction1 = this.direction1.asArray();
  53127. ;
  53128. serializationObject.direction2 = this.direction2.asArray();
  53129. ;
  53130. return serializationObject;
  53131. };
  53132. /**
  53133. * Parse properties from a JSON object
  53134. * @param serializationObject defines the JSON object
  53135. */
  53136. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  53137. _super.prototype.parse.call(this, serializationObject);
  53138. this.direction1.copyFrom(serializationObject.direction1);
  53139. this.direction2.copyFrom(serializationObject.direction2);
  53140. };
  53141. return SphereDirectedParticleEmitter;
  53142. }(SphereParticleEmitter));
  53143. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  53144. })(BABYLON || (BABYLON = {}));
  53145. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  53146. "use strict";
  53147. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53148. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53149. s = arguments[i];
  53150. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53151. t[p] = s[p];
  53152. }
  53153. return t;
  53154. };
  53155. var BABYLON;
  53156. (function (BABYLON) {
  53157. /**
  53158. * This represents a GPU particle system in Babylon
  53159. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  53160. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  53161. */
  53162. var GPUParticleSystem = /** @class */ (function () {
  53163. /**
  53164. * Instantiates a GPU particle system.
  53165. * 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.
  53166. * @param name The name of the particle system
  53167. * @param capacity The max number of particles alive at the same time
  53168. * @param scene The scene the particle system belongs to
  53169. */
  53170. function GPUParticleSystem(name, options, scene) {
  53171. /**
  53172. * The emitter represents the Mesh or position we are attaching the particle system to.
  53173. */
  53174. this.emitter = null;
  53175. /**
  53176. * The rendering group used by the Particle system to chose when to render.
  53177. */
  53178. this.renderingGroupId = 0;
  53179. /**
  53180. * The layer mask we are rendering the particles through.
  53181. */
  53182. this.layerMask = 0x0FFFFFFF;
  53183. this._targetIndex = 0;
  53184. this._currentRenderId = -1;
  53185. this._started = false;
  53186. this._stopped = false;
  53187. this._timeDelta = 0;
  53188. this._attributesStrideSize = 14;
  53189. this._actualFrame = 0;
  53190. /**
  53191. * List of animations used by the particle system.
  53192. */
  53193. this.animations = [];
  53194. /**
  53195. * An event triggered when the system is disposed.
  53196. */
  53197. this.onDisposeObservable = new BABYLON.Observable();
  53198. /**
  53199. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  53200. */
  53201. this.updateSpeed = 0.01;
  53202. /**
  53203. * The amount of time the particle system is running (depends of the overall update speed).
  53204. */
  53205. this.targetStopDuration = 0;
  53206. /**
  53207. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53208. */
  53209. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  53210. /**
  53211. * Minimum life time of emitting particles.
  53212. */
  53213. this.minLifeTime = 1;
  53214. /**
  53215. * Maximum life time of emitting particles.
  53216. */
  53217. this.maxLifeTime = 1;
  53218. /**
  53219. * Minimum Size of emitting particles.
  53220. */
  53221. this.minSize = 1;
  53222. /**
  53223. * Maximum Size of emitting particles.
  53224. */
  53225. this.maxSize = 1;
  53226. /**
  53227. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53228. */
  53229. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53230. /**
  53231. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53232. */
  53233. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53234. /**
  53235. * Color the particle will have at the end of its lifetime.
  53236. */
  53237. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  53238. /**
  53239. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  53240. */
  53241. this.emitRate = 100;
  53242. /**
  53243. * You can use gravity if you want to give an orientation to your particles.
  53244. */
  53245. this.gravity = BABYLON.Vector3.Zero();
  53246. /**
  53247. * Minimum power of emitting particles.
  53248. */
  53249. this.minEmitPower = 1;
  53250. /**
  53251. * Maximum power of emitting particles.
  53252. */
  53253. this.maxEmitPower = 1;
  53254. /**
  53255. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53256. * to override the particles.
  53257. */
  53258. this.forceDepthWrite = false;
  53259. this.id = name;
  53260. this.name = name;
  53261. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53262. this._engine = this._scene.getEngine();
  53263. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  53264. this._capacity = fullOptions.capacity;
  53265. this._activeCount = fullOptions.capacity;
  53266. this._currentActiveCount = 0;
  53267. this._scene.particleSystems.push(this);
  53268. this._updateEffectOptions = {
  53269. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  53270. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  53271. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  53272. uniformBuffersNames: [],
  53273. samplers: ["randomSampler"],
  53274. defines: "",
  53275. fallbacks: null,
  53276. onCompiled: null,
  53277. onError: null,
  53278. indexParameters: null,
  53279. maxSimultaneousLights: 0,
  53280. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  53281. };
  53282. // Random data
  53283. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  53284. var d = [];
  53285. for (var i = 0; i < maxTextureSize; ++i) {
  53286. d.push(Math.random());
  53287. d.push(Math.random());
  53288. d.push(Math.random());
  53289. d.push(Math.random());
  53290. }
  53291. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  53292. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53293. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53294. this._randomTextureSize = maxTextureSize;
  53295. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53296. }
  53297. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  53298. /**
  53299. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  53300. */
  53301. get: function () {
  53302. if (!BABYLON.Engine.LastCreatedEngine) {
  53303. return false;
  53304. }
  53305. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  53306. },
  53307. enumerable: true,
  53308. configurable: true
  53309. });
  53310. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  53311. /**
  53312. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53313. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53314. */
  53315. get: function () {
  53316. if (this.particleEmitterType.direction1) {
  53317. return this.particleEmitterType.direction1;
  53318. }
  53319. return BABYLON.Vector3.Zero();
  53320. },
  53321. set: function (value) {
  53322. if (this.particleEmitterType.direction1) {
  53323. this.particleEmitterType.direction1 = value;
  53324. }
  53325. },
  53326. enumerable: true,
  53327. configurable: true
  53328. });
  53329. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  53330. /**
  53331. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53332. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53333. */
  53334. get: function () {
  53335. if (this.particleEmitterType.direction2) {
  53336. return this.particleEmitterType.direction2;
  53337. }
  53338. return BABYLON.Vector3.Zero();
  53339. },
  53340. set: function (value) {
  53341. if (this.particleEmitterType.direction2) {
  53342. this.particleEmitterType.direction2 = value;
  53343. }
  53344. },
  53345. enumerable: true,
  53346. configurable: true
  53347. });
  53348. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  53349. /**
  53350. * 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.
  53351. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53352. */
  53353. get: function () {
  53354. if (this.particleEmitterType.minEmitBox) {
  53355. return this.particleEmitterType.minEmitBox;
  53356. }
  53357. return BABYLON.Vector3.Zero();
  53358. },
  53359. set: function (value) {
  53360. if (this.particleEmitterType.minEmitBox) {
  53361. this.particleEmitterType.minEmitBox = value;
  53362. }
  53363. },
  53364. enumerable: true,
  53365. configurable: true
  53366. });
  53367. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  53368. /**
  53369. * 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.
  53370. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53371. */
  53372. get: function () {
  53373. if (this.particleEmitterType.maxEmitBox) {
  53374. return this.particleEmitterType.maxEmitBox;
  53375. }
  53376. return BABYLON.Vector3.Zero();
  53377. },
  53378. set: function (value) {
  53379. if (this.particleEmitterType.maxEmitBox) {
  53380. this.particleEmitterType.maxEmitBox = value;
  53381. }
  53382. },
  53383. enumerable: true,
  53384. configurable: true
  53385. });
  53386. /**
  53387. * Gets the maximum number of particles active at the same time.
  53388. * @returns The max number of active particles.
  53389. */
  53390. GPUParticleSystem.prototype.getCapacity = function () {
  53391. return this._capacity;
  53392. };
  53393. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53394. /**
  53395. * Gets or set the number of active particles
  53396. */
  53397. get: function () {
  53398. return this._activeCount;
  53399. },
  53400. set: function (value) {
  53401. this._activeCount = Math.min(value, this._capacity);
  53402. },
  53403. enumerable: true,
  53404. configurable: true
  53405. });
  53406. /**
  53407. * Is this system ready to be used/rendered
  53408. * @return true if the system is ready
  53409. */
  53410. GPUParticleSystem.prototype.isReady = function () {
  53411. if (!this._updateEffect) {
  53412. this._recreateUpdateEffect();
  53413. this._recreateRenderEffect();
  53414. return false;
  53415. }
  53416. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53417. return false;
  53418. }
  53419. return true;
  53420. };
  53421. /**
  53422. * Gets Wether the system has been started.
  53423. * @returns True if it has been started, otherwise false.
  53424. */
  53425. GPUParticleSystem.prototype.isStarted = function () {
  53426. return this._started;
  53427. };
  53428. /**
  53429. * Starts the particle system and begins to emit.
  53430. */
  53431. GPUParticleSystem.prototype.start = function () {
  53432. this._started = true;
  53433. this._stopped = false;
  53434. };
  53435. /**
  53436. * Stops the particle system.
  53437. */
  53438. GPUParticleSystem.prototype.stop = function () {
  53439. this._stopped = true;
  53440. };
  53441. /**
  53442. * Remove all active particles
  53443. */
  53444. GPUParticleSystem.prototype.reset = function () {
  53445. this._releaseBuffers();
  53446. this._releaseVAOs();
  53447. this._currentActiveCount = 0;
  53448. this._targetIndex = 0;
  53449. };
  53450. /**
  53451. * Returns the string "GPUParticleSystem"
  53452. * @returns a string containing the class name
  53453. */
  53454. GPUParticleSystem.prototype.getClassName = function () {
  53455. return "GPUParticleSystem";
  53456. };
  53457. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53458. var updateVertexBuffers = {};
  53459. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53460. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53461. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53462. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53463. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53464. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53465. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53466. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53467. this._engine.bindArrayBuffer(null);
  53468. return vao;
  53469. };
  53470. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53471. var renderVertexBuffers = {};
  53472. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53473. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53474. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53475. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53476. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53477. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53478. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53479. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53480. this._engine.bindArrayBuffer(null);
  53481. return vao;
  53482. };
  53483. GPUParticleSystem.prototype._initialize = function (force) {
  53484. if (force === void 0) { force = false; }
  53485. if (this._buffer0 && !force) {
  53486. return;
  53487. }
  53488. var engine = this._scene.getEngine();
  53489. var data = new Array();
  53490. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53491. // position
  53492. data.push(0.0);
  53493. data.push(0.0);
  53494. data.push(0.0);
  53495. // Age and life
  53496. data.push(0.0); // create the particle as a dead one to create a new one at start
  53497. data.push(0.0);
  53498. // Seed
  53499. data.push(Math.random());
  53500. // Size
  53501. data.push(0.0);
  53502. // color
  53503. data.push(0.0);
  53504. data.push(0.0);
  53505. data.push(0.0);
  53506. data.push(0.0);
  53507. // direction
  53508. data.push(0.0);
  53509. data.push(0.0);
  53510. data.push(0.0);
  53511. }
  53512. // Sprite data
  53513. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53514. -0.5, 0.5, 0, 1,
  53515. -0.5, -0.5, 0, 0,
  53516. 0.5, -0.5, 1, 0]);
  53517. // Buffers
  53518. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53519. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53520. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53521. // Update VAO
  53522. this._updateVAO = [];
  53523. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53524. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53525. // Render VAO
  53526. this._renderVAO = [];
  53527. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53528. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53529. // Links
  53530. this._sourceBuffer = this._buffer0;
  53531. this._targetBuffer = this._buffer1;
  53532. };
  53533. /** @ignore */
  53534. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53535. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53536. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53537. return;
  53538. }
  53539. this._updateEffectOptions.defines = defines;
  53540. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53541. };
  53542. /** @ignore */
  53543. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53544. var defines = "";
  53545. if (this._scene.clipPlane) {
  53546. defines = "\n#define CLIPPLANE";
  53547. }
  53548. if (this._renderEffect && this._renderEffect.defines === defines) {
  53549. return;
  53550. }
  53551. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53552. };
  53553. /**
  53554. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53555. */
  53556. GPUParticleSystem.prototype.animate = function () {
  53557. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53558. this._actualFrame += this._timeDelta;
  53559. if (!this._stopped) {
  53560. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53561. this.stop();
  53562. }
  53563. }
  53564. };
  53565. /**
  53566. * Renders the particle system in its current state.
  53567. * @returns the current number of particles
  53568. */
  53569. GPUParticleSystem.prototype.render = function () {
  53570. if (!this._started) {
  53571. return 0;
  53572. }
  53573. this._recreateUpdateEffect();
  53574. this._recreateRenderEffect();
  53575. if (!this.isReady()) {
  53576. return 0;
  53577. }
  53578. if (this._currentRenderId === this._scene.getRenderId()) {
  53579. return 0;
  53580. }
  53581. this._currentRenderId = this._scene.getRenderId();
  53582. // Get everything ready to render
  53583. this._initialize();
  53584. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53585. // Enable update effect
  53586. this._engine.enableEffect(this._updateEffect);
  53587. this._engine.setState(false);
  53588. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53589. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53590. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53591. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53592. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53593. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53594. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53595. this._updateEffect.setDirectColor4("color1", this.color1);
  53596. this._updateEffect.setDirectColor4("color2", this.color2);
  53597. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53598. this._updateEffect.setVector3("gravity", this.gravity);
  53599. if (this.particleEmitterType) {
  53600. this.particleEmitterType.applyToShader(this._updateEffect);
  53601. }
  53602. var emitterWM;
  53603. if (this.emitter.position) {
  53604. var emitterMesh = this.emitter;
  53605. emitterWM = emitterMesh.getWorldMatrix();
  53606. }
  53607. else {
  53608. var emitterPosition = this.emitter;
  53609. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53610. }
  53611. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53612. // Bind source VAO
  53613. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53614. // Update
  53615. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53616. this._engine.setRasterizerState(false);
  53617. this._engine.beginTransformFeedback();
  53618. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53619. this._engine.endTransformFeedback();
  53620. this._engine.setRasterizerState(true);
  53621. this._engine.bindTransformFeedbackBuffer(null);
  53622. // Enable render effect
  53623. this._engine.enableEffect(this._renderEffect);
  53624. var viewMatrix = this._scene.getViewMatrix();
  53625. this._renderEffect.setMatrix("view", viewMatrix);
  53626. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53627. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53628. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53629. if (this._scene.clipPlane) {
  53630. var clipPlane = this._scene.clipPlane;
  53631. var invView = viewMatrix.clone();
  53632. invView.invert();
  53633. this._renderEffect.setMatrix("invView", invView);
  53634. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53635. }
  53636. // Draw order
  53637. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53638. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53639. }
  53640. else {
  53641. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53642. }
  53643. if (this.forceDepthWrite) {
  53644. this._engine.setDepthWrite(true);
  53645. }
  53646. // Bind source VAO
  53647. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53648. // Render
  53649. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53650. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53651. // Switch VAOs
  53652. this._targetIndex++;
  53653. if (this._targetIndex === 2) {
  53654. this._targetIndex = 0;
  53655. }
  53656. // Switch buffers
  53657. var tmpBuffer = this._sourceBuffer;
  53658. this._sourceBuffer = this._targetBuffer;
  53659. this._targetBuffer = tmpBuffer;
  53660. return this._currentActiveCount;
  53661. };
  53662. /**
  53663. * Rebuilds the particle system
  53664. */
  53665. GPUParticleSystem.prototype.rebuild = function () {
  53666. this._initialize(true);
  53667. };
  53668. GPUParticleSystem.prototype._releaseBuffers = function () {
  53669. if (this._buffer0) {
  53670. this._buffer0.dispose();
  53671. this._buffer0 = null;
  53672. }
  53673. if (this._buffer1) {
  53674. this._buffer1.dispose();
  53675. this._buffer1 = null;
  53676. }
  53677. if (this._spriteBuffer) {
  53678. this._spriteBuffer.dispose();
  53679. this._spriteBuffer = null;
  53680. }
  53681. };
  53682. GPUParticleSystem.prototype._releaseVAOs = function () {
  53683. if (!this._updateVAO) {
  53684. return;
  53685. }
  53686. for (var index = 0; index < this._updateVAO.length; index++) {
  53687. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53688. }
  53689. this._updateVAO = [];
  53690. for (var index = 0; index < this._renderVAO.length; index++) {
  53691. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53692. }
  53693. this._renderVAO = [];
  53694. };
  53695. /**
  53696. * Disposes the particle system and free the associated resources
  53697. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53698. */
  53699. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53700. if (disposeTexture === void 0) { disposeTexture = true; }
  53701. var index = this._scene.particleSystems.indexOf(this);
  53702. if (index > -1) {
  53703. this._scene.particleSystems.splice(index, 1);
  53704. }
  53705. this._releaseBuffers();
  53706. this._releaseVAOs();
  53707. if (this._randomTexture) {
  53708. this._randomTexture.dispose();
  53709. this._randomTexture = null;
  53710. }
  53711. if (disposeTexture && this.particleTexture) {
  53712. this.particleTexture.dispose();
  53713. this.particleTexture = null;
  53714. }
  53715. // Callback
  53716. this.onDisposeObservable.notifyObservers(this);
  53717. this.onDisposeObservable.clear();
  53718. };
  53719. /**
  53720. * Clones the particle system.
  53721. * @param name The name of the cloned object
  53722. * @param newEmitter The new emitter to use
  53723. * @returns the cloned particle system
  53724. */
  53725. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53726. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53727. BABYLON.Tools.DeepCopy(this, result);
  53728. if (newEmitter === undefined) {
  53729. newEmitter = this.emitter;
  53730. }
  53731. result.emitter = newEmitter;
  53732. if (this.particleTexture) {
  53733. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53734. }
  53735. return result;
  53736. };
  53737. /**
  53738. * Serializes the particle system to a JSON object.
  53739. * @returns the JSON object
  53740. */
  53741. GPUParticleSystem.prototype.serialize = function () {
  53742. var serializationObject = {};
  53743. serializationObject.name = this.name;
  53744. serializationObject.id = this.id;
  53745. // Emitter
  53746. if (this.emitter.position) {
  53747. var emitterMesh = this.emitter;
  53748. serializationObject.emitterId = emitterMesh.id;
  53749. }
  53750. else {
  53751. var emitterPosition = this.emitter;
  53752. serializationObject.emitter = emitterPosition.asArray();
  53753. }
  53754. serializationObject.capacity = this.getCapacity();
  53755. if (this.particleTexture) {
  53756. serializationObject.textureName = this.particleTexture.name;
  53757. }
  53758. // Animations
  53759. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53760. // Particle system
  53761. serializationObject.activeParticleCount = this.activeParticleCount;
  53762. serializationObject.randomTextureSize = this._randomTextureSize;
  53763. serializationObject.minSize = this.minSize;
  53764. serializationObject.maxSize = this.maxSize;
  53765. serializationObject.minEmitPower = this.minEmitPower;
  53766. serializationObject.maxEmitPower = this.maxEmitPower;
  53767. serializationObject.minLifeTime = this.minLifeTime;
  53768. serializationObject.maxLifeTime = this.maxLifeTime;
  53769. serializationObject.emitRate = this.emitRate;
  53770. serializationObject.gravity = this.gravity.asArray();
  53771. serializationObject.color1 = this.color1.asArray();
  53772. serializationObject.color2 = this.color2.asArray();
  53773. serializationObject.colorDead = this.colorDead.asArray();
  53774. serializationObject.updateSpeed = this.updateSpeed;
  53775. serializationObject.targetStopDuration = this.targetStopDuration;
  53776. serializationObject.blendMode = this.blendMode;
  53777. // Emitter
  53778. if (this.particleEmitterType) {
  53779. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53780. }
  53781. return serializationObject;
  53782. };
  53783. /**
  53784. * Parses a JSON object to create a GPU particle system.
  53785. * @param parsedParticleSystem The JSON object to parse
  53786. * @param scene The scene to create the particle system in
  53787. * @param rootUrl The root url to use to load external dependencies like texture
  53788. * @returns the parsed GPU particle system
  53789. */
  53790. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53791. var name = parsedParticleSystem.name;
  53792. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53793. if (parsedParticleSystem.id) {
  53794. particleSystem.id = parsedParticleSystem.id;
  53795. }
  53796. // Texture
  53797. if (parsedParticleSystem.textureName) {
  53798. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53799. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53800. }
  53801. // Emitter
  53802. if (parsedParticleSystem.emitterId) {
  53803. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53804. }
  53805. else {
  53806. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53807. }
  53808. // Animations
  53809. if (parsedParticleSystem.animations) {
  53810. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53811. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53812. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53813. }
  53814. }
  53815. // Particle system
  53816. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53817. particleSystem.minSize = parsedParticleSystem.minSize;
  53818. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53819. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53820. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53821. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53822. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53823. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53824. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53825. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53826. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53827. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53828. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53829. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53830. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53831. // Emitter
  53832. if (parsedParticleSystem.particleEmitterType) {
  53833. var emitterType = void 0;
  53834. switch (parsedParticleSystem.particleEmitterType.type) {
  53835. case "SphereEmitter":
  53836. emitterType = new BABYLON.SphereParticleEmitter();
  53837. break;
  53838. case "SphereDirectedParticleEmitter":
  53839. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53840. break;
  53841. case "ConeEmitter":
  53842. emitterType = new BABYLON.ConeParticleEmitter();
  53843. break;
  53844. case "BoxEmitter":
  53845. default:
  53846. emitterType = new BABYLON.BoxParticleEmitter();
  53847. break;
  53848. }
  53849. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53850. particleSystem.particleEmitterType = emitterType;
  53851. }
  53852. return particleSystem;
  53853. };
  53854. return GPUParticleSystem;
  53855. }());
  53856. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53857. })(BABYLON || (BABYLON = {}));
  53858. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53859. "use strict";
  53860. var BABYLON;
  53861. (function (BABYLON) {
  53862. /**
  53863. * Represents one particle of a solid particle system.
  53864. * @see SolidParticleSystem
  53865. */
  53866. var SolidParticle = /** @class */ (function () {
  53867. /**
  53868. * Creates a Solid Particle object.
  53869. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53870. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53871. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53872. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53873. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53874. * @param shapeId (integer) is the model shape identifier in the SPS.
  53875. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53876. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53877. */
  53878. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53879. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53880. /**
  53881. * particle global index
  53882. */
  53883. this.idx = 0;
  53884. /**
  53885. * The color of the particle
  53886. */
  53887. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53888. /**
  53889. * The world space position of the particle.
  53890. */
  53891. this.position = BABYLON.Vector3.Zero();
  53892. /**
  53893. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53894. */
  53895. this.rotation = BABYLON.Vector3.Zero();
  53896. /**
  53897. * The scaling of the particle.
  53898. */
  53899. this.scaling = BABYLON.Vector3.One();
  53900. /**
  53901. * The uvs of the particle.
  53902. */
  53903. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53904. /**
  53905. * The current speed of the particle.
  53906. */
  53907. this.velocity = BABYLON.Vector3.Zero();
  53908. /**
  53909. * The pivot point in the particle local space.
  53910. */
  53911. this.pivot = BABYLON.Vector3.Zero();
  53912. /**
  53913. * Must the particle be translated from its pivot point in its local space ?
  53914. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53915. * Default : false
  53916. */
  53917. this.translateFromPivot = false;
  53918. /**
  53919. * Is the particle active or not ?
  53920. */
  53921. this.alive = true;
  53922. /**
  53923. * Is the particle visible or not ?
  53924. */
  53925. this.isVisible = true;
  53926. /**
  53927. * Index of this particle in the global "positions" array (Internal use)
  53928. */
  53929. this._pos = 0;
  53930. /**
  53931. * Index of this particle in the global "indices" array (Internal use)
  53932. */
  53933. this._ind = 0;
  53934. /**
  53935. * ModelShape id of this particle
  53936. */
  53937. this.shapeId = 0;
  53938. /**
  53939. * Index of the particle in its shape id (Internal use)
  53940. */
  53941. this.idxInShape = 0;
  53942. /**
  53943. * Still set as invisible in order to skip useless computations (Internal use)
  53944. */
  53945. this._stillInvisible = false;
  53946. /**
  53947. * Last computed particle rotation matrix
  53948. */
  53949. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53950. /**
  53951. * Parent particle Id, if any.
  53952. * Default null.
  53953. */
  53954. this.parentId = null;
  53955. /**
  53956. * Internal global position in the SPS.
  53957. */
  53958. this._globalPosition = BABYLON.Vector3.Zero();
  53959. this.idx = particleIndex;
  53960. this._pos = positionIndex;
  53961. this._ind = indiceIndex;
  53962. this._model = model;
  53963. this.shapeId = shapeId;
  53964. this.idxInShape = idxInShape;
  53965. this._sps = sps;
  53966. if (modelBoundingInfo) {
  53967. this._modelBoundingInfo = modelBoundingInfo;
  53968. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53969. }
  53970. }
  53971. Object.defineProperty(SolidParticle.prototype, "scale", {
  53972. /**
  53973. * Legacy support, changed scale to scaling
  53974. */
  53975. get: function () {
  53976. return this.scaling;
  53977. },
  53978. /**
  53979. * Legacy support, changed scale to scaling
  53980. */
  53981. set: function (scale) {
  53982. this.scaling = scale;
  53983. },
  53984. enumerable: true,
  53985. configurable: true
  53986. });
  53987. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53988. /**
  53989. * Legacy support, changed quaternion to rotationQuaternion
  53990. */
  53991. get: function () {
  53992. return this.rotationQuaternion;
  53993. },
  53994. /**
  53995. * Legacy support, changed quaternion to rotationQuaternion
  53996. */
  53997. set: function (q) {
  53998. this.rotationQuaternion = q;
  53999. },
  54000. enumerable: true,
  54001. configurable: true
  54002. });
  54003. /**
  54004. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  54005. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  54006. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  54007. * @returns true if it intersects
  54008. */
  54009. SolidParticle.prototype.intersectsMesh = function (target) {
  54010. if (!this._boundingInfo || !target._boundingInfo) {
  54011. return false;
  54012. }
  54013. if (this._sps._bSphereOnly) {
  54014. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  54015. }
  54016. return this._boundingInfo.intersects(target._boundingInfo, false);
  54017. };
  54018. return SolidParticle;
  54019. }());
  54020. BABYLON.SolidParticle = SolidParticle;
  54021. /**
  54022. * Represents the shape of the model used by one particle of a solid particle system.
  54023. * SPS internal tool, don't use it manually.
  54024. * @see SolidParticleSystem
  54025. */
  54026. var ModelShape = /** @class */ (function () {
  54027. /**
  54028. * 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.
  54029. * SPS internal tool, don't use it manually.
  54030. * @ignore
  54031. */
  54032. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  54033. /**
  54034. * length of the shape in the model indices array (internal use)
  54035. */
  54036. this._indicesLength = 0;
  54037. this.shapeID = id;
  54038. this._shape = shape;
  54039. this._indicesLength = indicesLength;
  54040. this._shapeUV = shapeUV;
  54041. this._positionFunction = posFunction;
  54042. this._vertexFunction = vtxFunction;
  54043. }
  54044. return ModelShape;
  54045. }());
  54046. BABYLON.ModelShape = ModelShape;
  54047. /**
  54048. * Represents a Depth Sorted Particle in the solid particle system.
  54049. * @see SolidParticleSystem
  54050. */
  54051. var DepthSortedParticle = /** @class */ (function () {
  54052. function DepthSortedParticle() {
  54053. /**
  54054. * Index of the particle in the "indices" array
  54055. */
  54056. this.ind = 0;
  54057. /**
  54058. * Length of the particle shape in the "indices" array
  54059. */
  54060. this.indicesLength = 0;
  54061. /**
  54062. * Squared distance from the particle to the camera
  54063. */
  54064. this.sqDistance = 0.0;
  54065. }
  54066. return DepthSortedParticle;
  54067. }());
  54068. BABYLON.DepthSortedParticle = DepthSortedParticle;
  54069. })(BABYLON || (BABYLON = {}));
  54070. //# sourceMappingURL=babylon.solidParticle.js.map
  54071. "use strict";
  54072. var BABYLON;
  54073. (function (BABYLON) {
  54074. /**
  54075. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  54076. *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.
  54077. * The SPS is also a particle system. It provides some methods to manage the particles.
  54078. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  54079. *
  54080. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  54081. */
  54082. var SolidParticleSystem = /** @class */ (function () {
  54083. /**
  54084. * Creates a SPS (Solid Particle System) object.
  54085. * @param name (String) is the SPS name, this will be the underlying mesh name.
  54086. * @param scene (Scene) is the scene in which the SPS is added.
  54087. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  54088. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  54089. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  54090. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  54091. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  54092. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  54093. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  54094. */
  54095. function SolidParticleSystem(name, scene, options) {
  54096. /**
  54097. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  54098. * Example : var p = SPS.particles[i];
  54099. */
  54100. this.particles = new Array();
  54101. /**
  54102. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  54103. */
  54104. this.nbParticles = 0;
  54105. /**
  54106. * If the particles must ever face the camera (default false). Useful for planar particles.
  54107. */
  54108. this.billboard = false;
  54109. /**
  54110. * Recompute normals when adding a shape
  54111. */
  54112. this.recomputeNormals = true;
  54113. /**
  54114. * This a counter ofr your own usage. It's not set by any SPS functions.
  54115. */
  54116. this.counter = 0;
  54117. /**
  54118. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54119. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54120. */
  54121. this.vars = {};
  54122. /**
  54123. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  54124. */
  54125. this._bSphereOnly = false;
  54126. /**
  54127. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  54128. */
  54129. this._bSphereRadiusFactor = 1.0;
  54130. this._positions = new Array();
  54131. this._indices = new Array();
  54132. this._normals = new Array();
  54133. this._colors = new Array();
  54134. this._uvs = new Array();
  54135. this._index = 0; // indices index
  54136. this._updatable = true;
  54137. this._pickable = false;
  54138. this._isVisibilityBoxLocked = false;
  54139. this._alwaysVisible = false;
  54140. this._depthSort = false;
  54141. this._shapeCounter = 0;
  54142. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  54143. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54144. this._computeParticleColor = true;
  54145. this._computeParticleTexture = true;
  54146. this._computeParticleRotation = true;
  54147. this._computeParticleVertex = false;
  54148. this._computeBoundingBox = false;
  54149. this._depthSortParticles = true;
  54150. this._cam_axisZ = BABYLON.Vector3.Zero();
  54151. this._cam_axisY = BABYLON.Vector3.Zero();
  54152. this._cam_axisX = BABYLON.Vector3.Zero();
  54153. this._axisZ = BABYLON.Axis.Z;
  54154. this._camDir = BABYLON.Vector3.Zero();
  54155. this._camInvertedPosition = BABYLON.Vector3.Zero();
  54156. this._rotMatrix = new BABYLON.Matrix();
  54157. this._invertMatrix = new BABYLON.Matrix();
  54158. this._rotated = BABYLON.Vector3.Zero();
  54159. this._quaternion = new BABYLON.Quaternion();
  54160. this._vertex = BABYLON.Vector3.Zero();
  54161. this._normal = BABYLON.Vector3.Zero();
  54162. this._yaw = 0.0;
  54163. this._pitch = 0.0;
  54164. this._roll = 0.0;
  54165. this._halfroll = 0.0;
  54166. this._halfpitch = 0.0;
  54167. this._halfyaw = 0.0;
  54168. this._sinRoll = 0.0;
  54169. this._cosRoll = 0.0;
  54170. this._sinPitch = 0.0;
  54171. this._cosPitch = 0.0;
  54172. this._sinYaw = 0.0;
  54173. this._cosYaw = 0.0;
  54174. this._mustUnrotateFixedNormals = false;
  54175. this._minimum = BABYLON.Vector3.Zero();
  54176. this._maximum = BABYLON.Vector3.Zero();
  54177. this._minBbox = BABYLON.Vector3.Zero();
  54178. this._maxBbox = BABYLON.Vector3.Zero();
  54179. this._particlesIntersect = false;
  54180. this._depthSortFunction = function (p1, p2) {
  54181. return (p2.sqDistance - p1.sqDistance);
  54182. };
  54183. this._needs32Bits = false;
  54184. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  54185. this._scaledPivot = BABYLON.Vector3.Zero();
  54186. this._particleHasParent = false;
  54187. this.name = name;
  54188. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54189. this._camera = scene.activeCamera;
  54190. this._pickable = options ? options.isPickable : false;
  54191. this._depthSort = options ? options.enableDepthSort : false;
  54192. this._particlesIntersect = options ? options.particleIntersection : false;
  54193. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  54194. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  54195. if (options && options.updatable) {
  54196. this._updatable = options.updatable;
  54197. }
  54198. else {
  54199. this._updatable = true;
  54200. }
  54201. if (this._pickable) {
  54202. this.pickedParticles = [];
  54203. }
  54204. if (this._depthSort) {
  54205. this.depthSortedParticles = [];
  54206. }
  54207. }
  54208. /**
  54209. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54210. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54211. * @returns the created mesh
  54212. */
  54213. SolidParticleSystem.prototype.buildMesh = function () {
  54214. if (this.nbParticles === 0) {
  54215. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54216. this.addShape(triangle, 1);
  54217. triangle.dispose();
  54218. }
  54219. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  54220. this._positions32 = new Float32Array(this._positions);
  54221. this._uvs32 = new Float32Array(this._uvs);
  54222. this._colors32 = new Float32Array(this._colors);
  54223. if (this.recomputeNormals) {
  54224. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  54225. }
  54226. this._normals32 = new Float32Array(this._normals);
  54227. this._fixedNormal32 = new Float32Array(this._normals);
  54228. if (this._mustUnrotateFixedNormals) {
  54229. this._unrotateFixedNormals();
  54230. }
  54231. var vertexData = new BABYLON.VertexData();
  54232. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  54233. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54234. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54235. if (this._uvs32) {
  54236. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54237. ;
  54238. }
  54239. if (this._colors32) {
  54240. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54241. }
  54242. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54243. vertexData.applyToMesh(mesh, this._updatable);
  54244. this.mesh = mesh;
  54245. this.mesh.isPickable = this._pickable;
  54246. // free memory
  54247. if (!this._depthSort) {
  54248. this._indices = null;
  54249. }
  54250. this._positions = null;
  54251. this._normals = null;
  54252. this._uvs = null;
  54253. this._colors = null;
  54254. if (!this._updatable) {
  54255. this.particles.length = 0;
  54256. }
  54257. return mesh;
  54258. };
  54259. /**
  54260. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54261. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54262. * Thus the particles generated from `digest()` have their property `position` set yet.
  54263. * @param mesh ( Mesh ) is the mesh to be digested
  54264. * @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
  54265. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54266. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54267. * @returns the current SPS
  54268. */
  54269. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54270. var size = (options && options.facetNb) || 1;
  54271. var number = (options && options.number) || 0;
  54272. var delta = (options && options.delta) || 0;
  54273. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54274. var meshInd = mesh.getIndices();
  54275. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54276. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54277. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54278. var f = 0; // facet counter
  54279. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54280. // compute size from number
  54281. if (number) {
  54282. number = (number > totalFacets) ? totalFacets : number;
  54283. size = Math.round(totalFacets / number);
  54284. delta = 0;
  54285. }
  54286. else {
  54287. size = (size > totalFacets) ? totalFacets : size;
  54288. }
  54289. var facetPos = []; // submesh positions
  54290. var facetInd = []; // submesh indices
  54291. var facetUV = []; // submesh UV
  54292. var facetCol = []; // submesh colors
  54293. var barycenter = BABYLON.Vector3.Zero();
  54294. var sizeO = size;
  54295. while (f < totalFacets) {
  54296. size = sizeO + Math.floor((1 + delta) * Math.random());
  54297. if (f > totalFacets - size) {
  54298. size = totalFacets - f;
  54299. }
  54300. // reset temp arrays
  54301. facetPos.length = 0;
  54302. facetInd.length = 0;
  54303. facetUV.length = 0;
  54304. facetCol.length = 0;
  54305. // iterate over "size" facets
  54306. var fi = 0;
  54307. for (var j = f * 3; j < (f + size) * 3; j++) {
  54308. facetInd.push(fi);
  54309. var i = meshInd[j];
  54310. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54311. if (meshUV) {
  54312. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54313. }
  54314. if (meshCol) {
  54315. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54316. }
  54317. fi++;
  54318. }
  54319. // create a model shape for each single particle
  54320. var idx = this.nbParticles;
  54321. var shape = this._posToShape(facetPos);
  54322. var shapeUV = this._uvsToShapeUV(facetUV);
  54323. // compute the barycenter of the shape
  54324. var v;
  54325. for (v = 0; v < shape.length; v++) {
  54326. barycenter.addInPlace(shape[v]);
  54327. }
  54328. barycenter.scaleInPlace(1 / shape.length);
  54329. // shift the shape from its barycenter to the origin
  54330. for (v = 0; v < shape.length; v++) {
  54331. shape[v].subtractInPlace(barycenter);
  54332. }
  54333. var bInfo;
  54334. if (this._particlesIntersect) {
  54335. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54336. }
  54337. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  54338. // add the particle in the SPS
  54339. var currentPos = this._positions.length;
  54340. var currentInd = this._indices.length;
  54341. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54342. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  54343. // initialize the particle position
  54344. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54345. this._index += shape.length;
  54346. idx++;
  54347. this.nbParticles++;
  54348. this._shapeCounter++;
  54349. f += size;
  54350. }
  54351. return this;
  54352. };
  54353. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54354. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54355. var index = 0;
  54356. var idx = 0;
  54357. for (var p = 0; p < this.particles.length; p++) {
  54358. this._particle = this.particles[p];
  54359. this._shape = this._particle._model._shape;
  54360. if (this._particle.rotationQuaternion) {
  54361. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54362. }
  54363. else {
  54364. this._yaw = this._particle.rotation.y;
  54365. this._pitch = this._particle.rotation.x;
  54366. this._roll = this._particle.rotation.z;
  54367. this._quaternionRotationYPR();
  54368. }
  54369. this._quaternionToRotationMatrix();
  54370. this._rotMatrix.invertToRef(this._invertMatrix);
  54371. for (var pt = 0; pt < this._shape.length; pt++) {
  54372. idx = index + pt * 3;
  54373. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54374. this._fixedNormal32[idx] = this._normal.x;
  54375. this._fixedNormal32[idx + 1] = this._normal.y;
  54376. this._fixedNormal32[idx + 2] = this._normal.z;
  54377. }
  54378. index = idx + 3;
  54379. }
  54380. };
  54381. //reset copy
  54382. SolidParticleSystem.prototype._resetCopy = function () {
  54383. this._copy.position.x = 0;
  54384. this._copy.position.y = 0;
  54385. this._copy.position.z = 0;
  54386. this._copy.rotation.x = 0;
  54387. this._copy.rotation.y = 0;
  54388. this._copy.rotation.z = 0;
  54389. this._copy.rotationQuaternion = null;
  54390. this._copy.scaling.x = 1.0;
  54391. this._copy.scaling.y = 1.0;
  54392. this._copy.scaling.z = 1.0;
  54393. this._copy.uvs.x = 0;
  54394. this._copy.uvs.y = 0;
  54395. this._copy.uvs.z = 1.0;
  54396. this._copy.uvs.w = 1.0;
  54397. this._copy.color = null;
  54398. this._copy.translateFromPivot = false;
  54399. };
  54400. // _meshBuilder : inserts the shape model in the global SPS mesh
  54401. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54402. var i;
  54403. var u = 0;
  54404. var c = 0;
  54405. var n = 0;
  54406. this._resetCopy();
  54407. if (options && options.positionFunction) {
  54408. options.positionFunction(this._copy, idx, idxInShape);
  54409. this._mustUnrotateFixedNormals = true;
  54410. }
  54411. if (this._copy.rotationQuaternion) {
  54412. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54413. }
  54414. else {
  54415. this._yaw = this._copy.rotation.y;
  54416. this._pitch = this._copy.rotation.x;
  54417. this._roll = this._copy.rotation.z;
  54418. this._quaternionRotationYPR();
  54419. }
  54420. this._quaternionToRotationMatrix();
  54421. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54422. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54423. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54424. if (this._copy.translateFromPivot) {
  54425. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54426. }
  54427. else {
  54428. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54429. }
  54430. for (i = 0; i < shape.length; i++) {
  54431. this._vertex.x = shape[i].x;
  54432. this._vertex.y = shape[i].y;
  54433. this._vertex.z = shape[i].z;
  54434. if (options && options.vertexFunction) {
  54435. options.vertexFunction(this._copy, this._vertex, i);
  54436. }
  54437. this._vertex.x *= this._copy.scaling.x;
  54438. this._vertex.y *= this._copy.scaling.y;
  54439. this._vertex.z *= this._copy.scaling.z;
  54440. this._vertex.x -= this._scaledPivot.x;
  54441. this._vertex.y -= this._scaledPivot.y;
  54442. this._vertex.z -= this._scaledPivot.z;
  54443. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54444. this._rotated.addInPlace(this._pivotBackTranslation);
  54445. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54446. if (meshUV) {
  54447. 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);
  54448. u += 2;
  54449. }
  54450. if (this._copy.color) {
  54451. this._color = this._copy.color;
  54452. }
  54453. else if (meshCol && meshCol[c] !== undefined) {
  54454. this._color.r = meshCol[c];
  54455. this._color.g = meshCol[c + 1];
  54456. this._color.b = meshCol[c + 2];
  54457. this._color.a = meshCol[c + 3];
  54458. }
  54459. else {
  54460. this._color.r = 1.0;
  54461. this._color.g = 1.0;
  54462. this._color.b = 1.0;
  54463. this._color.a = 1.0;
  54464. }
  54465. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54466. c += 4;
  54467. if (!this.recomputeNormals && meshNor) {
  54468. this._normal.x = meshNor[n];
  54469. this._normal.y = meshNor[n + 1];
  54470. this._normal.z = meshNor[n + 2];
  54471. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54472. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54473. n += 3;
  54474. }
  54475. }
  54476. for (i = 0; i < meshInd.length; i++) {
  54477. var current_ind = p + meshInd[i];
  54478. indices.push(current_ind);
  54479. if (current_ind > 65535) {
  54480. this._needs32Bits = true;
  54481. }
  54482. }
  54483. if (this._pickable) {
  54484. var nbfaces = meshInd.length / 3;
  54485. for (i = 0; i < nbfaces; i++) {
  54486. this.pickedParticles.push({ idx: idx, faceId: i });
  54487. }
  54488. }
  54489. if (this._depthSort) {
  54490. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54491. }
  54492. return this._copy;
  54493. };
  54494. // returns a shape array from positions array
  54495. SolidParticleSystem.prototype._posToShape = function (positions) {
  54496. var shape = [];
  54497. for (var i = 0; i < positions.length; i += 3) {
  54498. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54499. }
  54500. return shape;
  54501. };
  54502. // returns a shapeUV array from a Vector4 uvs
  54503. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54504. var shapeUV = [];
  54505. if (uvs) {
  54506. for (var i = 0; i < uvs.length; i++)
  54507. shapeUV.push(uvs[i]);
  54508. }
  54509. return shapeUV;
  54510. };
  54511. // adds a new particle object in the particles array
  54512. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54513. if (bInfo === void 0) { bInfo = null; }
  54514. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54515. this.particles.push(sp);
  54516. return sp;
  54517. };
  54518. /**
  54519. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54520. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54521. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54522. * @param nb (positive integer) the number of particles to be created from this model
  54523. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54524. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54525. * @returns the number of shapes in the system
  54526. */
  54527. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54528. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54529. var meshInd = mesh.getIndices();
  54530. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54531. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54532. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54533. var bbInfo;
  54534. if (this._particlesIntersect) {
  54535. bbInfo = mesh.getBoundingInfo();
  54536. }
  54537. var shape = this._posToShape(meshPos);
  54538. var shapeUV = this._uvsToShapeUV(meshUV);
  54539. var posfunc = options ? options.positionFunction : null;
  54540. var vtxfunc = options ? options.vertexFunction : null;
  54541. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54542. // particles
  54543. var sp;
  54544. var currentCopy;
  54545. var idx = this.nbParticles;
  54546. for (var i = 0; i < nb; i++) {
  54547. var currentPos = this._positions.length;
  54548. var currentInd = this._indices.length;
  54549. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54550. if (this._updatable) {
  54551. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54552. sp.position.copyFrom(currentCopy.position);
  54553. sp.rotation.copyFrom(currentCopy.rotation);
  54554. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54555. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54556. }
  54557. if (currentCopy.color && sp.color) {
  54558. sp.color.copyFrom(currentCopy.color);
  54559. }
  54560. sp.scaling.copyFrom(currentCopy.scaling);
  54561. sp.uvs.copyFrom(currentCopy.uvs);
  54562. }
  54563. this._index += shape.length;
  54564. idx++;
  54565. }
  54566. this.nbParticles += nb;
  54567. this._shapeCounter++;
  54568. return this._shapeCounter - 1;
  54569. };
  54570. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54571. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54572. this._resetCopy();
  54573. if (particle._model._positionFunction) {
  54574. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54575. }
  54576. if (this._copy.rotationQuaternion) {
  54577. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54578. }
  54579. else {
  54580. this._yaw = this._copy.rotation.y;
  54581. this._pitch = this._copy.rotation.x;
  54582. this._roll = this._copy.rotation.z;
  54583. this._quaternionRotationYPR();
  54584. }
  54585. this._quaternionToRotationMatrix();
  54586. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54587. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54588. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54589. if (this._copy.translateFromPivot) {
  54590. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54591. }
  54592. else {
  54593. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54594. }
  54595. this._shape = particle._model._shape;
  54596. for (var pt = 0; pt < this._shape.length; pt++) {
  54597. this._vertex.x = this._shape[pt].x;
  54598. this._vertex.y = this._shape[pt].y;
  54599. this._vertex.z = this._shape[pt].z;
  54600. if (particle._model._vertexFunction) {
  54601. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54602. }
  54603. this._vertex.x *= this._copy.scaling.x;
  54604. this._vertex.y *= this._copy.scaling.y;
  54605. this._vertex.z *= this._copy.scaling.z;
  54606. this._vertex.x -= this._scaledPivot.x;
  54607. this._vertex.y -= this._scaledPivot.y;
  54608. this._vertex.z -= this._scaledPivot.z;
  54609. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54610. this._rotated.addInPlace(this._pivotBackTranslation);
  54611. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54612. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54613. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54614. }
  54615. particle.position.x = 0.0;
  54616. particle.position.y = 0.0;
  54617. particle.position.z = 0.0;
  54618. particle.rotation.x = 0.0;
  54619. particle.rotation.y = 0.0;
  54620. particle.rotation.z = 0.0;
  54621. particle.rotationQuaternion = null;
  54622. particle.scaling.x = 1.0;
  54623. particle.scaling.y = 1.0;
  54624. particle.scaling.z = 1.0;
  54625. particle.uvs.x = 0.0;
  54626. particle.uvs.y = 0.0;
  54627. particle.uvs.z = 1.0;
  54628. particle.uvs.w = 1.0;
  54629. particle.pivot.x = 0.0;
  54630. particle.pivot.y = 0.0;
  54631. particle.pivot.z = 0.0;
  54632. particle.translateFromPivot = false;
  54633. particle.parentId = null;
  54634. };
  54635. /**
  54636. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54637. * @returns the SPS.
  54638. */
  54639. SolidParticleSystem.prototype.rebuildMesh = function () {
  54640. for (var p = 0; p < this.particles.length; p++) {
  54641. this._rebuildParticle(this.particles[p]);
  54642. }
  54643. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54644. return this;
  54645. };
  54646. /**
  54647. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54648. * This method calls `updateParticle()` for each particle of the SPS.
  54649. * For an animated SPS, it is usually called within the render loop.
  54650. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54651. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54652. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54653. * @returns the SPS.
  54654. */
  54655. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54656. if (start === void 0) { start = 0; }
  54657. if (end === void 0) { end = this.nbParticles - 1; }
  54658. if (update === void 0) { update = true; }
  54659. if (!this._updatable) {
  54660. return this;
  54661. }
  54662. // custom beforeUpdate
  54663. this.beforeUpdateParticles(start, end, update);
  54664. this._cam_axisX.x = 1.0;
  54665. this._cam_axisX.y = 0.0;
  54666. this._cam_axisX.z = 0.0;
  54667. this._cam_axisY.x = 0.0;
  54668. this._cam_axisY.y = 1.0;
  54669. this._cam_axisY.z = 0.0;
  54670. this._cam_axisZ.x = 0.0;
  54671. this._cam_axisZ.y = 0.0;
  54672. this._cam_axisZ.z = 1.0;
  54673. // cases when the World Matrix is to be computed first
  54674. if (this.billboard || this._depthSort) {
  54675. this.mesh.computeWorldMatrix(true);
  54676. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54677. }
  54678. // if the particles will always face the camera
  54679. if (this.billboard) {
  54680. // compute the camera position and un-rotate it by the current mesh rotation
  54681. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54682. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54683. this._cam_axisZ.normalize();
  54684. // same for camera up vector extracted from the cam view matrix
  54685. var view = this._camera.getViewMatrix(true);
  54686. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54687. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54688. this._cam_axisY.normalize();
  54689. this._cam_axisX.normalize();
  54690. }
  54691. // if depthSort, compute the camera global position in the mesh local system
  54692. if (this._depthSort) {
  54693. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54694. }
  54695. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54696. var idx = 0; // current position index in the global array positions32
  54697. var index = 0; // position start index in the global array positions32 of the current particle
  54698. var colidx = 0; // current color index in the global array colors32
  54699. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54700. var uvidx = 0; // current uv index in the global array uvs32
  54701. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54702. var pt = 0; // current index in the particle model shape
  54703. if (this.mesh.isFacetDataEnabled) {
  54704. this._computeBoundingBox = true;
  54705. }
  54706. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54707. if (this._computeBoundingBox) {
  54708. if (start == 0 && end == this.nbParticles - 1) {
  54709. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54710. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54711. }
  54712. else {
  54713. if (this.mesh._boundingInfo) {
  54714. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54715. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54716. }
  54717. }
  54718. }
  54719. // particle loop
  54720. index = this.particles[start]._pos;
  54721. var vpos = (index / 3) | 0;
  54722. colorIndex = vpos * 4;
  54723. uvIndex = vpos * 2;
  54724. for (var p = start; p <= end; p++) {
  54725. this._particle = this.particles[p];
  54726. this._shape = this._particle._model._shape;
  54727. this._shapeUV = this._particle._model._shapeUV;
  54728. // call to custom user function to update the particle properties
  54729. this.updateParticle(this._particle);
  54730. // camera-particle distance for depth sorting
  54731. if (this._depthSort && this._depthSortParticles) {
  54732. var dsp = this.depthSortedParticles[p];
  54733. dsp.ind = this._particle._ind;
  54734. dsp.indicesLength = this._particle._model._indicesLength;
  54735. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54736. }
  54737. // skip the computations for inactive or already invisible particles
  54738. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54739. // increment indexes for the next particle
  54740. pt = this._shape.length;
  54741. index += pt * 3;
  54742. colorIndex += pt * 4;
  54743. uvIndex += pt * 2;
  54744. continue;
  54745. }
  54746. if (this._particle.isVisible) {
  54747. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54748. this._particleHasParent = (this._particle.parentId !== null);
  54749. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54750. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54751. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54752. // particle rotation matrix
  54753. if (this.billboard) {
  54754. this._particle.rotation.x = 0.0;
  54755. this._particle.rotation.y = 0.0;
  54756. }
  54757. if (this._computeParticleRotation || this.billboard) {
  54758. if (this._particle.rotationQuaternion) {
  54759. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54760. }
  54761. else {
  54762. this._yaw = this._particle.rotation.y;
  54763. this._pitch = this._particle.rotation.x;
  54764. this._roll = this._particle.rotation.z;
  54765. this._quaternionRotationYPR();
  54766. }
  54767. this._quaternionToRotationMatrix();
  54768. }
  54769. if (this._particleHasParent) {
  54770. this._parent = this.particles[this._particle.parentId];
  54771. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  54772. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  54773. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  54774. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54775. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54776. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54777. if (this._computeParticleRotation || this.billboard) {
  54778. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  54779. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  54780. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  54781. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  54782. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  54783. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  54784. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  54785. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  54786. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  54787. }
  54788. }
  54789. else {
  54790. this._particle._globalPosition.x = this._particle.position.x;
  54791. this._particle._globalPosition.y = this._particle.position.y;
  54792. this._particle._globalPosition.z = this._particle.position.z;
  54793. if (this._computeParticleRotation || this.billboard) {
  54794. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54795. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54796. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54797. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54798. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54799. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54800. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54801. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54802. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54803. }
  54804. }
  54805. if (this._particle.translateFromPivot) {
  54806. this._pivotBackTranslation.x = 0.0;
  54807. this._pivotBackTranslation.y = 0.0;
  54808. this._pivotBackTranslation.z = 0.0;
  54809. }
  54810. else {
  54811. this._pivotBackTranslation.x = this._scaledPivot.x;
  54812. this._pivotBackTranslation.y = this._scaledPivot.y;
  54813. this._pivotBackTranslation.z = this._scaledPivot.z;
  54814. }
  54815. // particle vertex loop
  54816. for (pt = 0; pt < this._shape.length; pt++) {
  54817. idx = index + pt * 3;
  54818. colidx = colorIndex + pt * 4;
  54819. uvidx = uvIndex + pt * 2;
  54820. this._vertex.x = this._shape[pt].x;
  54821. this._vertex.y = this._shape[pt].y;
  54822. this._vertex.z = this._shape[pt].z;
  54823. if (this._computeParticleVertex) {
  54824. this.updateParticleVertex(this._particle, this._vertex, pt);
  54825. }
  54826. // positions
  54827. this._vertex.x *= this._particle.scaling.x;
  54828. this._vertex.y *= this._particle.scaling.y;
  54829. this._vertex.z *= this._particle.scaling.z;
  54830. this._vertex.x -= this._scaledPivot.x;
  54831. this._vertex.y -= this._scaledPivot.y;
  54832. this._vertex.z -= this._scaledPivot.z;
  54833. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54834. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54835. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54836. this._rotated.x += this._pivotBackTranslation.x;
  54837. this._rotated.y += this._pivotBackTranslation.y;
  54838. this._rotated.z += this._pivotBackTranslation.z;
  54839. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54840. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  54841. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  54842. if (this._computeBoundingBox) {
  54843. if (this._positions32[idx] < this._minimum.x) {
  54844. this._minimum.x = this._positions32[idx];
  54845. }
  54846. if (this._positions32[idx] > this._maximum.x) {
  54847. this._maximum.x = this._positions32[idx];
  54848. }
  54849. if (this._positions32[idx + 1] < this._minimum.y) {
  54850. this._minimum.y = this._positions32[idx + 1];
  54851. }
  54852. if (this._positions32[idx + 1] > this._maximum.y) {
  54853. this._maximum.y = this._positions32[idx + 1];
  54854. }
  54855. if (this._positions32[idx + 2] < this._minimum.z) {
  54856. this._minimum.z = this._positions32[idx + 2];
  54857. }
  54858. if (this._positions32[idx + 2] > this._maximum.z) {
  54859. this._maximum.z = this._positions32[idx + 2];
  54860. }
  54861. }
  54862. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54863. if (!this._computeParticleVertex) {
  54864. this._normal.x = this._fixedNormal32[idx];
  54865. this._normal.y = this._fixedNormal32[idx + 1];
  54866. this._normal.z = this._fixedNormal32[idx + 2];
  54867. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54868. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54869. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54870. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54871. 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;
  54872. 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;
  54873. }
  54874. if (this._computeParticleColor && this._particle.color) {
  54875. this._colors32[colidx] = this._particle.color.r;
  54876. this._colors32[colidx + 1] = this._particle.color.g;
  54877. this._colors32[colidx + 2] = this._particle.color.b;
  54878. this._colors32[colidx + 3] = this._particle.color.a;
  54879. }
  54880. if (this._computeParticleTexture) {
  54881. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54882. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54883. }
  54884. }
  54885. }
  54886. else {
  54887. this._particle._stillInvisible = true; // mark the particle as invisible
  54888. for (pt = 0; pt < this._shape.length; pt++) {
  54889. idx = index + pt * 3;
  54890. colidx = colorIndex + pt * 4;
  54891. uvidx = uvIndex + pt * 2;
  54892. this._positions32[idx] = 0.0;
  54893. this._positions32[idx + 1] = 0.0;
  54894. this._positions32[idx + 2] = 0.0;
  54895. this._normals32[idx] = 0.0;
  54896. this._normals32[idx + 1] = 0.0;
  54897. this._normals32[idx + 2] = 0.0;
  54898. if (this._computeParticleColor && this._particle.color) {
  54899. this._colors32[colidx] = this._particle.color.r;
  54900. this._colors32[colidx + 1] = this._particle.color.g;
  54901. this._colors32[colidx + 2] = this._particle.color.b;
  54902. this._colors32[colidx + 3] = this._particle.color.a;
  54903. }
  54904. if (this._computeParticleTexture) {
  54905. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54906. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54907. }
  54908. }
  54909. }
  54910. // if the particle intersections must be computed : update the bbInfo
  54911. if (this._particlesIntersect) {
  54912. var bInfo = this._particle._boundingInfo;
  54913. var bBox = bInfo.boundingBox;
  54914. var bSphere = bInfo.boundingSphere;
  54915. if (!this._bSphereOnly) {
  54916. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54917. for (var b = 0; b < bBox.vectors.length; b++) {
  54918. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54919. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54920. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54921. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54922. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54923. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54924. 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;
  54925. 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;
  54926. 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;
  54927. }
  54928. bBox._update(this.mesh._worldMatrix);
  54929. }
  54930. // place and scale the particle bouding sphere in the SPS local system, then update it
  54931. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54932. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54933. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54934. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54935. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54936. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54937. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54938. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54939. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54940. 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));
  54941. bSphere._update(this.mesh._worldMatrix);
  54942. }
  54943. // increment indexes for the next particle
  54944. index = idx + 3;
  54945. colorIndex = colidx + 4;
  54946. uvIndex = uvidx + 2;
  54947. }
  54948. // if the VBO must be updated
  54949. if (update) {
  54950. if (this._computeParticleColor) {
  54951. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54952. }
  54953. if (this._computeParticleTexture) {
  54954. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54955. }
  54956. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54957. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54958. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54959. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54960. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54961. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54962. for (var i = 0; i < this._normals32.length; i++) {
  54963. this._fixedNormal32[i] = this._normals32[i];
  54964. }
  54965. }
  54966. if (!this.mesh.areNormalsFrozen) {
  54967. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54968. }
  54969. }
  54970. if (this._depthSort && this._depthSortParticles) {
  54971. this.depthSortedParticles.sort(this._depthSortFunction);
  54972. var dspl = this.depthSortedParticles.length;
  54973. var sorted = 0;
  54974. var lind = 0;
  54975. var sind = 0;
  54976. var sid = 0;
  54977. for (sorted = 0; sorted < dspl; sorted++) {
  54978. lind = this.depthSortedParticles[sorted].indicesLength;
  54979. sind = this.depthSortedParticles[sorted].ind;
  54980. for (var i = 0; i < lind; i++) {
  54981. this._indices32[sid] = this._indices[sind + i];
  54982. sid++;
  54983. }
  54984. }
  54985. this.mesh.updateIndices(this._indices32);
  54986. }
  54987. }
  54988. if (this._computeBoundingBox) {
  54989. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54990. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54991. }
  54992. this.afterUpdateParticles(start, end, update);
  54993. return this;
  54994. };
  54995. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54996. this._halfroll = this._roll * 0.5;
  54997. this._halfpitch = this._pitch * 0.5;
  54998. this._halfyaw = this._yaw * 0.5;
  54999. this._sinRoll = Math.sin(this._halfroll);
  55000. this._cosRoll = Math.cos(this._halfroll);
  55001. this._sinPitch = Math.sin(this._halfpitch);
  55002. this._cosPitch = Math.cos(this._halfpitch);
  55003. this._sinYaw = Math.sin(this._halfyaw);
  55004. this._cosYaw = Math.cos(this._halfyaw);
  55005. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  55006. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  55007. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  55008. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  55009. };
  55010. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  55011. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  55012. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  55013. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  55014. this._rotMatrix.m[3] = 0;
  55015. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  55016. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  55017. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  55018. this._rotMatrix.m[7] = 0;
  55019. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  55020. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  55021. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  55022. this._rotMatrix.m[11] = 0;
  55023. this._rotMatrix.m[12] = 0;
  55024. this._rotMatrix.m[13] = 0;
  55025. this._rotMatrix.m[14] = 0;
  55026. this._rotMatrix.m[15] = 1.0;
  55027. };
  55028. /**
  55029. * Disposes the SPS.
  55030. */
  55031. SolidParticleSystem.prototype.dispose = function () {
  55032. this.mesh.dispose();
  55033. this.vars = null;
  55034. // drop references to internal big arrays for the GC
  55035. this._positions = null;
  55036. this._indices = null;
  55037. this._normals = null;
  55038. this._uvs = null;
  55039. this._colors = null;
  55040. this._indices32 = null;
  55041. this._positions32 = null;
  55042. this._normals32 = null;
  55043. this._fixedNormal32 = null;
  55044. this._uvs32 = null;
  55045. this._colors32 = null;
  55046. this.pickedParticles = null;
  55047. };
  55048. /**
  55049. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  55050. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55051. * @returns the SPS.
  55052. */
  55053. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  55054. if (!this._isVisibilityBoxLocked) {
  55055. this.mesh.refreshBoundingInfo();
  55056. }
  55057. return this;
  55058. };
  55059. /**
  55060. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  55061. * @param size the size (float) of the visibility box
  55062. * note : this doesn't lock the SPS mesh bounding box.
  55063. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55064. */
  55065. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  55066. var vis = size / 2;
  55067. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  55068. };
  55069. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  55070. /**
  55071. * Gets whether the SPS as always visible or not
  55072. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55073. */
  55074. get: function () {
  55075. return this._alwaysVisible;
  55076. },
  55077. /**
  55078. * Sets the SPS as always visible or not
  55079. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55080. */
  55081. set: function (val) {
  55082. this._alwaysVisible = val;
  55083. this.mesh.alwaysSelectAsActiveMesh = val;
  55084. },
  55085. enumerable: true,
  55086. configurable: true
  55087. });
  55088. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  55089. /**
  55090. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55091. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55092. */
  55093. get: function () {
  55094. return this._isVisibilityBoxLocked;
  55095. },
  55096. /**
  55097. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55098. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55099. */
  55100. set: function (val) {
  55101. this._isVisibilityBoxLocked = val;
  55102. var boundingInfo = this.mesh.getBoundingInfo();
  55103. boundingInfo.isLocked = val;
  55104. },
  55105. enumerable: true,
  55106. configurable: true
  55107. });
  55108. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55109. /**
  55110. * Gets if `setParticles()` computes the particle rotations or not.
  55111. * Default value : true. The SPS is faster when it's set to false.
  55112. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55113. */
  55114. get: function () {
  55115. return this._computeParticleRotation;
  55116. },
  55117. /**
  55118. * Tells to `setParticles()` to compute the particle rotations or not.
  55119. * Default value : true. The SPS is faster when it's set to false.
  55120. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55121. */
  55122. set: function (val) {
  55123. this._computeParticleRotation = val;
  55124. },
  55125. enumerable: true,
  55126. configurable: true
  55127. });
  55128. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55129. /**
  55130. * Gets if `setParticles()` computes the particle colors or not.
  55131. * Default value : true. The SPS is faster when it's set to false.
  55132. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55133. */
  55134. get: function () {
  55135. return this._computeParticleColor;
  55136. },
  55137. /**
  55138. * Tells to `setParticles()` to compute the particle colors or not.
  55139. * Default value : true. The SPS is faster when it's set to false.
  55140. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55141. */
  55142. set: function (val) {
  55143. this._computeParticleColor = val;
  55144. },
  55145. enumerable: true,
  55146. configurable: true
  55147. });
  55148. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55149. /**
  55150. * Gets if `setParticles()` computes the particle textures or not.
  55151. * Default value : true. The SPS is faster when it's set to false.
  55152. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  55153. */
  55154. get: function () {
  55155. return this._computeParticleTexture;
  55156. },
  55157. set: function (val) {
  55158. this._computeParticleTexture = val;
  55159. },
  55160. enumerable: true,
  55161. configurable: true
  55162. });
  55163. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  55164. /**
  55165. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  55166. * Default value : false. The SPS is faster when it's set to false.
  55167. * Note : the particle custom vertex positions aren't stored values.
  55168. */
  55169. get: function () {
  55170. return this._computeParticleVertex;
  55171. },
  55172. /**
  55173. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  55174. * Default value : false. The SPS is faster when it's set to false.
  55175. * Note : the particle custom vertex positions aren't stored values.
  55176. */
  55177. set: function (val) {
  55178. this._computeParticleVertex = val;
  55179. },
  55180. enumerable: true,
  55181. configurable: true
  55182. });
  55183. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  55184. /**
  55185. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  55186. */
  55187. get: function () {
  55188. return this._computeBoundingBox;
  55189. },
  55190. /**
  55191. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  55192. */
  55193. set: function (val) {
  55194. this._computeBoundingBox = val;
  55195. },
  55196. enumerable: true,
  55197. configurable: true
  55198. });
  55199. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  55200. /**
  55201. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  55202. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55203. * Default : `true`
  55204. */
  55205. get: function () {
  55206. return this._depthSortParticles;
  55207. },
  55208. /**
  55209. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  55210. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55211. * Default : `true`
  55212. */
  55213. set: function (val) {
  55214. this._depthSortParticles = val;
  55215. },
  55216. enumerable: true,
  55217. configurable: true
  55218. });
  55219. // =======================================================================
  55220. // Particle behavior logic
  55221. // these following methods may be overwritten by the user to fit his needs
  55222. /**
  55223. * This function does nothing. It may be overwritten to set all the particle first values.
  55224. * The SPS doesn't call this function, you may have to call it by your own.
  55225. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55226. */
  55227. SolidParticleSystem.prototype.initParticles = function () {
  55228. };
  55229. /**
  55230. * This function does nothing. It may be overwritten to recycle a particle.
  55231. * The SPS doesn't call this function, you may have to call it by your own.
  55232. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55233. * @param particle The particle to recycle
  55234. * @returns the recycled particle
  55235. */
  55236. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55237. return particle;
  55238. };
  55239. /**
  55240. * Updates a particle : this function should be overwritten by the user.
  55241. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55242. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55243. * @example : just set a particle position or velocity and recycle conditions
  55244. * @param particle The particle to update
  55245. * @returns the updated particle
  55246. */
  55247. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55248. return particle;
  55249. };
  55250. /**
  55251. * Updates a vertex of a particle : it can be overwritten by the user.
  55252. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55253. * @param particle the current particle
  55254. * @param vertex the current index of the current particle
  55255. * @param pt the index of the current vertex in the particle shape
  55256. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55257. * @example : just set a vertex particle position
  55258. * @returns the updated vertex
  55259. */
  55260. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55261. return vertex;
  55262. };
  55263. /**
  55264. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55265. * This does nothing and may be overwritten by the user.
  55266. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55267. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55268. * @param update the boolean update value actually passed to setParticles()
  55269. */
  55270. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55271. };
  55272. /**
  55273. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55274. * This will be passed three parameters.
  55275. * This does nothing and may be overwritten by the user.
  55276. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55277. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55278. * @param update the boolean update value actually passed to setParticles()
  55279. */
  55280. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55281. };
  55282. return SolidParticleSystem;
  55283. }());
  55284. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55285. })(BABYLON || (BABYLON = {}));
  55286. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55287. "use strict";
  55288. var BABYLON;
  55289. (function (BABYLON) {
  55290. var ShaderMaterial = /** @class */ (function (_super) {
  55291. __extends(ShaderMaterial, _super);
  55292. function ShaderMaterial(name, scene, shaderPath, options) {
  55293. var _this = _super.call(this, name, scene) || this;
  55294. _this._textures = {};
  55295. _this._textureArrays = {};
  55296. _this._floats = {};
  55297. _this._ints = {};
  55298. _this._floatsArrays = {};
  55299. _this._colors3 = {};
  55300. _this._colors3Arrays = {};
  55301. _this._colors4 = {};
  55302. _this._vectors2 = {};
  55303. _this._vectors3 = {};
  55304. _this._vectors4 = {};
  55305. _this._matrices = {};
  55306. _this._matrices3x3 = {};
  55307. _this._matrices2x2 = {};
  55308. _this._vectors2Arrays = {};
  55309. _this._vectors3Arrays = {};
  55310. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  55311. _this._shaderPath = shaderPath;
  55312. options.needAlphaBlending = options.needAlphaBlending || false;
  55313. options.needAlphaTesting = options.needAlphaTesting || false;
  55314. options.attributes = options.attributes || ["position", "normal", "uv"];
  55315. options.uniforms = options.uniforms || ["worldViewProjection"];
  55316. options.uniformBuffers = options.uniformBuffers || [];
  55317. options.samplers = options.samplers || [];
  55318. options.defines = options.defines || [];
  55319. _this._options = options;
  55320. return _this;
  55321. }
  55322. ShaderMaterial.prototype.getClassName = function () {
  55323. return "ShaderMaterial";
  55324. };
  55325. ShaderMaterial.prototype.needAlphaBlending = function () {
  55326. return this._options.needAlphaBlending;
  55327. };
  55328. ShaderMaterial.prototype.needAlphaTesting = function () {
  55329. return this._options.needAlphaTesting;
  55330. };
  55331. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  55332. if (this._options.uniforms.indexOf(uniformName) === -1) {
  55333. this._options.uniforms.push(uniformName);
  55334. }
  55335. };
  55336. ShaderMaterial.prototype.setTexture = function (name, texture) {
  55337. if (this._options.samplers.indexOf(name) === -1) {
  55338. this._options.samplers.push(name);
  55339. }
  55340. this._textures[name] = texture;
  55341. return this;
  55342. };
  55343. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  55344. if (this._options.samplers.indexOf(name) === -1) {
  55345. this._options.samplers.push(name);
  55346. }
  55347. this._checkUniform(name);
  55348. this._textureArrays[name] = textures;
  55349. return this;
  55350. };
  55351. ShaderMaterial.prototype.setFloat = function (name, value) {
  55352. this._checkUniform(name);
  55353. this._floats[name] = value;
  55354. return this;
  55355. };
  55356. ShaderMaterial.prototype.setInt = function (name, value) {
  55357. this._checkUniform(name);
  55358. this._ints[name] = value;
  55359. return this;
  55360. };
  55361. ShaderMaterial.prototype.setFloats = function (name, value) {
  55362. this._checkUniform(name);
  55363. this._floatsArrays[name] = value;
  55364. return this;
  55365. };
  55366. ShaderMaterial.prototype.setColor3 = function (name, value) {
  55367. this._checkUniform(name);
  55368. this._colors3[name] = value;
  55369. return this;
  55370. };
  55371. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  55372. this._checkUniform(name);
  55373. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  55374. color.toArray(arr, arr.length);
  55375. return arr;
  55376. }, []);
  55377. return this;
  55378. };
  55379. ShaderMaterial.prototype.setColor4 = function (name, value) {
  55380. this._checkUniform(name);
  55381. this._colors4[name] = value;
  55382. return this;
  55383. };
  55384. ShaderMaterial.prototype.setVector2 = function (name, value) {
  55385. this._checkUniform(name);
  55386. this._vectors2[name] = value;
  55387. return this;
  55388. };
  55389. ShaderMaterial.prototype.setVector3 = function (name, value) {
  55390. this._checkUniform(name);
  55391. this._vectors3[name] = value;
  55392. return this;
  55393. };
  55394. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55395. this._checkUniform(name);
  55396. this._vectors4[name] = value;
  55397. return this;
  55398. };
  55399. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55400. this._checkUniform(name);
  55401. this._matrices[name] = value;
  55402. return this;
  55403. };
  55404. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55405. this._checkUniform(name);
  55406. this._matrices3x3[name] = value;
  55407. return this;
  55408. };
  55409. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55410. this._checkUniform(name);
  55411. this._matrices2x2[name] = value;
  55412. return this;
  55413. };
  55414. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55415. this._checkUniform(name);
  55416. this._vectors2Arrays[name] = value;
  55417. return this;
  55418. };
  55419. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55420. this._checkUniform(name);
  55421. this._vectors3Arrays[name] = value;
  55422. return this;
  55423. };
  55424. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55425. if (!mesh) {
  55426. return true;
  55427. }
  55428. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55429. return false;
  55430. }
  55431. return false;
  55432. };
  55433. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55434. var scene = this.getScene();
  55435. var engine = scene.getEngine();
  55436. if (!this.checkReadyOnEveryCall) {
  55437. if (this._renderId === scene.getRenderId()) {
  55438. if (this._checkCache(scene, mesh, useInstances)) {
  55439. return true;
  55440. }
  55441. }
  55442. }
  55443. // Instances
  55444. var defines = [];
  55445. var attribs = [];
  55446. var fallbacks = new BABYLON.EffectFallbacks();
  55447. if (useInstances) {
  55448. defines.push("#define INSTANCES");
  55449. }
  55450. for (var index = 0; index < this._options.defines.length; index++) {
  55451. defines.push(this._options.defines[index]);
  55452. }
  55453. for (var index = 0; index < this._options.attributes.length; index++) {
  55454. attribs.push(this._options.attributes[index]);
  55455. }
  55456. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55457. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55458. defines.push("#define VERTEXCOLOR");
  55459. }
  55460. // Bones
  55461. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55462. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55463. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55464. if (mesh.numBoneInfluencers > 4) {
  55465. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55466. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55467. }
  55468. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55469. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55470. fallbacks.addCPUSkinningFallback(0, mesh);
  55471. if (this._options.uniforms.indexOf("mBones") === -1) {
  55472. this._options.uniforms.push("mBones");
  55473. }
  55474. }
  55475. else {
  55476. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55477. }
  55478. // Textures
  55479. for (var name in this._textures) {
  55480. if (!this._textures[name].isReady()) {
  55481. return false;
  55482. }
  55483. }
  55484. // Alpha test
  55485. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55486. defines.push("#define ALPHATEST");
  55487. }
  55488. var previousEffect = this._effect;
  55489. var join = defines.join("\n");
  55490. this._effect = engine.createEffect(this._shaderPath, {
  55491. attributes: attribs,
  55492. uniformsNames: this._options.uniforms,
  55493. uniformBuffersNames: this._options.uniformBuffers,
  55494. samplers: this._options.samplers,
  55495. defines: join,
  55496. fallbacks: fallbacks,
  55497. onCompiled: this.onCompiled,
  55498. onError: this.onError
  55499. }, engine);
  55500. if (!this._effect.isReady()) {
  55501. return false;
  55502. }
  55503. if (previousEffect !== this._effect) {
  55504. scene.resetCachedMaterial();
  55505. }
  55506. this._renderId = scene.getRenderId();
  55507. return true;
  55508. };
  55509. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55510. var scene = this.getScene();
  55511. if (!this._effect) {
  55512. return;
  55513. }
  55514. if (this._options.uniforms.indexOf("world") !== -1) {
  55515. this._effect.setMatrix("world", world);
  55516. }
  55517. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55518. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55519. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55520. }
  55521. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55522. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55523. }
  55524. };
  55525. ShaderMaterial.prototype.bind = function (world, mesh) {
  55526. // Std values
  55527. this.bindOnlyWorldMatrix(world);
  55528. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55529. if (this._options.uniforms.indexOf("view") !== -1) {
  55530. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55531. }
  55532. if (this._options.uniforms.indexOf("projection") !== -1) {
  55533. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55534. }
  55535. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55536. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55537. }
  55538. // Bones
  55539. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55540. var name;
  55541. // Texture
  55542. for (name in this._textures) {
  55543. this._effect.setTexture(name, this._textures[name]);
  55544. }
  55545. // Texture arrays
  55546. for (name in this._textureArrays) {
  55547. this._effect.setTextureArray(name, this._textureArrays[name]);
  55548. }
  55549. // Int
  55550. for (name in this._ints) {
  55551. this._effect.setInt(name, this._ints[name]);
  55552. }
  55553. // Float
  55554. for (name in this._floats) {
  55555. this._effect.setFloat(name, this._floats[name]);
  55556. }
  55557. // Floats
  55558. for (name in this._floatsArrays) {
  55559. this._effect.setArray(name, this._floatsArrays[name]);
  55560. }
  55561. // Color3
  55562. for (name in this._colors3) {
  55563. this._effect.setColor3(name, this._colors3[name]);
  55564. }
  55565. for (name in this._colors3Arrays) {
  55566. this._effect.setArray3(name, this._colors3Arrays[name]);
  55567. }
  55568. // Color4
  55569. for (name in this._colors4) {
  55570. var color = this._colors4[name];
  55571. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55572. }
  55573. // Vector2
  55574. for (name in this._vectors2) {
  55575. this._effect.setVector2(name, this._vectors2[name]);
  55576. }
  55577. // Vector3
  55578. for (name in this._vectors3) {
  55579. this._effect.setVector3(name, this._vectors3[name]);
  55580. }
  55581. // Vector4
  55582. for (name in this._vectors4) {
  55583. this._effect.setVector4(name, this._vectors4[name]);
  55584. }
  55585. // Matrix
  55586. for (name in this._matrices) {
  55587. this._effect.setMatrix(name, this._matrices[name]);
  55588. }
  55589. // Matrix 3x3
  55590. for (name in this._matrices3x3) {
  55591. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55592. }
  55593. // Matrix 2x2
  55594. for (name in this._matrices2x2) {
  55595. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55596. }
  55597. // Vector2Array
  55598. for (name in this._vectors2Arrays) {
  55599. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55600. }
  55601. // Vector3Array
  55602. for (name in this._vectors3Arrays) {
  55603. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55604. }
  55605. }
  55606. this._afterBind(mesh);
  55607. };
  55608. ShaderMaterial.prototype.getActiveTextures = function () {
  55609. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55610. for (var name in this._textures) {
  55611. activeTextures.push(this._textures[name]);
  55612. }
  55613. for (var name in this._textureArrays) {
  55614. var array = this._textureArrays[name];
  55615. for (var index = 0; index < array.length; index++) {
  55616. activeTextures.push(array[index]);
  55617. }
  55618. }
  55619. return activeTextures;
  55620. };
  55621. ShaderMaterial.prototype.hasTexture = function (texture) {
  55622. if (_super.prototype.hasTexture.call(this, texture)) {
  55623. return true;
  55624. }
  55625. for (var name in this._textures) {
  55626. if (this._textures[name] === texture) {
  55627. return true;
  55628. }
  55629. }
  55630. for (var name in this._textureArrays) {
  55631. var array = this._textureArrays[name];
  55632. for (var index = 0; index < array.length; index++) {
  55633. if (array[index] === texture) {
  55634. return true;
  55635. }
  55636. }
  55637. }
  55638. return false;
  55639. };
  55640. ShaderMaterial.prototype.clone = function (name) {
  55641. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55642. return newShaderMaterial;
  55643. };
  55644. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55645. if (forceDisposeTextures) {
  55646. var name;
  55647. for (name in this._textures) {
  55648. this._textures[name].dispose();
  55649. }
  55650. for (name in this._textureArrays) {
  55651. var array = this._textureArrays[name];
  55652. for (var index = 0; index < array.length; index++) {
  55653. array[index].dispose();
  55654. }
  55655. }
  55656. }
  55657. this._textures = {};
  55658. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55659. };
  55660. ShaderMaterial.prototype.serialize = function () {
  55661. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55662. serializationObject.customType = "BABYLON.ShaderMaterial";
  55663. serializationObject.options = this._options;
  55664. serializationObject.shaderPath = this._shaderPath;
  55665. var name;
  55666. // Texture
  55667. serializationObject.textures = {};
  55668. for (name in this._textures) {
  55669. serializationObject.textures[name] = this._textures[name].serialize();
  55670. }
  55671. // Texture arrays
  55672. serializationObject.textureArrays = {};
  55673. for (name in this._textureArrays) {
  55674. serializationObject.textureArrays[name] = [];
  55675. var array = this._textureArrays[name];
  55676. for (var index = 0; index < array.length; index++) {
  55677. serializationObject.textureArrays[name].push(array[index].serialize());
  55678. }
  55679. }
  55680. // Float
  55681. serializationObject.floats = {};
  55682. for (name in this._floats) {
  55683. serializationObject.floats[name] = this._floats[name];
  55684. }
  55685. // Float s
  55686. serializationObject.FloatArrays = {};
  55687. for (name in this._floatsArrays) {
  55688. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55689. }
  55690. // Color3
  55691. serializationObject.colors3 = {};
  55692. for (name in this._colors3) {
  55693. serializationObject.colors3[name] = this._colors3[name].asArray();
  55694. }
  55695. // Color3 array
  55696. serializationObject.colors3Arrays = {};
  55697. for (name in this._colors3Arrays) {
  55698. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55699. }
  55700. // Color4
  55701. serializationObject.colors4 = {};
  55702. for (name in this._colors4) {
  55703. serializationObject.colors4[name] = this._colors4[name].asArray();
  55704. }
  55705. // Vector2
  55706. serializationObject.vectors2 = {};
  55707. for (name in this._vectors2) {
  55708. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55709. }
  55710. // Vector3
  55711. serializationObject.vectors3 = {};
  55712. for (name in this._vectors3) {
  55713. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55714. }
  55715. // Vector4
  55716. serializationObject.vectors4 = {};
  55717. for (name in this._vectors4) {
  55718. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55719. }
  55720. // Matrix
  55721. serializationObject.matrices = {};
  55722. for (name in this._matrices) {
  55723. serializationObject.matrices[name] = this._matrices[name].asArray();
  55724. }
  55725. // Matrix 3x3
  55726. serializationObject.matrices3x3 = {};
  55727. for (name in this._matrices3x3) {
  55728. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55729. }
  55730. // Matrix 2x2
  55731. serializationObject.matrices2x2 = {};
  55732. for (name in this._matrices2x2) {
  55733. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55734. }
  55735. // Vector2Array
  55736. serializationObject.vectors2Arrays = {};
  55737. for (name in this._vectors2Arrays) {
  55738. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55739. }
  55740. // Vector3Array
  55741. serializationObject.vectors3Arrays = {};
  55742. for (name in this._vectors3Arrays) {
  55743. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55744. }
  55745. return serializationObject;
  55746. };
  55747. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55748. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55749. var name;
  55750. // Texture
  55751. for (name in source.textures) {
  55752. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55753. }
  55754. // Texture arrays
  55755. for (name in source.textureArrays) {
  55756. var array = source.textureArrays[name];
  55757. var textureArray = new Array();
  55758. for (var index = 0; index < array.length; index++) {
  55759. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55760. }
  55761. material.setTextureArray(name, textureArray);
  55762. }
  55763. // Float
  55764. for (name in source.floats) {
  55765. material.setFloat(name, source.floats[name]);
  55766. }
  55767. // Float s
  55768. for (name in source.floatsArrays) {
  55769. material.setFloats(name, source.floatsArrays[name]);
  55770. }
  55771. // Color3
  55772. for (name in source.colors3) {
  55773. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55774. }
  55775. // Color3 arrays
  55776. for (name in source.colors3Arrays) {
  55777. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55778. if (i % 3 === 0) {
  55779. arr.push([num]);
  55780. }
  55781. else {
  55782. arr[arr.length - 1].push(num);
  55783. }
  55784. return arr;
  55785. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55786. material.setColor3Array(name, colors);
  55787. }
  55788. // Color4
  55789. for (name in source.colors4) {
  55790. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55791. }
  55792. // Vector2
  55793. for (name in source.vectors2) {
  55794. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55795. }
  55796. // Vector3
  55797. for (name in source.vectors3) {
  55798. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55799. }
  55800. // Vector4
  55801. for (name in source.vectors4) {
  55802. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55803. }
  55804. // Matrix
  55805. for (name in source.matrices) {
  55806. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55807. }
  55808. // Matrix 3x3
  55809. for (name in source.matrices3x3) {
  55810. material.setMatrix3x3(name, source.matrices3x3[name]);
  55811. }
  55812. // Matrix 2x2
  55813. for (name in source.matrices2x2) {
  55814. material.setMatrix2x2(name, source.matrices2x2[name]);
  55815. }
  55816. // Vector2Array
  55817. for (name in source.vectors2Arrays) {
  55818. material.setArray2(name, source.vectors2Arrays[name]);
  55819. }
  55820. // Vector3Array
  55821. for (name in source.vectors3Arrays) {
  55822. material.setArray3(name, source.vectors3Arrays[name]);
  55823. }
  55824. return material;
  55825. };
  55826. return ShaderMaterial;
  55827. }(BABYLON.Material));
  55828. BABYLON.ShaderMaterial = ShaderMaterial;
  55829. })(BABYLON || (BABYLON = {}));
  55830. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55831. "use strict";
  55832. var BABYLON;
  55833. (function (BABYLON) {
  55834. var GroundMesh = /** @class */ (function (_super) {
  55835. __extends(GroundMesh, _super);
  55836. function GroundMesh(name, scene) {
  55837. var _this = _super.call(this, name, scene) || this;
  55838. _this.generateOctree = false;
  55839. return _this;
  55840. }
  55841. GroundMesh.prototype.getClassName = function () {
  55842. return "GroundMesh";
  55843. };
  55844. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55845. get: function () {
  55846. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55847. },
  55848. enumerable: true,
  55849. configurable: true
  55850. });
  55851. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55852. get: function () {
  55853. return this._subdivisionsX;
  55854. },
  55855. enumerable: true,
  55856. configurable: true
  55857. });
  55858. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55859. get: function () {
  55860. return this._subdivisionsY;
  55861. },
  55862. enumerable: true,
  55863. configurable: true
  55864. });
  55865. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55866. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55867. this._subdivisionsX = chunksCount;
  55868. this._subdivisionsY = chunksCount;
  55869. this.subdivide(chunksCount);
  55870. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55871. };
  55872. /**
  55873. * Returns a height (y) value in the Worl system :
  55874. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55875. * Returns the ground y position if (x, z) are outside the ground surface.
  55876. */
  55877. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55878. var world = this.getWorldMatrix();
  55879. var invMat = BABYLON.Tmp.Matrix[5];
  55880. world.invertToRef(invMat);
  55881. var tmpVect = BABYLON.Tmp.Vector3[8];
  55882. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55883. x = tmpVect.x;
  55884. z = tmpVect.z;
  55885. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55886. return this.position.y;
  55887. }
  55888. if (!this._heightQuads || this._heightQuads.length == 0) {
  55889. this._initHeightQuads();
  55890. this._computeHeightQuads();
  55891. }
  55892. var facet = this._getFacetAt(x, z);
  55893. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55894. // return y in the World system
  55895. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55896. return tmpVect.y;
  55897. };
  55898. /**
  55899. * Returns a normalized vector (Vector3) orthogonal to the ground
  55900. * at the ground coordinates (x, z) expressed in the World system.
  55901. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55902. */
  55903. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55904. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55905. this.getNormalAtCoordinatesToRef(x, z, normal);
  55906. return normal;
  55907. };
  55908. /**
  55909. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55910. * at the ground coordinates (x, z) expressed in the World system.
  55911. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55912. * Returns the GroundMesh.
  55913. */
  55914. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55915. var world = this.getWorldMatrix();
  55916. var tmpMat = BABYLON.Tmp.Matrix[5];
  55917. world.invertToRef(tmpMat);
  55918. var tmpVect = BABYLON.Tmp.Vector3[8];
  55919. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55920. x = tmpVect.x;
  55921. z = tmpVect.z;
  55922. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55923. return this;
  55924. }
  55925. if (!this._heightQuads || this._heightQuads.length == 0) {
  55926. this._initHeightQuads();
  55927. this._computeHeightQuads();
  55928. }
  55929. var facet = this._getFacetAt(x, z);
  55930. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55931. return this;
  55932. };
  55933. /**
  55934. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55935. * if the ground has been updated.
  55936. * This can be used in the render loop.
  55937. * Returns the GroundMesh.
  55938. */
  55939. GroundMesh.prototype.updateCoordinateHeights = function () {
  55940. if (!this._heightQuads || this._heightQuads.length == 0) {
  55941. this._initHeightQuads();
  55942. }
  55943. this._computeHeightQuads();
  55944. return this;
  55945. };
  55946. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55947. GroundMesh.prototype._getFacetAt = function (x, z) {
  55948. // retrieve col and row from x, z coordinates in the ground local system
  55949. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55950. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55951. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55952. var facet;
  55953. if (z < quad.slope.x * x + quad.slope.y) {
  55954. facet = quad.facet1;
  55955. }
  55956. else {
  55957. facet = quad.facet2;
  55958. }
  55959. return facet;
  55960. };
  55961. // Creates and populates the heightMap array with "facet" elements :
  55962. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55963. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55964. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55965. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55966. // Returns the GroundMesh.
  55967. GroundMesh.prototype._initHeightQuads = function () {
  55968. var subdivisionsX = this._subdivisionsX;
  55969. var subdivisionsY = this._subdivisionsY;
  55970. this._heightQuads = new Array();
  55971. for (var row = 0; row < subdivisionsY; row++) {
  55972. for (var col = 0; col < subdivisionsX; col++) {
  55973. 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) };
  55974. this._heightQuads[row * subdivisionsX + col] = quad;
  55975. }
  55976. }
  55977. return this;
  55978. };
  55979. // Compute each quad element values and update the the heightMap array :
  55980. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55981. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55982. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55983. // Returns the GroundMesh.
  55984. GroundMesh.prototype._computeHeightQuads = function () {
  55985. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55986. if (!positions) {
  55987. return this;
  55988. }
  55989. var v1 = BABYLON.Tmp.Vector3[3];
  55990. var v2 = BABYLON.Tmp.Vector3[2];
  55991. var v3 = BABYLON.Tmp.Vector3[1];
  55992. var v4 = BABYLON.Tmp.Vector3[0];
  55993. var v1v2 = BABYLON.Tmp.Vector3[4];
  55994. var v1v3 = BABYLON.Tmp.Vector3[5];
  55995. var v1v4 = BABYLON.Tmp.Vector3[6];
  55996. var norm1 = BABYLON.Tmp.Vector3[7];
  55997. var norm2 = BABYLON.Tmp.Vector3[8];
  55998. var i = 0;
  55999. var j = 0;
  56000. var k = 0;
  56001. var cd = 0; // 2D slope coefficient : z = cd * x + h
  56002. var h = 0;
  56003. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  56004. var d2 = 0;
  56005. var subdivisionsX = this._subdivisionsX;
  56006. var subdivisionsY = this._subdivisionsY;
  56007. for (var row = 0; row < subdivisionsY; row++) {
  56008. for (var col = 0; col < subdivisionsX; col++) {
  56009. i = col * 3;
  56010. j = row * (subdivisionsX + 1) * 3;
  56011. k = (row + 1) * (subdivisionsX + 1) * 3;
  56012. v1.x = positions[j + i];
  56013. v1.y = positions[j + i + 1];
  56014. v1.z = positions[j + i + 2];
  56015. v2.x = positions[j + i + 3];
  56016. v2.y = positions[j + i + 4];
  56017. v2.z = positions[j + i + 5];
  56018. v3.x = positions[k + i];
  56019. v3.y = positions[k + i + 1];
  56020. v3.z = positions[k + i + 2];
  56021. v4.x = positions[k + i + 3];
  56022. v4.y = positions[k + i + 4];
  56023. v4.z = positions[k + i + 5];
  56024. // 2D slope V1V4
  56025. cd = (v4.z - v1.z) / (v4.x - v1.x);
  56026. h = v1.z - cd * v1.x; // v1 belongs to the slope
  56027. // facet equations :
  56028. // we compute each facet normal vector
  56029. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  56030. // we compute the value d by applying the equation to v1 which belongs to the plane
  56031. // then we store the facet equation in a Vector4
  56032. v2.subtractToRef(v1, v1v2);
  56033. v3.subtractToRef(v1, v1v3);
  56034. v4.subtractToRef(v1, v1v4);
  56035. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  56036. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  56037. norm1.normalize();
  56038. norm2.normalize();
  56039. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  56040. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  56041. var quad = this._heightQuads[row * subdivisionsX + col];
  56042. quad.slope.copyFromFloats(cd, h);
  56043. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  56044. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  56045. }
  56046. }
  56047. return this;
  56048. };
  56049. GroundMesh.prototype.serialize = function (serializationObject) {
  56050. _super.prototype.serialize.call(this, serializationObject);
  56051. serializationObject.subdivisionsX = this._subdivisionsX;
  56052. serializationObject.subdivisionsY = this._subdivisionsY;
  56053. serializationObject.minX = this._minX;
  56054. serializationObject.maxX = this._maxX;
  56055. serializationObject.minZ = this._minZ;
  56056. serializationObject.maxZ = this._maxZ;
  56057. serializationObject.width = this._width;
  56058. serializationObject.height = this._height;
  56059. };
  56060. GroundMesh.Parse = function (parsedMesh, scene) {
  56061. var result = new GroundMesh(parsedMesh.name, scene);
  56062. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  56063. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  56064. result._minX = parsedMesh.minX;
  56065. result._maxX = parsedMesh.maxX;
  56066. result._minZ = parsedMesh.minZ;
  56067. result._maxZ = parsedMesh.maxZ;
  56068. result._width = parsedMesh.width;
  56069. result._height = parsedMesh.height;
  56070. return result;
  56071. };
  56072. return GroundMesh;
  56073. }(BABYLON.Mesh));
  56074. BABYLON.GroundMesh = GroundMesh;
  56075. })(BABYLON || (BABYLON = {}));
  56076. //# sourceMappingURL=babylon.groundMesh.js.map
  56077. "use strict";
  56078. var BABYLON;
  56079. (function (BABYLON) {
  56080. /**
  56081. * Creates an instance based on a source mesh.
  56082. */
  56083. var InstancedMesh = /** @class */ (function (_super) {
  56084. __extends(InstancedMesh, _super);
  56085. function InstancedMesh(name, source) {
  56086. var _this = _super.call(this, name, source.getScene()) || this;
  56087. source.instances.push(_this);
  56088. _this._sourceMesh = source;
  56089. _this.position.copyFrom(source.position);
  56090. _this.rotation.copyFrom(source.rotation);
  56091. _this.scaling.copyFrom(source.scaling);
  56092. if (source.rotationQuaternion) {
  56093. _this.rotationQuaternion = source.rotationQuaternion.clone();
  56094. }
  56095. _this.infiniteDistance = source.infiniteDistance;
  56096. _this.setPivotMatrix(source.getPivotMatrix());
  56097. _this.refreshBoundingInfo();
  56098. _this._syncSubMeshes();
  56099. return _this;
  56100. }
  56101. /**
  56102. * Returns the string "InstancedMesh".
  56103. */
  56104. InstancedMesh.prototype.getClassName = function () {
  56105. return "InstancedMesh";
  56106. };
  56107. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  56108. // Methods
  56109. get: function () {
  56110. return this._sourceMesh.receiveShadows;
  56111. },
  56112. enumerable: true,
  56113. configurable: true
  56114. });
  56115. Object.defineProperty(InstancedMesh.prototype, "material", {
  56116. get: function () {
  56117. return this._sourceMesh.material;
  56118. },
  56119. enumerable: true,
  56120. configurable: true
  56121. });
  56122. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  56123. get: function () {
  56124. return this._sourceMesh.visibility;
  56125. },
  56126. enumerable: true,
  56127. configurable: true
  56128. });
  56129. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  56130. get: function () {
  56131. return this._sourceMesh.skeleton;
  56132. },
  56133. enumerable: true,
  56134. configurable: true
  56135. });
  56136. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  56137. get: function () {
  56138. return this._sourceMesh.renderingGroupId;
  56139. },
  56140. set: function (value) {
  56141. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  56142. return;
  56143. }
  56144. //no-op with warning
  56145. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  56146. },
  56147. enumerable: true,
  56148. configurable: true
  56149. });
  56150. /**
  56151. * Returns the total number of vertices (integer).
  56152. */
  56153. InstancedMesh.prototype.getTotalVertices = function () {
  56154. return this._sourceMesh.getTotalVertices();
  56155. };
  56156. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  56157. get: function () {
  56158. return this._sourceMesh;
  56159. },
  56160. enumerable: true,
  56161. configurable: true
  56162. });
  56163. /**
  56164. * Is this node ready to be used/rendered
  56165. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  56166. * @return {boolean} is it ready
  56167. */
  56168. InstancedMesh.prototype.isReady = function (completeCheck) {
  56169. if (completeCheck === void 0) { completeCheck = false; }
  56170. return this._sourceMesh.isReady(completeCheck, true);
  56171. };
  56172. /**
  56173. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  56174. */
  56175. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  56176. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  56177. };
  56178. /**
  56179. * Sets the vertex data of the mesh geometry for the requested `kind`.
  56180. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  56181. * The `data` are either a numeric array either a Float32Array.
  56182. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  56183. * 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).
  56184. * Note that a new underlying VertexBuffer object is created each call.
  56185. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  56186. *
  56187. * Possible `kind` values :
  56188. * - BABYLON.VertexBuffer.PositionKind
  56189. * - BABYLON.VertexBuffer.UVKind
  56190. * - BABYLON.VertexBuffer.UV2Kind
  56191. * - BABYLON.VertexBuffer.UV3Kind
  56192. * - BABYLON.VertexBuffer.UV4Kind
  56193. * - BABYLON.VertexBuffer.UV5Kind
  56194. * - BABYLON.VertexBuffer.UV6Kind
  56195. * - BABYLON.VertexBuffer.ColorKind
  56196. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56197. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56198. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56199. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56200. *
  56201. * Returns the Mesh.
  56202. */
  56203. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  56204. if (this.sourceMesh) {
  56205. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  56206. }
  56207. return this.sourceMesh;
  56208. };
  56209. /**
  56210. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  56211. * If the mesh has no geometry, it is simply returned as it is.
  56212. * The `data` are either a numeric array either a Float32Array.
  56213. * No new underlying VertexBuffer object is created.
  56214. * 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.
  56215. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  56216. *
  56217. * Possible `kind` values :
  56218. * - BABYLON.VertexBuffer.PositionKind
  56219. * - BABYLON.VertexBuffer.UVKind
  56220. * - BABYLON.VertexBuffer.UV2Kind
  56221. * - BABYLON.VertexBuffer.UV3Kind
  56222. * - BABYLON.VertexBuffer.UV4Kind
  56223. * - BABYLON.VertexBuffer.UV5Kind
  56224. * - BABYLON.VertexBuffer.UV6Kind
  56225. * - BABYLON.VertexBuffer.ColorKind
  56226. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56227. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56228. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56229. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56230. *
  56231. * Returns the Mesh.
  56232. */
  56233. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  56234. if (this.sourceMesh) {
  56235. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  56236. }
  56237. return this.sourceMesh;
  56238. };
  56239. /**
  56240. * Sets the mesh indices.
  56241. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  56242. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  56243. * This method creates a new index buffer each call.
  56244. * Returns the Mesh.
  56245. */
  56246. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  56247. if (totalVertices === void 0) { totalVertices = null; }
  56248. if (this.sourceMesh) {
  56249. this.sourceMesh.setIndices(indices, totalVertices);
  56250. }
  56251. return this.sourceMesh;
  56252. };
  56253. /**
  56254. * Boolean : True if the mesh owns the requested kind of data.
  56255. */
  56256. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  56257. return this._sourceMesh.isVerticesDataPresent(kind);
  56258. };
  56259. /**
  56260. * Returns an array of indices (IndicesArray).
  56261. */
  56262. InstancedMesh.prototype.getIndices = function () {
  56263. return this._sourceMesh.getIndices();
  56264. };
  56265. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  56266. get: function () {
  56267. return this._sourceMesh._positions;
  56268. },
  56269. enumerable: true,
  56270. configurable: true
  56271. });
  56272. /**
  56273. * Sets a new updated BoundingInfo to the mesh.
  56274. * Returns the mesh.
  56275. */
  56276. InstancedMesh.prototype.refreshBoundingInfo = function () {
  56277. var meshBB = this._sourceMesh.getBoundingInfo();
  56278. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  56279. this._updateBoundingInfo();
  56280. return this;
  56281. };
  56282. InstancedMesh.prototype._preActivate = function () {
  56283. if (this._currentLOD) {
  56284. this._currentLOD._preActivate();
  56285. }
  56286. return this;
  56287. };
  56288. InstancedMesh.prototype._activate = function (renderId) {
  56289. if (this._currentLOD) {
  56290. this._currentLOD._registerInstanceForRenderId(this, renderId);
  56291. }
  56292. return this;
  56293. };
  56294. /**
  56295. * Returns the current associated LOD AbstractMesh.
  56296. */
  56297. InstancedMesh.prototype.getLOD = function (camera) {
  56298. if (!camera) {
  56299. return this;
  56300. }
  56301. var boundingInfo = this.getBoundingInfo();
  56302. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  56303. if (this._currentLOD === this.sourceMesh) {
  56304. return this;
  56305. }
  56306. return this._currentLOD;
  56307. };
  56308. InstancedMesh.prototype._syncSubMeshes = function () {
  56309. this.releaseSubMeshes();
  56310. if (this._sourceMesh.subMeshes) {
  56311. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  56312. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  56313. }
  56314. }
  56315. return this;
  56316. };
  56317. InstancedMesh.prototype._generatePointsArray = function () {
  56318. return this._sourceMesh._generatePointsArray();
  56319. };
  56320. /**
  56321. * Creates a new InstancedMesh from the current mesh.
  56322. * - name (string) : the cloned mesh name
  56323. * - newParent (optional Node) : the optional Node to parent the clone to.
  56324. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  56325. *
  56326. * Returns the clone.
  56327. */
  56328. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56329. var result = this._sourceMesh.createInstance(name);
  56330. // Deep copy
  56331. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  56332. // Bounding info
  56333. this.refreshBoundingInfo();
  56334. // Parent
  56335. if (newParent) {
  56336. result.parent = newParent;
  56337. }
  56338. if (!doNotCloneChildren) {
  56339. // Children
  56340. for (var index = 0; index < this.getScene().meshes.length; index++) {
  56341. var mesh = this.getScene().meshes[index];
  56342. if (mesh.parent === this) {
  56343. mesh.clone(mesh.name, result);
  56344. }
  56345. }
  56346. }
  56347. result.computeWorldMatrix(true);
  56348. return result;
  56349. };
  56350. /**
  56351. * Disposes the InstancedMesh.
  56352. * Returns nothing.
  56353. */
  56354. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  56355. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  56356. // Remove from mesh
  56357. var index = this._sourceMesh.instances.indexOf(this);
  56358. this._sourceMesh.instances.splice(index, 1);
  56359. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  56360. };
  56361. return InstancedMesh;
  56362. }(BABYLON.AbstractMesh));
  56363. BABYLON.InstancedMesh = InstancedMesh;
  56364. })(BABYLON || (BABYLON = {}));
  56365. //# sourceMappingURL=babylon.instancedMesh.js.map
  56366. "use strict";
  56367. var BABYLON;
  56368. (function (BABYLON) {
  56369. var LinesMesh = /** @class */ (function (_super) {
  56370. __extends(LinesMesh, _super);
  56371. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  56372. if (scene === void 0) { scene = null; }
  56373. if (parent === void 0) { parent = null; }
  56374. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  56375. _this.useVertexColor = useVertexColor;
  56376. _this.useVertexAlpha = useVertexAlpha;
  56377. _this.color = new BABYLON.Color3(1, 1, 1);
  56378. _this.alpha = 1;
  56379. if (source) {
  56380. _this.color = source.color.clone();
  56381. _this.alpha = source.alpha;
  56382. _this.useVertexColor = source.useVertexColor;
  56383. _this.useVertexAlpha = source.useVertexAlpha;
  56384. }
  56385. _this._intersectionThreshold = 0.1;
  56386. var defines = [];
  56387. var options = {
  56388. attributes: [BABYLON.VertexBuffer.PositionKind],
  56389. uniforms: ["world", "viewProjection"],
  56390. needAlphaBlending: true,
  56391. defines: defines
  56392. };
  56393. if (useVertexAlpha === false) {
  56394. options.needAlphaBlending = false;
  56395. }
  56396. if (!useVertexColor) {
  56397. options.uniforms.push("color");
  56398. }
  56399. else {
  56400. options.defines.push("#define VERTEXCOLOR");
  56401. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56402. }
  56403. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56404. return _this;
  56405. }
  56406. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56407. /**
  56408. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56409. * This margin is expressed in world space coordinates, so its value may vary.
  56410. * Default value is 0.1
  56411. * @returns the intersection Threshold value.
  56412. */
  56413. get: function () {
  56414. return this._intersectionThreshold;
  56415. },
  56416. /**
  56417. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56418. * This margin is expressed in world space coordinates, so its value may vary.
  56419. * @param value the new threshold to apply
  56420. */
  56421. set: function (value) {
  56422. if (this._intersectionThreshold === value) {
  56423. return;
  56424. }
  56425. this._intersectionThreshold = value;
  56426. if (this.geometry) {
  56427. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56428. }
  56429. },
  56430. enumerable: true,
  56431. configurable: true
  56432. });
  56433. /**
  56434. * Returns the string "LineMesh"
  56435. */
  56436. LinesMesh.prototype.getClassName = function () {
  56437. return "LinesMesh";
  56438. };
  56439. Object.defineProperty(LinesMesh.prototype, "material", {
  56440. get: function () {
  56441. return this._colorShader;
  56442. },
  56443. set: function (value) {
  56444. // Do nothing
  56445. },
  56446. enumerable: true,
  56447. configurable: true
  56448. });
  56449. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56450. get: function () {
  56451. return false;
  56452. },
  56453. enumerable: true,
  56454. configurable: true
  56455. });
  56456. LinesMesh.prototype.createInstance = function (name) {
  56457. throw new Error("LinesMeshes do not support createInstance.");
  56458. };
  56459. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56460. if (!this._geometry) {
  56461. return this;
  56462. }
  56463. // VBOs
  56464. this._geometry._bind(this._colorShader.getEffect());
  56465. // Color
  56466. if (!this.useVertexColor) {
  56467. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56468. }
  56469. return this;
  56470. };
  56471. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56472. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56473. return this;
  56474. }
  56475. var engine = this.getScene().getEngine();
  56476. // Draw order
  56477. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56478. return this;
  56479. };
  56480. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56481. this._colorShader.dispose();
  56482. _super.prototype.dispose.call(this, doNotRecurse);
  56483. };
  56484. /**
  56485. * Returns a new LineMesh object cloned from the current one.
  56486. */
  56487. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56488. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56489. };
  56490. return LinesMesh;
  56491. }(BABYLON.Mesh));
  56492. BABYLON.LinesMesh = LinesMesh;
  56493. })(BABYLON || (BABYLON = {}));
  56494. //# sourceMappingURL=babylon.linesMesh.js.map
  56495. "use strict";
  56496. var BABYLON;
  56497. (function (BABYLON) {
  56498. var MeshBuilder = /** @class */ (function () {
  56499. function MeshBuilder() {
  56500. }
  56501. MeshBuilder.updateSideOrientation = function (orientation) {
  56502. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56503. return BABYLON.Mesh.DOUBLESIDE;
  56504. }
  56505. if (orientation === undefined || orientation === null) {
  56506. return BABYLON.Mesh.FRONTSIDE;
  56507. }
  56508. return orientation;
  56509. };
  56510. /**
  56511. * Creates a box mesh.
  56512. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56513. * The parameter `size` sets the size (float) of each box side (default 1).
  56514. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56515. * 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).
  56516. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56517. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56518. * 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).
  56519. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56520. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56521. */
  56522. MeshBuilder.CreateBox = function (name, options, scene) {
  56523. if (scene === void 0) { scene = null; }
  56524. var box = new BABYLON.Mesh(name, scene);
  56525. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56526. box._originalBuilderSideOrientation = options.sideOrientation;
  56527. var vertexData = BABYLON.VertexData.CreateBox(options);
  56528. vertexData.applyToMesh(box, options.updatable);
  56529. return box;
  56530. };
  56531. /**
  56532. * Creates a sphere mesh.
  56533. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56534. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56535. * 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`).
  56536. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56537. * 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
  56538. * 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).
  56539. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56540. * 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).
  56541. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56542. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56543. */
  56544. MeshBuilder.CreateSphere = function (name, options, scene) {
  56545. var sphere = new BABYLON.Mesh(name, scene);
  56546. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56547. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56548. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56549. vertexData.applyToMesh(sphere, options.updatable);
  56550. return sphere;
  56551. };
  56552. /**
  56553. * Creates a plane polygonal mesh. By default, this is a disc.
  56554. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56555. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56556. * 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.
  56557. * 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
  56558. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56559. * 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).
  56560. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56562. */
  56563. MeshBuilder.CreateDisc = function (name, options, scene) {
  56564. if (scene === void 0) { scene = null; }
  56565. var disc = new BABYLON.Mesh(name, scene);
  56566. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56567. disc._originalBuilderSideOrientation = options.sideOrientation;
  56568. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56569. vertexData.applyToMesh(disc, options.updatable);
  56570. return disc;
  56571. };
  56572. /**
  56573. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56574. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56575. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56576. * 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`).
  56577. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56578. * 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.
  56579. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56580. * 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).
  56581. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56582. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56583. */
  56584. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56585. var sphere = new BABYLON.Mesh(name, scene);
  56586. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56587. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56588. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56589. vertexData.applyToMesh(sphere, options.updatable);
  56590. return sphere;
  56591. };
  56592. ;
  56593. /**
  56594. * Creates a ribbon mesh.
  56595. * 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.
  56596. *
  56597. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56598. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56599. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56600. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56601. * 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.
  56602. * 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.
  56603. * 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
  56604. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56605. * 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).
  56606. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56607. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56608. * 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.
  56609. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56610. * 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
  56611. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56612. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56613. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56614. */
  56615. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56616. if (scene === void 0) { scene = null; }
  56617. var pathArray = options.pathArray;
  56618. var closeArray = options.closeArray;
  56619. var closePath = options.closePath;
  56620. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56621. var instance = options.instance;
  56622. var updatable = options.updatable;
  56623. if (instance) {
  56624. // positionFunction : ribbon case
  56625. // only pathArray and sideOrientation parameters are taken into account for positions update
  56626. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56627. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56628. var positionFunction = function (positions) {
  56629. var minlg = pathArray[0].length;
  56630. var i = 0;
  56631. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56632. for (var si = 1; si <= ns; si++) {
  56633. for (var p = 0; p < pathArray.length; p++) {
  56634. var path = pathArray[p];
  56635. var l = path.length;
  56636. minlg = (minlg < l) ? minlg : l;
  56637. var j = 0;
  56638. while (j < minlg) {
  56639. positions[i] = path[j].x;
  56640. positions[i + 1] = path[j].y;
  56641. positions[i + 2] = path[j].z;
  56642. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56643. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56644. }
  56645. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56646. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56647. }
  56648. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56649. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56650. }
  56651. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56652. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56653. }
  56654. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56655. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56656. }
  56657. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56658. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56659. }
  56660. j++;
  56661. i += 3;
  56662. }
  56663. if (instance._closePath) {
  56664. positions[i] = path[0].x;
  56665. positions[i + 1] = path[0].y;
  56666. positions[i + 2] = path[0].z;
  56667. i += 3;
  56668. }
  56669. }
  56670. }
  56671. };
  56672. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56673. positionFunction(positions);
  56674. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56675. instance._boundingInfo.update(instance._worldMatrix);
  56676. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56677. if (options.colors) {
  56678. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56679. for (var c = 0; c < options.colors.length; c++) {
  56680. colors[c * 4] = options.colors[c].r;
  56681. colors[c * 4 + 1] = options.colors[c].g;
  56682. colors[c * 4 + 2] = options.colors[c].b;
  56683. colors[c * 4 + 3] = options.colors[c].a;
  56684. }
  56685. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56686. }
  56687. if (options.uvs) {
  56688. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56689. for (var i = 0; i < options.uvs.length; i++) {
  56690. uvs[i * 2] = options.uvs[i].x;
  56691. uvs[i * 2 + 1] = options.uvs[i].y;
  56692. }
  56693. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56694. }
  56695. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56696. var indices = instance.getIndices();
  56697. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56698. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56699. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56700. if (instance._closePath) {
  56701. var indexFirst = 0;
  56702. var indexLast = 0;
  56703. for (var p = 0; p < pathArray.length; p++) {
  56704. indexFirst = instance._idx[p] * 3;
  56705. if (p + 1 < pathArray.length) {
  56706. indexLast = (instance._idx[p + 1] - 1) * 3;
  56707. }
  56708. else {
  56709. indexLast = normals.length - 3;
  56710. }
  56711. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56712. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56713. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56714. normals[indexLast] = normals[indexFirst];
  56715. normals[indexLast + 1] = normals[indexFirst + 1];
  56716. normals[indexLast + 2] = normals[indexFirst + 2];
  56717. }
  56718. }
  56719. if (!(instance.areNormalsFrozen)) {
  56720. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56721. }
  56722. }
  56723. return instance;
  56724. }
  56725. else {
  56726. var ribbon = new BABYLON.Mesh(name, scene);
  56727. ribbon._originalBuilderSideOrientation = sideOrientation;
  56728. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56729. if (closePath) {
  56730. ribbon._idx = vertexData._idx;
  56731. }
  56732. ribbon._closePath = closePath;
  56733. ribbon._closeArray = closeArray;
  56734. vertexData.applyToMesh(ribbon, updatable);
  56735. return ribbon;
  56736. }
  56737. };
  56738. /**
  56739. * Creates a cylinder or a cone mesh.
  56740. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56741. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56742. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56743. * 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.
  56744. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56745. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56746. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56747. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56748. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56749. * 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).
  56750. * 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
  56751. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56752. * 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
  56753. * 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.
  56754. * If `enclose` is false, a ring surface is one element.
  56755. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56756. * 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
  56757. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56758. * 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).
  56759. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56761. */
  56762. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56763. var cylinder = new BABYLON.Mesh(name, scene);
  56764. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56765. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56766. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56767. vertexData.applyToMesh(cylinder, options.updatable);
  56768. return cylinder;
  56769. };
  56770. /**
  56771. * Creates a torus mesh.
  56772. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56773. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56774. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56775. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56776. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56777. * 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).
  56778. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56779. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56780. */
  56781. MeshBuilder.CreateTorus = function (name, options, scene) {
  56782. var torus = new BABYLON.Mesh(name, scene);
  56783. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56784. torus._originalBuilderSideOrientation = options.sideOrientation;
  56785. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56786. vertexData.applyToMesh(torus, options.updatable);
  56787. return torus;
  56788. };
  56789. /**
  56790. * Creates a torus knot mesh.
  56791. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56792. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56793. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56794. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56795. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56796. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56797. * 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).
  56798. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56799. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56800. */
  56801. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56802. var torusKnot = new BABYLON.Mesh(name, scene);
  56803. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56804. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56805. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56806. vertexData.applyToMesh(torusKnot, options.updatable);
  56807. return torusKnot;
  56808. };
  56809. /**
  56810. * Creates a line system mesh.
  56811. * A line system is a pool of many lines gathered in a single mesh.
  56812. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56813. * 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.
  56814. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56815. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56816. * 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
  56817. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56818. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56819. * 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
  56820. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56821. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56822. */
  56823. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56824. var instance = options.instance;
  56825. var lines = options.lines;
  56826. var colors = options.colors;
  56827. if (instance) {
  56828. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56829. var vertexColor;
  56830. var lineColors;
  56831. if (colors) {
  56832. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56833. }
  56834. var i = 0;
  56835. var c = 0;
  56836. for (var l = 0; l < lines.length; l++) {
  56837. var points = lines[l];
  56838. for (var p = 0; p < points.length; p++) {
  56839. positions[i] = points[p].x;
  56840. positions[i + 1] = points[p].y;
  56841. positions[i + 2] = points[p].z;
  56842. if (colors && vertexColor) {
  56843. lineColors = colors[l];
  56844. vertexColor[c] = lineColors[p].r;
  56845. vertexColor[c + 1] = lineColors[p].g;
  56846. vertexColor[c + 2] = lineColors[p].b;
  56847. vertexColor[c + 3] = lineColors[p].a;
  56848. c += 4;
  56849. }
  56850. i += 3;
  56851. }
  56852. }
  56853. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56854. if (colors && vertexColor) {
  56855. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56856. }
  56857. return instance;
  56858. }
  56859. // line system creation
  56860. var useVertexColor = (colors) ? true : false;
  56861. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56862. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56863. vertexData.applyToMesh(lineSystem, options.updatable);
  56864. return lineSystem;
  56865. };
  56866. /**
  56867. * Creates a line mesh.
  56868. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56869. * 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.
  56870. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56871. * The parameter `points` is an array successive Vector3.
  56872. * 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
  56873. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56874. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56875. * When updating an instance, remember that only point positions can change, not the number of points.
  56876. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56877. */
  56878. MeshBuilder.CreateLines = function (name, options, scene) {
  56879. if (scene === void 0) { scene = null; }
  56880. var colors = (options.colors) ? [options.colors] : null;
  56881. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56882. return lines;
  56883. };
  56884. /**
  56885. * Creates a dashed line mesh.
  56886. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56887. * 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.
  56888. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56889. * The parameter `points` is an array successive Vector3.
  56890. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56891. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56892. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56893. * 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
  56894. * When updating an instance, remember that only point positions can change, not the number of points.
  56895. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56896. */
  56897. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56898. if (scene === void 0) { scene = null; }
  56899. var points = options.points;
  56900. var instance = options.instance;
  56901. var gapSize = options.gapSize || 1;
  56902. var dashSize = options.dashSize || 3;
  56903. if (instance) {
  56904. var positionFunction = function (positions) {
  56905. var curvect = BABYLON.Vector3.Zero();
  56906. var nbSeg = positions.length / 6;
  56907. var lg = 0;
  56908. var nb = 0;
  56909. var shft = 0;
  56910. var dashshft = 0;
  56911. var curshft = 0;
  56912. var p = 0;
  56913. var i = 0;
  56914. var j = 0;
  56915. for (i = 0; i < points.length - 1; i++) {
  56916. points[i + 1].subtractToRef(points[i], curvect);
  56917. lg += curvect.length();
  56918. }
  56919. shft = lg / nbSeg;
  56920. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56921. for (i = 0; i < points.length - 1; i++) {
  56922. points[i + 1].subtractToRef(points[i], curvect);
  56923. nb = Math.floor(curvect.length() / shft);
  56924. curvect.normalize();
  56925. j = 0;
  56926. while (j < nb && p < positions.length) {
  56927. curshft = shft * j;
  56928. positions[p] = points[i].x + curshft * curvect.x;
  56929. positions[p + 1] = points[i].y + curshft * curvect.y;
  56930. positions[p + 2] = points[i].z + curshft * curvect.z;
  56931. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56932. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56933. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56934. p += 6;
  56935. j++;
  56936. }
  56937. }
  56938. while (p < positions.length) {
  56939. positions[p] = points[i].x;
  56940. positions[p + 1] = points[i].y;
  56941. positions[p + 2] = points[i].z;
  56942. p += 3;
  56943. }
  56944. };
  56945. instance.updateMeshPositions(positionFunction, false);
  56946. return instance;
  56947. }
  56948. // dashed lines creation
  56949. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56950. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56951. vertexData.applyToMesh(dashedLines, options.updatable);
  56952. dashedLines.dashSize = dashSize;
  56953. dashedLines.gapSize = gapSize;
  56954. return dashedLines;
  56955. };
  56956. /**
  56957. * Creates an extruded shape mesh.
  56958. * 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.
  56959. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56960. *
  56961. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56962. * 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
  56963. * extruded along the Z axis.
  56964. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56965. * 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.
  56966. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56967. * 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
  56968. * 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
  56969. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56970. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56971. * 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).
  56972. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56973. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56975. */
  56976. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56977. if (scene === void 0) { scene = null; }
  56978. var path = options.path;
  56979. var shape = options.shape;
  56980. var scale = options.scale || 1;
  56981. var rotation = options.rotation || 0;
  56982. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56983. var updatable = options.updatable;
  56984. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56985. var instance = options.instance || null;
  56986. var invertUV = options.invertUV || false;
  56987. 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);
  56988. };
  56989. /**
  56990. * Creates an custom extruded shape mesh.
  56991. * 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.
  56992. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56993. *
  56994. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56995. * 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
  56996. * extruded along the Z axis.
  56997. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56998. * 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
  56999. * and the distance of this point from the begining of the path :
  57000. * ```javascript
  57001. * var rotationFunction = function(i, distance) {
  57002. * // do things
  57003. * return rotationValue; }
  57004. * ```
  57005. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  57006. * 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
  57007. * and the distance of this point from the begining of the path :
  57008. * ```javascript
  57009. * var scaleFunction = function(i, distance) {
  57010. * // do things
  57011. * return scaleValue;}
  57012. * ```
  57013. * It must returns a float value that will be the scale value applied to the shape on each path point.
  57014. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  57015. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  57016. * 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
  57017. * 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
  57018. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  57019. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57020. * 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).
  57021. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57022. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57023. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57024. */
  57025. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  57026. var path = options.path;
  57027. var shape = options.shape;
  57028. var scaleFunction = options.scaleFunction || (function () { return 1; });
  57029. var rotationFunction = options.rotationFunction || (function () { return 0; });
  57030. var ribbonCloseArray = options.ribbonCloseArray || false;
  57031. var ribbonClosePath = options.ribbonClosePath || false;
  57032. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  57033. var updatable = options.updatable;
  57034. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57035. var instance = options.instance;
  57036. var invertUV = options.invertUV || false;
  57037. 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);
  57038. };
  57039. /**
  57040. * Creates lathe mesh.
  57041. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  57042. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  57043. *
  57044. * 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
  57045. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  57046. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  57047. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  57048. * 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.
  57049. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  57050. * 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
  57051. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57052. * 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).
  57053. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57054. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57056. */
  57057. MeshBuilder.CreateLathe = function (name, options, scene) {
  57058. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  57059. var closed = (options.closed === undefined) ? true : options.closed;
  57060. var shape = options.shape;
  57061. var radius = options.radius || 1;
  57062. var tessellation = options.tessellation || 64;
  57063. var updatable = options.updatable;
  57064. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57065. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57066. var pi2 = Math.PI * 2;
  57067. var paths = new Array();
  57068. var invertUV = options.invertUV || false;
  57069. var i = 0;
  57070. var p = 0;
  57071. var step = pi2 / tessellation * arc;
  57072. var rotated;
  57073. var path = new Array();
  57074. ;
  57075. for (i = 0; i <= tessellation; i++) {
  57076. var path = [];
  57077. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  57078. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  57079. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  57080. }
  57081. for (p = 0; p < shape.length; p++) {
  57082. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  57083. path.push(rotated);
  57084. }
  57085. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  57086. 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));
  57087. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  57088. }
  57089. paths.push(path);
  57090. }
  57091. // lathe ribbon
  57092. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57093. return lathe;
  57094. };
  57095. /**
  57096. * Creates a plane mesh.
  57097. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57098. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  57099. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  57100. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  57101. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57102. * 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).
  57103. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57104. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57105. */
  57106. MeshBuilder.CreatePlane = function (name, options, scene) {
  57107. var plane = new BABYLON.Mesh(name, scene);
  57108. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57109. plane._originalBuilderSideOrientation = options.sideOrientation;
  57110. var vertexData = BABYLON.VertexData.CreatePlane(options);
  57111. vertexData.applyToMesh(plane, options.updatable);
  57112. if (options.sourcePlane) {
  57113. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  57114. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  57115. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  57116. plane.rotate(vectorProduct, product);
  57117. }
  57118. return plane;
  57119. };
  57120. /**
  57121. * Creates a ground mesh.
  57122. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57123. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  57124. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  57125. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57126. */
  57127. MeshBuilder.CreateGround = function (name, options, scene) {
  57128. var ground = new BABYLON.GroundMesh(name, scene);
  57129. ground._setReady(false);
  57130. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  57131. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  57132. ground._width = options.width || 1;
  57133. ground._height = options.height || 1;
  57134. ground._maxX = ground._width / 2;
  57135. ground._maxZ = ground._height / 2;
  57136. ground._minX = -ground._maxX;
  57137. ground._minZ = -ground._maxZ;
  57138. var vertexData = BABYLON.VertexData.CreateGround(options);
  57139. vertexData.applyToMesh(ground, options.updatable);
  57140. ground._setReady(true);
  57141. return ground;
  57142. };
  57143. /**
  57144. * Creates a tiled ground mesh.
  57145. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  57146. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  57147. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  57148. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  57149. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  57150. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  57151. * numbers of subdivisions on the ground width and height of each tile.
  57152. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57153. */
  57154. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  57155. var tiledGround = new BABYLON.Mesh(name, scene);
  57156. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  57157. vertexData.applyToMesh(tiledGround, options.updatable);
  57158. return tiledGround;
  57159. };
  57160. /**
  57161. * Creates a ground mesh from a height map.
  57162. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  57163. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  57164. * The parameter `url` sets the URL of the height map image resource.
  57165. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  57166. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  57167. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  57168. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  57169. * 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.
  57170. * 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).
  57171. * This function is passed the newly built mesh :
  57172. * ```javascript
  57173. * function(mesh) { // do things
  57174. * return; }
  57175. * ```
  57176. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57177. */
  57178. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  57179. var width = options.width || 10.0;
  57180. var height = options.height || 10.0;
  57181. var subdivisions = options.subdivisions || 1 | 0;
  57182. var minHeight = options.minHeight || 0.0;
  57183. var maxHeight = options.maxHeight || 1.0;
  57184. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  57185. var updatable = options.updatable;
  57186. var onReady = options.onReady;
  57187. var ground = new BABYLON.GroundMesh(name, scene);
  57188. ground._subdivisionsX = subdivisions;
  57189. ground._subdivisionsY = subdivisions;
  57190. ground._width = width;
  57191. ground._height = height;
  57192. ground._maxX = ground._width / 2.0;
  57193. ground._maxZ = ground._height / 2.0;
  57194. ground._minX = -ground._maxX;
  57195. ground._minZ = -ground._maxZ;
  57196. ground._setReady(false);
  57197. var onload = function (img) {
  57198. // Getting height map data
  57199. var canvas = document.createElement("canvas");
  57200. var context = canvas.getContext("2d");
  57201. if (!context) {
  57202. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  57203. }
  57204. if (scene.isDisposed) {
  57205. return;
  57206. }
  57207. var bufferWidth = img.width;
  57208. var bufferHeight = img.height;
  57209. canvas.width = bufferWidth;
  57210. canvas.height = bufferHeight;
  57211. context.drawImage(img, 0, 0);
  57212. // Create VertexData from map data
  57213. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  57214. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  57215. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  57216. width: width, height: height,
  57217. subdivisions: subdivisions,
  57218. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  57219. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  57220. });
  57221. vertexData.applyToMesh(ground, updatable);
  57222. //execute ready callback, if set
  57223. if (onReady) {
  57224. onReady(ground);
  57225. }
  57226. ground._setReady(true);
  57227. };
  57228. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  57229. return ground;
  57230. };
  57231. /**
  57232. * Creates a polygon mesh.
  57233. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  57234. * 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.
  57235. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57236. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57237. * 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).
  57238. * Remember you can only change the shape positions, not their number when updating a polygon.
  57239. */
  57240. MeshBuilder.CreatePolygon = function (name, options, scene) {
  57241. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57242. var shape = options.shape;
  57243. var holes = options.holes || [];
  57244. var depth = options.depth || 0;
  57245. var contours = [];
  57246. var hole = [];
  57247. for (var i = 0; i < shape.length; i++) {
  57248. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  57249. }
  57250. var epsilon = 0.00000001;
  57251. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  57252. contours.pop();
  57253. }
  57254. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  57255. for (var hNb = 0; hNb < holes.length; hNb++) {
  57256. hole = [];
  57257. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  57258. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  57259. }
  57260. polygonTriangulation.addHole(hole);
  57261. }
  57262. var polygon = polygonTriangulation.build(options.updatable, depth);
  57263. polygon._originalBuilderSideOrientation = options.sideOrientation;
  57264. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  57265. vertexData.applyToMesh(polygon, options.updatable);
  57266. return polygon;
  57267. };
  57268. ;
  57269. /**
  57270. * Creates an extruded polygon mesh, with depth in the Y direction.
  57271. * 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).
  57272. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57273. */
  57274. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  57275. return MeshBuilder.CreatePolygon(name, options, scene);
  57276. };
  57277. ;
  57278. /**
  57279. * Creates a tube mesh.
  57280. * 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.
  57281. *
  57282. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  57283. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  57284. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  57285. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  57286. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  57287. * 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.
  57288. * It must return a radius value (positive float) :
  57289. * ```javascript
  57290. * var radiusFunction = function(i, distance) {
  57291. * // do things
  57292. * return radius; }
  57293. * ```
  57294. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  57295. * 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
  57296. * 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
  57297. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57298. * 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).
  57299. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57300. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57301. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57302. */
  57303. MeshBuilder.CreateTube = function (name, options, scene) {
  57304. var path = options.path;
  57305. var instance = options.instance;
  57306. var radius = 1.0;
  57307. if (instance) {
  57308. radius = instance.radius;
  57309. }
  57310. if (options.radius !== undefined) {
  57311. radius = options.radius;
  57312. }
  57313. ;
  57314. var tessellation = options.tessellation || 64 | 0;
  57315. var radiusFunction = options.radiusFunction || null;
  57316. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57317. var invertUV = options.invertUV || false;
  57318. var updatable = options.updatable;
  57319. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57320. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  57321. // tube geometry
  57322. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  57323. var tangents = path3D.getTangents();
  57324. var normals = path3D.getNormals();
  57325. var distances = path3D.getDistances();
  57326. var pi2 = Math.PI * 2;
  57327. var step = pi2 / tessellation * arc;
  57328. var returnRadius = function () { return radius; };
  57329. var radiusFunctionFinal = radiusFunction || returnRadius;
  57330. var circlePath;
  57331. var rad;
  57332. var normal;
  57333. var rotated;
  57334. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57335. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57336. for (var i = 0; i < path.length; i++) {
  57337. rad = radiusFunctionFinal(i, distances[i]); // current radius
  57338. circlePath = Array(); // current circle array
  57339. normal = normals[i]; // current normal
  57340. for (var t = 0; t < tessellation; t++) {
  57341. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  57342. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  57343. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  57344. rotated.scaleInPlace(rad).addInPlace(path[i]);
  57345. circlePath[t] = rotated;
  57346. }
  57347. circlePaths[index] = circlePath;
  57348. index++;
  57349. }
  57350. // cap
  57351. var capPath = function (nbPoints, pathIndex) {
  57352. var pointCap = Array();
  57353. for (var i = 0; i < nbPoints; i++) {
  57354. pointCap.push(path[pathIndex]);
  57355. }
  57356. return pointCap;
  57357. };
  57358. switch (cap) {
  57359. case BABYLON.Mesh.NO_CAP:
  57360. break;
  57361. case BABYLON.Mesh.CAP_START:
  57362. circlePaths[0] = capPath(tessellation, 0);
  57363. circlePaths[1] = circlePaths[2].slice(0);
  57364. break;
  57365. case BABYLON.Mesh.CAP_END:
  57366. circlePaths[index] = circlePaths[index - 1].slice(0);
  57367. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57368. break;
  57369. case BABYLON.Mesh.CAP_ALL:
  57370. circlePaths[0] = capPath(tessellation, 0);
  57371. circlePaths[1] = circlePaths[2].slice(0);
  57372. circlePaths[index] = circlePaths[index - 1].slice(0);
  57373. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57374. break;
  57375. default:
  57376. break;
  57377. }
  57378. return circlePaths;
  57379. };
  57380. var path3D;
  57381. var pathArray;
  57382. if (instance) {
  57383. var arc = options.arc || instance.arc;
  57384. path3D = (instance.path3D).update(path);
  57385. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  57386. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  57387. instance.path3D = path3D;
  57388. instance.pathArray = pathArray;
  57389. instance.arc = arc;
  57390. instance.radius = radius;
  57391. return instance;
  57392. }
  57393. // tube creation
  57394. path3D = new BABYLON.Path3D(path);
  57395. var newPathArray = new Array();
  57396. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57397. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57398. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57399. tube.pathArray = pathArray;
  57400. tube.path3D = path3D;
  57401. tube.tessellation = tessellation;
  57402. tube.cap = cap;
  57403. tube.arc = options.arc;
  57404. tube.radius = radius;
  57405. return tube;
  57406. };
  57407. /**
  57408. * Creates a polyhedron mesh.
  57409. *
  57410. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57411. * 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
  57412. * to choose the wanted type.
  57413. * The parameter `size` (positive float, default 1) sets the polygon size.
  57414. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57415. * 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`.
  57416. * 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
  57417. * 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)`).
  57418. * 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
  57419. * 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.
  57420. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57421. * 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).
  57422. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57423. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57424. */
  57425. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57426. var polyhedron = new BABYLON.Mesh(name, scene);
  57427. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57428. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57429. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57430. vertexData.applyToMesh(polyhedron, options.updatable);
  57431. return polyhedron;
  57432. };
  57433. /**
  57434. * Creates a decal mesh.
  57435. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57436. * 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.
  57437. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57438. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57439. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57440. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57441. */
  57442. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57443. var indices = sourceMesh.getIndices();
  57444. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57445. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57446. var position = options.position || BABYLON.Vector3.Zero();
  57447. var normal = options.normal || BABYLON.Vector3.Up();
  57448. var size = options.size || BABYLON.Vector3.One();
  57449. var angle = options.angle || 0;
  57450. // Getting correct rotation
  57451. if (!normal) {
  57452. var target = new BABYLON.Vector3(0, 0, 1);
  57453. var camera = sourceMesh.getScene().activeCamera;
  57454. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57455. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57456. }
  57457. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57458. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57459. var pitch = Math.atan2(normal.y, len);
  57460. // Matrix
  57461. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57462. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57463. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57464. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57465. var vertexData = new BABYLON.VertexData();
  57466. vertexData.indices = [];
  57467. vertexData.positions = [];
  57468. vertexData.normals = [];
  57469. vertexData.uvs = [];
  57470. var currentVertexDataIndex = 0;
  57471. var extractDecalVector3 = function (indexId) {
  57472. var result = new BABYLON.PositionNormalVertex();
  57473. if (!indices || !positions || !normals) {
  57474. return result;
  57475. }
  57476. var vertexId = indices[indexId];
  57477. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57478. // Send vector to decal local world
  57479. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57480. // Get normal
  57481. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57482. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57483. return result;
  57484. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57485. var clip = function (vertices, axis) {
  57486. if (vertices.length === 0) {
  57487. return vertices;
  57488. }
  57489. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57490. var clipVertices = function (v0, v1) {
  57491. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57492. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57493. };
  57494. var result = new Array();
  57495. for (var index = 0; index < vertices.length; index += 3) {
  57496. var v1Out;
  57497. var v2Out;
  57498. var v3Out;
  57499. var total = 0;
  57500. var nV1 = null;
  57501. var nV2 = null;
  57502. var nV3 = null;
  57503. var nV4 = null;
  57504. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57505. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57506. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57507. v1Out = d1 > 0;
  57508. v2Out = d2 > 0;
  57509. v3Out = d3 > 0;
  57510. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57511. switch (total) {
  57512. case 0:
  57513. result.push(vertices[index]);
  57514. result.push(vertices[index + 1]);
  57515. result.push(vertices[index + 2]);
  57516. break;
  57517. case 1:
  57518. if (v1Out) {
  57519. nV1 = vertices[index + 1];
  57520. nV2 = vertices[index + 2];
  57521. nV3 = clipVertices(vertices[index], nV1);
  57522. nV4 = clipVertices(vertices[index], nV2);
  57523. }
  57524. if (v2Out) {
  57525. nV1 = vertices[index];
  57526. nV2 = vertices[index + 2];
  57527. nV3 = clipVertices(vertices[index + 1], nV1);
  57528. nV4 = clipVertices(vertices[index + 1], nV2);
  57529. result.push(nV3);
  57530. result.push(nV2.clone());
  57531. result.push(nV1.clone());
  57532. result.push(nV2.clone());
  57533. result.push(nV3.clone());
  57534. result.push(nV4);
  57535. break;
  57536. }
  57537. if (v3Out) {
  57538. nV1 = vertices[index];
  57539. nV2 = vertices[index + 1];
  57540. nV3 = clipVertices(vertices[index + 2], nV1);
  57541. nV4 = clipVertices(vertices[index + 2], nV2);
  57542. }
  57543. if (nV1 && nV2 && nV3 && nV4) {
  57544. result.push(nV1.clone());
  57545. result.push(nV2.clone());
  57546. result.push(nV3);
  57547. result.push(nV4);
  57548. result.push(nV3.clone());
  57549. result.push(nV2.clone());
  57550. }
  57551. break;
  57552. case 2:
  57553. if (!v1Out) {
  57554. nV1 = vertices[index].clone();
  57555. nV2 = clipVertices(nV1, vertices[index + 1]);
  57556. nV3 = clipVertices(nV1, vertices[index + 2]);
  57557. result.push(nV1);
  57558. result.push(nV2);
  57559. result.push(nV3);
  57560. }
  57561. if (!v2Out) {
  57562. nV1 = vertices[index + 1].clone();
  57563. nV2 = clipVertices(nV1, vertices[index + 2]);
  57564. nV3 = clipVertices(nV1, vertices[index]);
  57565. result.push(nV1);
  57566. result.push(nV2);
  57567. result.push(nV3);
  57568. }
  57569. if (!v3Out) {
  57570. nV1 = vertices[index + 2].clone();
  57571. nV2 = clipVertices(nV1, vertices[index]);
  57572. nV3 = clipVertices(nV1, vertices[index + 1]);
  57573. result.push(nV1);
  57574. result.push(nV2);
  57575. result.push(nV3);
  57576. }
  57577. break;
  57578. case 3:
  57579. break;
  57580. }
  57581. }
  57582. return result;
  57583. };
  57584. for (var index = 0; index < indices.length; index += 3) {
  57585. var faceVertices = new Array();
  57586. faceVertices.push(extractDecalVector3(index));
  57587. faceVertices.push(extractDecalVector3(index + 1));
  57588. faceVertices.push(extractDecalVector3(index + 2));
  57589. // Clip
  57590. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57591. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57592. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57593. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57594. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57595. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57596. if (faceVertices.length === 0) {
  57597. continue;
  57598. }
  57599. // Add UVs and get back to world
  57600. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57601. var vertex = faceVertices[vIndex];
  57602. //TODO check for Int32Array | Uint32Array | Uint16Array
  57603. vertexData.indices.push(currentVertexDataIndex);
  57604. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57605. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57606. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57607. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57608. currentVertexDataIndex++;
  57609. }
  57610. }
  57611. // Return mesh
  57612. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57613. vertexData.applyToMesh(decal);
  57614. decal.position = position.clone();
  57615. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57616. return decal;
  57617. };
  57618. // Privates
  57619. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57620. // extrusion geometry
  57621. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57622. var tangents = path3D.getTangents();
  57623. var normals = path3D.getNormals();
  57624. var binormals = path3D.getBinormals();
  57625. var distances = path3D.getDistances();
  57626. var angle = 0;
  57627. var returnScale = function () { return scale !== null ? scale : 1; };
  57628. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57629. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57630. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57631. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57632. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57633. for (var i = 0; i < curve.length; i++) {
  57634. var shapePath = new Array();
  57635. var angleStep = rotate(i, distances[i]);
  57636. var scaleRatio = scl(i, distances[i]);
  57637. for (var p = 0; p < shape.length; p++) {
  57638. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57639. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57640. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57641. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57642. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57643. shapePath[p] = rotated;
  57644. }
  57645. shapePaths[index] = shapePath;
  57646. angle += angleStep;
  57647. index++;
  57648. }
  57649. // cap
  57650. var capPath = function (shapePath) {
  57651. var pointCap = Array();
  57652. var barycenter = BABYLON.Vector3.Zero();
  57653. var i;
  57654. for (i = 0; i < shapePath.length; i++) {
  57655. barycenter.addInPlace(shapePath[i]);
  57656. }
  57657. barycenter.scaleInPlace(1.0 / shapePath.length);
  57658. for (i = 0; i < shapePath.length; i++) {
  57659. pointCap.push(barycenter);
  57660. }
  57661. return pointCap;
  57662. };
  57663. switch (cap) {
  57664. case BABYLON.Mesh.NO_CAP:
  57665. break;
  57666. case BABYLON.Mesh.CAP_START:
  57667. shapePaths[0] = capPath(shapePaths[2]);
  57668. shapePaths[1] = shapePaths[2];
  57669. break;
  57670. case BABYLON.Mesh.CAP_END:
  57671. shapePaths[index] = shapePaths[index - 1];
  57672. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57673. break;
  57674. case BABYLON.Mesh.CAP_ALL:
  57675. shapePaths[0] = capPath(shapePaths[2]);
  57676. shapePaths[1] = shapePaths[2];
  57677. shapePaths[index] = shapePaths[index - 1];
  57678. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57679. break;
  57680. default:
  57681. break;
  57682. }
  57683. return shapePaths;
  57684. };
  57685. var path3D;
  57686. var pathArray;
  57687. if (instance) {
  57688. path3D = (instance.path3D).update(curve);
  57689. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57690. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57691. return instance;
  57692. }
  57693. // extruded shape creation
  57694. path3D = new BABYLON.Path3D(curve);
  57695. var newShapePaths = new Array();
  57696. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57697. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57698. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57699. extrudedGeneric.pathArray = pathArray;
  57700. extrudedGeneric.path3D = path3D;
  57701. extrudedGeneric.cap = cap;
  57702. return extrudedGeneric;
  57703. };
  57704. return MeshBuilder;
  57705. }());
  57706. BABYLON.MeshBuilder = MeshBuilder;
  57707. })(BABYLON || (BABYLON = {}));
  57708. //# sourceMappingURL=babylon.meshBuilder.js.map
  57709. "use strict";
  57710. var BABYLON;
  57711. (function (BABYLON) {
  57712. /**
  57713. * Draco compression (https://google.github.io/draco/)
  57714. */
  57715. var DracoCompression = /** @class */ (function () {
  57716. /**
  57717. * Constructor
  57718. * @param numWorkers The number of workers for async operations
  57719. */
  57720. function DracoCompression(numWorkers) {
  57721. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57722. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57723. if (!workerBlobUrl || !Worker) {
  57724. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57725. return;
  57726. }
  57727. var workers = new Array(numWorkers);
  57728. for (var i = 0; i < workers.length; i++) {
  57729. var worker = new Worker(workerBlobUrl);
  57730. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57731. workers[i] = worker;
  57732. }
  57733. this._workerPool = new BABYLON.WorkerPool(workers);
  57734. }
  57735. /**
  57736. * Stop all async operations and release resources.
  57737. */
  57738. DracoCompression.prototype.dispose = function () {
  57739. this._workerPool.dispose();
  57740. delete this._workerPool;
  57741. };
  57742. /**
  57743. * Decode Draco compressed mesh data to vertex data.
  57744. * @param data The array buffer view for the Draco compression data
  57745. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57746. * @returns A promise that resolves with the decoded vertex data
  57747. */
  57748. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57749. var _this = this;
  57750. return new Promise(function (resolve, reject) {
  57751. _this._workerPool.push(function (worker, onComplete) {
  57752. var vertexData = new BABYLON.VertexData();
  57753. var onError = function (error) {
  57754. worker.removeEventListener("error", onError);
  57755. worker.removeEventListener("message", onMessage);
  57756. reject(error);
  57757. onComplete();
  57758. };
  57759. var onMessage = function (message) {
  57760. if (message.data === "done") {
  57761. worker.removeEventListener("error", onError);
  57762. worker.removeEventListener("message", onMessage);
  57763. resolve(vertexData);
  57764. onComplete();
  57765. }
  57766. else if (message.data.id === "indices") {
  57767. vertexData.indices = message.data.value;
  57768. }
  57769. else {
  57770. vertexData.set(message.data.value, message.data.id);
  57771. }
  57772. };
  57773. worker.addEventListener("error", onError);
  57774. worker.addEventListener("message", onMessage);
  57775. var dataCopy = new Uint8Array(data.byteLength);
  57776. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57777. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57778. });
  57779. });
  57780. };
  57781. /**
  57782. * The worker function that gets converted to a blob url to pass into a worker.
  57783. */
  57784. DracoCompression._Worker = function () {
  57785. // self is actually a DedicatedWorkerGlobalScope
  57786. var _self = self;
  57787. var decodeMesh = function (data, attributes) {
  57788. var dracoModule = new DracoDecoderModule();
  57789. var buffer = new dracoModule.DecoderBuffer();
  57790. buffer.Init(data, data.byteLength);
  57791. var decoder = new dracoModule.Decoder();
  57792. var geometry;
  57793. var status;
  57794. try {
  57795. var type = decoder.GetEncodedGeometryType(buffer);
  57796. switch (type) {
  57797. case dracoModule.TRIANGULAR_MESH:
  57798. geometry = new dracoModule.Mesh();
  57799. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57800. break;
  57801. case dracoModule.POINT_CLOUD:
  57802. geometry = new dracoModule.PointCloud();
  57803. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57804. break;
  57805. default:
  57806. throw new Error("Invalid geometry type " + type);
  57807. }
  57808. if (!status.ok() || !geometry.ptr) {
  57809. throw new Error(status.error_msg());
  57810. }
  57811. var numPoints = geometry.num_points();
  57812. if (type === dracoModule.TRIANGULAR_MESH) {
  57813. var numFaces = geometry.num_faces();
  57814. var faceIndices = new dracoModule.DracoInt32Array();
  57815. try {
  57816. var indices = new Uint32Array(numFaces * 3);
  57817. for (var i = 0; i < numFaces; i++) {
  57818. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57819. var offset = i * 3;
  57820. indices[offset + 0] = faceIndices.GetValue(0);
  57821. indices[offset + 1] = faceIndices.GetValue(1);
  57822. indices[offset + 2] = faceIndices.GetValue(2);
  57823. }
  57824. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57825. }
  57826. finally {
  57827. dracoModule.destroy(faceIndices);
  57828. }
  57829. }
  57830. for (var kind in attributes) {
  57831. var uniqueId = attributes[kind];
  57832. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57833. var dracoData = new dracoModule.DracoFloat32Array();
  57834. try {
  57835. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57836. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57837. for (var i = 0; i < babylonData.length; i++) {
  57838. babylonData[i] = dracoData.GetValue(i);
  57839. }
  57840. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57841. }
  57842. finally {
  57843. dracoModule.destroy(dracoData);
  57844. }
  57845. }
  57846. }
  57847. finally {
  57848. if (geometry) {
  57849. dracoModule.destroy(geometry);
  57850. }
  57851. dracoModule.destroy(decoder);
  57852. dracoModule.destroy(buffer);
  57853. }
  57854. _self.postMessage("done");
  57855. };
  57856. _self.onmessage = function (event) {
  57857. switch (event.data.id) {
  57858. case "initDecoder": {
  57859. importScripts(event.data.url);
  57860. break;
  57861. }
  57862. case "decodeMesh": {
  57863. decodeMesh(event.data.data, event.data.attributes);
  57864. break;
  57865. }
  57866. }
  57867. };
  57868. };
  57869. DracoCompression._GetDefaultDecoderUrl = function () {
  57870. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57871. return null;
  57872. }
  57873. for (var i = 0; i < document.scripts.length; i++) {
  57874. if (document.scripts[i].type === "text/x-draco-decoder") {
  57875. return document.scripts[i].src;
  57876. }
  57877. }
  57878. return null;
  57879. };
  57880. /**
  57881. * Gets the url to the draco decoder if available.
  57882. */
  57883. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57884. return DracoCompression;
  57885. }());
  57886. BABYLON.DracoCompression = DracoCompression;
  57887. })(BABYLON || (BABYLON = {}));
  57888. //# sourceMappingURL=babylon.dracoCompression.js.map
  57889. "use strict";
  57890. var BABYLON;
  57891. (function (BABYLON) {
  57892. var AudioEngine = /** @class */ (function () {
  57893. function AudioEngine() {
  57894. this._audioContext = null;
  57895. this._audioContextInitialized = false;
  57896. this.canUseWebAudio = false;
  57897. this.WarnedWebAudioUnsupported = false;
  57898. this.unlocked = false;
  57899. this.isMP3supported = false;
  57900. this.isOGGsupported = false;
  57901. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57902. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57903. this.canUseWebAudio = true;
  57904. }
  57905. var audioElem = document.createElement('audio');
  57906. try {
  57907. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57908. this.isMP3supported = true;
  57909. }
  57910. }
  57911. catch (e) {
  57912. // protect error during capability check.
  57913. }
  57914. try {
  57915. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57916. this.isOGGsupported = true;
  57917. }
  57918. }
  57919. catch (e) {
  57920. // protect error during capability check.
  57921. }
  57922. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57923. this._unlockiOSaudio();
  57924. }
  57925. else {
  57926. this.unlocked = true;
  57927. }
  57928. }
  57929. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57930. get: function () {
  57931. if (!this._audioContextInitialized) {
  57932. this._initializeAudioContext();
  57933. }
  57934. return this._audioContext;
  57935. },
  57936. enumerable: true,
  57937. configurable: true
  57938. });
  57939. AudioEngine.prototype._unlockiOSaudio = function () {
  57940. var _this = this;
  57941. var unlockaudio = function () {
  57942. if (!_this.audioContext) {
  57943. return;
  57944. }
  57945. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57946. var source = _this.audioContext.createBufferSource();
  57947. source.buffer = buffer;
  57948. source.connect(_this.audioContext.destination);
  57949. source.start(0);
  57950. setTimeout(function () {
  57951. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57952. _this.unlocked = true;
  57953. window.removeEventListener('touchend', unlockaudio, false);
  57954. if (_this.onAudioUnlocked) {
  57955. _this.onAudioUnlocked();
  57956. }
  57957. }
  57958. }, 0);
  57959. };
  57960. window.addEventListener('touchend', unlockaudio, false);
  57961. };
  57962. AudioEngine.prototype._initializeAudioContext = function () {
  57963. try {
  57964. if (this.canUseWebAudio) {
  57965. this._audioContext = new AudioContext();
  57966. // create a global volume gain node
  57967. this.masterGain = this._audioContext.createGain();
  57968. this.masterGain.gain.value = 1;
  57969. this.masterGain.connect(this._audioContext.destination);
  57970. this._audioContextInitialized = true;
  57971. }
  57972. }
  57973. catch (e) {
  57974. this.canUseWebAudio = false;
  57975. BABYLON.Tools.Error("Web Audio: " + e.message);
  57976. }
  57977. };
  57978. AudioEngine.prototype.dispose = function () {
  57979. if (this.canUseWebAudio && this._audioContextInitialized) {
  57980. if (this._connectedAnalyser && this._audioContext) {
  57981. this._connectedAnalyser.stopDebugCanvas();
  57982. this._connectedAnalyser.dispose();
  57983. this.masterGain.disconnect();
  57984. this.masterGain.connect(this._audioContext.destination);
  57985. this._connectedAnalyser = null;
  57986. }
  57987. this.masterGain.gain.value = 1;
  57988. }
  57989. this.WarnedWebAudioUnsupported = false;
  57990. };
  57991. AudioEngine.prototype.getGlobalVolume = function () {
  57992. if (this.canUseWebAudio && this._audioContextInitialized) {
  57993. return this.masterGain.gain.value;
  57994. }
  57995. else {
  57996. return -1;
  57997. }
  57998. };
  57999. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  58000. if (this.canUseWebAudio && this._audioContextInitialized) {
  58001. this.masterGain.gain.value = newVolume;
  58002. }
  58003. };
  58004. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  58005. if (this._connectedAnalyser) {
  58006. this._connectedAnalyser.stopDebugCanvas();
  58007. }
  58008. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  58009. this._connectedAnalyser = analyser;
  58010. this.masterGain.disconnect();
  58011. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  58012. }
  58013. };
  58014. return AudioEngine;
  58015. }());
  58016. BABYLON.AudioEngine = AudioEngine;
  58017. })(BABYLON || (BABYLON = {}));
  58018. //# sourceMappingURL=babylon.audioEngine.js.map
  58019. "use strict";
  58020. var BABYLON;
  58021. (function (BABYLON) {
  58022. var Sound = /** @class */ (function () {
  58023. /**
  58024. * Create a sound and attach it to a scene
  58025. * @param name Name of your sound
  58026. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  58027. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  58028. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  58029. */
  58030. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  58031. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  58032. var _this = this;
  58033. this.autoplay = false;
  58034. this.loop = false;
  58035. this.useCustomAttenuation = false;
  58036. this.spatialSound = false;
  58037. this.refDistance = 1;
  58038. this.rolloffFactor = 1;
  58039. this.maxDistance = 100;
  58040. this.distanceModel = "linear";
  58041. this._panningModel = "equalpower";
  58042. this._playbackRate = 1;
  58043. this._streaming = false;
  58044. this._startTime = 0;
  58045. this._startOffset = 0;
  58046. this._position = BABYLON.Vector3.Zero();
  58047. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  58048. this._volume = 1;
  58049. this._isReadyToPlay = false;
  58050. this.isPlaying = false;
  58051. this.isPaused = false;
  58052. this._isDirectional = false;
  58053. // Used if you'd like to create a directional sound.
  58054. // If not set, the sound will be omnidirectional
  58055. this._coneInnerAngle = 360;
  58056. this._coneOuterAngle = 360;
  58057. this._coneOuterGain = 0;
  58058. this._isOutputConnected = false;
  58059. this._urlType = "Unknown";
  58060. this.name = name;
  58061. this._scene = scene;
  58062. this._readyToPlayCallback = readyToPlayCallback;
  58063. // Default custom attenuation function is a linear attenuation
  58064. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  58065. if (currentDistance < maxDistance) {
  58066. return currentVolume * (1 - currentDistance / maxDistance);
  58067. }
  58068. else {
  58069. return 0;
  58070. }
  58071. };
  58072. if (options) {
  58073. this.autoplay = options.autoplay || false;
  58074. this.loop = options.loop || false;
  58075. // if volume === 0, we need another way to check this option
  58076. if (options.volume !== undefined) {
  58077. this._volume = options.volume;
  58078. }
  58079. this.spatialSound = options.spatialSound || false;
  58080. this.maxDistance = options.maxDistance || 100;
  58081. this.useCustomAttenuation = options.useCustomAttenuation || false;
  58082. this.rolloffFactor = options.rolloffFactor || 1;
  58083. this.refDistance = options.refDistance || 1;
  58084. this.distanceModel = options.distanceModel || "linear";
  58085. this._playbackRate = options.playbackRate || 1;
  58086. this._streaming = options.streaming || false;
  58087. }
  58088. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58089. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  58090. this._soundGain.gain.value = this._volume;
  58091. this._inputAudioNode = this._soundGain;
  58092. this._ouputAudioNode = this._soundGain;
  58093. if (this.spatialSound) {
  58094. this._createSpatialParameters();
  58095. }
  58096. this._scene.mainSoundTrack.AddSound(this);
  58097. var validParameter = true;
  58098. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  58099. if (urlOrArrayBuffer) {
  58100. try {
  58101. if (typeof (urlOrArrayBuffer) === "string")
  58102. this._urlType = "String";
  58103. if (Array.isArray(urlOrArrayBuffer))
  58104. this._urlType = "Array";
  58105. if (urlOrArrayBuffer instanceof ArrayBuffer)
  58106. this._urlType = "ArrayBuffer";
  58107. var urls = [];
  58108. var codecSupportedFound = false;
  58109. switch (this._urlType) {
  58110. case "ArrayBuffer":
  58111. if (urlOrArrayBuffer.byteLength > 0) {
  58112. codecSupportedFound = true;
  58113. this._soundLoaded(urlOrArrayBuffer);
  58114. }
  58115. break;
  58116. case "String":
  58117. urls.push(urlOrArrayBuffer);
  58118. case "Array":
  58119. if (urls.length === 0)
  58120. urls = urlOrArrayBuffer;
  58121. // If we found a supported format, we load it immediately and stop the loop
  58122. for (var i = 0; i < urls.length; i++) {
  58123. var url = urls[i];
  58124. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  58125. codecSupportedFound = true;
  58126. }
  58127. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  58128. codecSupportedFound = true;
  58129. }
  58130. if (url.indexOf(".wav", url.length - 4) !== -1) {
  58131. codecSupportedFound = true;
  58132. }
  58133. if (url.indexOf("blob:") !== -1) {
  58134. codecSupportedFound = true;
  58135. }
  58136. if (codecSupportedFound) {
  58137. // Loading sound using XHR2
  58138. if (!this._streaming) {
  58139. this._scene._loadFile(url, function (data) {
  58140. _this._soundLoaded(data);
  58141. }, undefined, true, true, function (exception) {
  58142. if (exception) {
  58143. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  58144. }
  58145. BABYLON.Tools.Error("Sound creation aborted.");
  58146. _this._scene.mainSoundTrack.RemoveSound(_this);
  58147. });
  58148. }
  58149. else {
  58150. this._htmlAudioElement = new Audio(url);
  58151. this._htmlAudioElement.controls = false;
  58152. this._htmlAudioElement.loop = this.loop;
  58153. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  58154. this._htmlAudioElement.preload = "auto";
  58155. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  58156. _this._isReadyToPlay = true;
  58157. if (_this.autoplay) {
  58158. _this.play();
  58159. }
  58160. if (_this._readyToPlayCallback) {
  58161. _this._readyToPlayCallback();
  58162. }
  58163. });
  58164. document.body.appendChild(this._htmlAudioElement);
  58165. }
  58166. break;
  58167. }
  58168. }
  58169. break;
  58170. default:
  58171. validParameter = false;
  58172. break;
  58173. }
  58174. if (!validParameter) {
  58175. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  58176. }
  58177. else {
  58178. if (!codecSupportedFound) {
  58179. this._isReadyToPlay = true;
  58180. // Simulating a ready to play event to avoid breaking code path
  58181. if (this._readyToPlayCallback) {
  58182. window.setTimeout(function () {
  58183. if (_this._readyToPlayCallback) {
  58184. _this._readyToPlayCallback();
  58185. }
  58186. }, 1000);
  58187. }
  58188. }
  58189. }
  58190. }
  58191. catch (ex) {
  58192. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  58193. this._scene.mainSoundTrack.RemoveSound(this);
  58194. }
  58195. }
  58196. }
  58197. else {
  58198. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  58199. this._scene.mainSoundTrack.AddSound(this);
  58200. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  58201. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  58202. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  58203. }
  58204. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  58205. if (this._readyToPlayCallback) {
  58206. window.setTimeout(function () {
  58207. if (_this._readyToPlayCallback) {
  58208. _this._readyToPlayCallback();
  58209. }
  58210. }, 1000);
  58211. }
  58212. }
  58213. }
  58214. Sound.prototype.dispose = function () {
  58215. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58216. if (this.isPlaying) {
  58217. this.stop();
  58218. }
  58219. this._isReadyToPlay = false;
  58220. if (this.soundTrackId === -1) {
  58221. this._scene.mainSoundTrack.RemoveSound(this);
  58222. }
  58223. else {
  58224. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  58225. }
  58226. if (this._soundGain) {
  58227. this._soundGain.disconnect();
  58228. this._soundGain = null;
  58229. }
  58230. if (this._soundPanner) {
  58231. this._soundPanner.disconnect();
  58232. this._soundPanner = null;
  58233. }
  58234. if (this._soundSource) {
  58235. this._soundSource.disconnect();
  58236. this._soundSource = null;
  58237. }
  58238. this._audioBuffer = null;
  58239. if (this._htmlAudioElement) {
  58240. this._htmlAudioElement.pause();
  58241. this._htmlAudioElement.src = "";
  58242. document.body.removeChild(this._htmlAudioElement);
  58243. }
  58244. if (this._connectedMesh && this._registerFunc) {
  58245. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58246. this._connectedMesh = null;
  58247. }
  58248. }
  58249. };
  58250. Sound.prototype.isReady = function () {
  58251. return this._isReadyToPlay;
  58252. };
  58253. Sound.prototype._soundLoaded = function (audioData) {
  58254. var _this = this;
  58255. if (!BABYLON.Engine.audioEngine.audioContext) {
  58256. return;
  58257. }
  58258. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  58259. _this._audioBuffer = buffer;
  58260. _this._isReadyToPlay = true;
  58261. if (_this.autoplay) {
  58262. _this.play();
  58263. }
  58264. if (_this._readyToPlayCallback) {
  58265. _this._readyToPlayCallback();
  58266. }
  58267. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  58268. };
  58269. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  58270. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58271. this._audioBuffer = audioBuffer;
  58272. this._isReadyToPlay = true;
  58273. }
  58274. };
  58275. Sound.prototype.updateOptions = function (options) {
  58276. if (options) {
  58277. this.loop = options.loop || this.loop;
  58278. this.maxDistance = options.maxDistance || this.maxDistance;
  58279. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  58280. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  58281. this.refDistance = options.refDistance || this.refDistance;
  58282. this.distanceModel = options.distanceModel || this.distanceModel;
  58283. this._playbackRate = options.playbackRate || this._playbackRate;
  58284. this._updateSpatialParameters();
  58285. if (this.isPlaying) {
  58286. if (this._streaming) {
  58287. this._htmlAudioElement.playbackRate = this._playbackRate;
  58288. }
  58289. else {
  58290. if (this._soundSource) {
  58291. this._soundSource.playbackRate.value = this._playbackRate;
  58292. }
  58293. }
  58294. }
  58295. }
  58296. };
  58297. Sound.prototype._createSpatialParameters = function () {
  58298. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58299. if (this._scene.headphone) {
  58300. this._panningModel = "HRTF";
  58301. }
  58302. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  58303. this._updateSpatialParameters();
  58304. this._soundPanner.connect(this._ouputAudioNode);
  58305. this._inputAudioNode = this._soundPanner;
  58306. }
  58307. };
  58308. Sound.prototype._updateSpatialParameters = function () {
  58309. if (this.spatialSound && this._soundPanner) {
  58310. if (this.useCustomAttenuation) {
  58311. // Tricks to disable in a way embedded Web Audio attenuation
  58312. this._soundPanner.distanceModel = "linear";
  58313. this._soundPanner.maxDistance = Number.MAX_VALUE;
  58314. this._soundPanner.refDistance = 1;
  58315. this._soundPanner.rolloffFactor = 1;
  58316. this._soundPanner.panningModel = this._panningModel;
  58317. }
  58318. else {
  58319. this._soundPanner.distanceModel = this.distanceModel;
  58320. this._soundPanner.maxDistance = this.maxDistance;
  58321. this._soundPanner.refDistance = this.refDistance;
  58322. this._soundPanner.rolloffFactor = this.rolloffFactor;
  58323. this._soundPanner.panningModel = this._panningModel;
  58324. }
  58325. }
  58326. };
  58327. Sound.prototype.switchPanningModelToHRTF = function () {
  58328. this._panningModel = "HRTF";
  58329. this._switchPanningModel();
  58330. };
  58331. Sound.prototype.switchPanningModelToEqualPower = function () {
  58332. this._panningModel = "equalpower";
  58333. this._switchPanningModel();
  58334. };
  58335. Sound.prototype._switchPanningModel = function () {
  58336. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58337. this._soundPanner.panningModel = this._panningModel;
  58338. }
  58339. };
  58340. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  58341. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58342. if (this._isOutputConnected) {
  58343. this._ouputAudioNode.disconnect();
  58344. }
  58345. this._ouputAudioNode.connect(soundTrackAudioNode);
  58346. this._isOutputConnected = true;
  58347. }
  58348. };
  58349. /**
  58350. * Transform this sound into a directional source
  58351. * @param coneInnerAngle Size of the inner cone in degree
  58352. * @param coneOuterAngle Size of the outer cone in degree
  58353. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  58354. */
  58355. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  58356. if (coneOuterAngle < coneInnerAngle) {
  58357. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  58358. return;
  58359. }
  58360. this._coneInnerAngle = coneInnerAngle;
  58361. this._coneOuterAngle = coneOuterAngle;
  58362. this._coneOuterGain = coneOuterGain;
  58363. this._isDirectional = true;
  58364. if (this.isPlaying && this.loop) {
  58365. this.stop();
  58366. this.play();
  58367. }
  58368. };
  58369. Sound.prototype.setPosition = function (newPosition) {
  58370. this._position = newPosition;
  58371. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58372. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58373. }
  58374. };
  58375. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  58376. this._localDirection = newLocalDirection;
  58377. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  58378. this._updateDirection();
  58379. }
  58380. };
  58381. Sound.prototype._updateDirection = function () {
  58382. if (!this._connectedMesh || !this._soundPanner) {
  58383. return;
  58384. }
  58385. var mat = this._connectedMesh.getWorldMatrix();
  58386. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  58387. direction.normalize();
  58388. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  58389. };
  58390. Sound.prototype.updateDistanceFromListener = function () {
  58391. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  58392. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  58393. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  58394. }
  58395. };
  58396. Sound.prototype.setAttenuationFunction = function (callback) {
  58397. this._customAttenuationFunction = callback;
  58398. };
  58399. /**
  58400. * Play the sound
  58401. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  58402. * @param offset (optional) Start the sound setting it at a specific time
  58403. */
  58404. Sound.prototype.play = function (time, offset) {
  58405. var _this = this;
  58406. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  58407. try {
  58408. if (this._startOffset < 0) {
  58409. time = -this._startOffset;
  58410. this._startOffset = 0;
  58411. }
  58412. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58413. if (!this._soundSource || !this._streamingSource) {
  58414. if (this.spatialSound && this._soundPanner) {
  58415. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58416. if (this._isDirectional) {
  58417. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58418. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58419. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58420. if (this._connectedMesh) {
  58421. this._updateDirection();
  58422. }
  58423. else {
  58424. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58425. }
  58426. }
  58427. }
  58428. }
  58429. if (this._streaming) {
  58430. if (!this._streamingSource) {
  58431. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58432. this._htmlAudioElement.onended = function () { _this._onended(); };
  58433. this._htmlAudioElement.playbackRate = this._playbackRate;
  58434. }
  58435. this._streamingSource.disconnect();
  58436. this._streamingSource.connect(this._inputAudioNode);
  58437. this._htmlAudioElement.play();
  58438. }
  58439. else {
  58440. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58441. this._soundSource.buffer = this._audioBuffer;
  58442. this._soundSource.connect(this._inputAudioNode);
  58443. this._soundSource.loop = this.loop;
  58444. this._soundSource.playbackRate.value = this._playbackRate;
  58445. this._soundSource.onended = function () { _this._onended(); };
  58446. if (this._soundSource.buffer) {
  58447. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58448. }
  58449. }
  58450. this._startTime = startTime;
  58451. this.isPlaying = true;
  58452. this.isPaused = false;
  58453. }
  58454. catch (ex) {
  58455. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58456. }
  58457. }
  58458. };
  58459. Sound.prototype._onended = function () {
  58460. this.isPlaying = false;
  58461. if (this.onended) {
  58462. this.onended();
  58463. }
  58464. };
  58465. /**
  58466. * Stop the sound
  58467. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58468. */
  58469. Sound.prototype.stop = function (time) {
  58470. if (this.isPlaying) {
  58471. if (this._streaming) {
  58472. this._htmlAudioElement.pause();
  58473. // Test needed for Firefox or it will generate an Invalid State Error
  58474. if (this._htmlAudioElement.currentTime > 0) {
  58475. this._htmlAudioElement.currentTime = 0;
  58476. }
  58477. }
  58478. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58479. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58480. this._soundSource.stop(stopTime);
  58481. this._soundSource.onended = function () { };
  58482. if (!this.isPaused) {
  58483. this._startOffset = 0;
  58484. }
  58485. }
  58486. this.isPlaying = false;
  58487. }
  58488. };
  58489. Sound.prototype.pause = function () {
  58490. if (this.isPlaying) {
  58491. this.isPaused = true;
  58492. if (this._streaming) {
  58493. this._htmlAudioElement.pause();
  58494. }
  58495. else if (BABYLON.Engine.audioEngine.audioContext) {
  58496. this.stop(0);
  58497. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58498. }
  58499. }
  58500. };
  58501. Sound.prototype.setVolume = function (newVolume, time) {
  58502. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58503. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58504. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58505. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58506. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58507. }
  58508. else {
  58509. this._soundGain.gain.value = newVolume;
  58510. }
  58511. }
  58512. this._volume = newVolume;
  58513. };
  58514. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58515. this._playbackRate = newPlaybackRate;
  58516. if (this.isPlaying) {
  58517. if (this._streaming) {
  58518. this._htmlAudioElement.playbackRate = this._playbackRate;
  58519. }
  58520. else if (this._soundSource) {
  58521. this._soundSource.playbackRate.value = this._playbackRate;
  58522. }
  58523. }
  58524. };
  58525. Sound.prototype.getVolume = function () {
  58526. return this._volume;
  58527. };
  58528. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58529. var _this = this;
  58530. if (this._connectedMesh && this._registerFunc) {
  58531. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58532. this._registerFunc = null;
  58533. }
  58534. this._connectedMesh = meshToConnectTo;
  58535. if (!this.spatialSound) {
  58536. this.spatialSound = true;
  58537. this._createSpatialParameters();
  58538. if (this.isPlaying && this.loop) {
  58539. this.stop();
  58540. this.play();
  58541. }
  58542. }
  58543. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58544. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58545. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58546. };
  58547. Sound.prototype.detachFromMesh = function () {
  58548. if (this._connectedMesh && this._registerFunc) {
  58549. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58550. this._registerFunc = null;
  58551. this._connectedMesh = null;
  58552. }
  58553. };
  58554. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58555. if (!node.getBoundingInfo) {
  58556. return;
  58557. }
  58558. var mesh = node;
  58559. var boundingInfo = mesh.getBoundingInfo();
  58560. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58561. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58562. this._updateDirection();
  58563. }
  58564. };
  58565. Sound.prototype.clone = function () {
  58566. var _this = this;
  58567. if (!this._streaming) {
  58568. var setBufferAndRun = function () {
  58569. if (_this._isReadyToPlay) {
  58570. clonedSound._audioBuffer = _this.getAudioBuffer();
  58571. clonedSound._isReadyToPlay = true;
  58572. if (clonedSound.autoplay) {
  58573. clonedSound.play();
  58574. }
  58575. }
  58576. else {
  58577. window.setTimeout(setBufferAndRun, 300);
  58578. }
  58579. };
  58580. var currentOptions = {
  58581. autoplay: this.autoplay, loop: this.loop,
  58582. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58583. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58584. refDistance: this.refDistance, distanceModel: this.distanceModel
  58585. };
  58586. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58587. if (this.useCustomAttenuation) {
  58588. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58589. }
  58590. clonedSound.setPosition(this._position);
  58591. clonedSound.setPlaybackRate(this._playbackRate);
  58592. setBufferAndRun();
  58593. return clonedSound;
  58594. }
  58595. else {
  58596. return null;
  58597. }
  58598. };
  58599. Sound.prototype.getAudioBuffer = function () {
  58600. return this._audioBuffer;
  58601. };
  58602. Sound.prototype.serialize = function () {
  58603. var serializationObject = {
  58604. name: this.name,
  58605. url: this.name,
  58606. autoplay: this.autoplay,
  58607. loop: this.loop,
  58608. volume: this._volume,
  58609. spatialSound: this.spatialSound,
  58610. maxDistance: this.maxDistance,
  58611. rolloffFactor: this.rolloffFactor,
  58612. refDistance: this.refDistance,
  58613. distanceModel: this.distanceModel,
  58614. playbackRate: this._playbackRate,
  58615. panningModel: this._panningModel,
  58616. soundTrackId: this.soundTrackId
  58617. };
  58618. if (this.spatialSound) {
  58619. if (this._connectedMesh)
  58620. serializationObject.connectedMeshId = this._connectedMesh.id;
  58621. serializationObject.position = this._position.asArray();
  58622. serializationObject.refDistance = this.refDistance;
  58623. serializationObject.distanceModel = this.distanceModel;
  58624. serializationObject.isDirectional = this._isDirectional;
  58625. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58626. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58627. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58628. serializationObject.coneOuterGain = this._coneOuterGain;
  58629. }
  58630. return serializationObject;
  58631. };
  58632. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58633. var soundName = parsedSound.name;
  58634. var soundUrl;
  58635. if (parsedSound.url) {
  58636. soundUrl = rootUrl + parsedSound.url;
  58637. }
  58638. else {
  58639. soundUrl = rootUrl + soundName;
  58640. }
  58641. var options = {
  58642. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58643. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58644. rolloffFactor: parsedSound.rolloffFactor,
  58645. refDistance: parsedSound.refDistance,
  58646. distanceModel: parsedSound.distanceModel,
  58647. playbackRate: parsedSound.playbackRate
  58648. };
  58649. var newSound;
  58650. if (!sourceSound) {
  58651. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58652. scene._addPendingData(newSound);
  58653. }
  58654. else {
  58655. var setBufferAndRun = function () {
  58656. if (sourceSound._isReadyToPlay) {
  58657. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58658. newSound._isReadyToPlay = true;
  58659. if (newSound.autoplay) {
  58660. newSound.play();
  58661. }
  58662. }
  58663. else {
  58664. window.setTimeout(setBufferAndRun, 300);
  58665. }
  58666. };
  58667. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58668. setBufferAndRun();
  58669. }
  58670. if (parsedSound.position) {
  58671. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58672. newSound.setPosition(soundPosition);
  58673. }
  58674. if (parsedSound.isDirectional) {
  58675. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58676. if (parsedSound.localDirectionToMesh) {
  58677. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58678. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58679. }
  58680. }
  58681. if (parsedSound.connectedMeshId) {
  58682. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58683. if (connectedMesh) {
  58684. newSound.attachToMesh(connectedMesh);
  58685. }
  58686. }
  58687. return newSound;
  58688. };
  58689. return Sound;
  58690. }());
  58691. BABYLON.Sound = Sound;
  58692. })(BABYLON || (BABYLON = {}));
  58693. //# sourceMappingURL=babylon.sound.js.map
  58694. "use strict";
  58695. var BABYLON;
  58696. (function (BABYLON) {
  58697. var SoundTrack = /** @class */ (function () {
  58698. function SoundTrack(scene, options) {
  58699. this.id = -1;
  58700. this._isMainTrack = false;
  58701. this._isInitialized = false;
  58702. this._scene = scene;
  58703. this.soundCollection = new Array();
  58704. this._options = options;
  58705. if (!this._isMainTrack) {
  58706. this._scene.soundTracks.push(this);
  58707. this.id = this._scene.soundTracks.length - 1;
  58708. }
  58709. }
  58710. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58711. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58712. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58713. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58714. if (this._options) {
  58715. if (this._options.volume) {
  58716. this._outputAudioNode.gain.value = this._options.volume;
  58717. }
  58718. if (this._options.mainTrack) {
  58719. this._isMainTrack = this._options.mainTrack;
  58720. }
  58721. }
  58722. this._isInitialized = true;
  58723. }
  58724. };
  58725. SoundTrack.prototype.dispose = function () {
  58726. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58727. if (this._connectedAnalyser) {
  58728. this._connectedAnalyser.stopDebugCanvas();
  58729. }
  58730. while (this.soundCollection.length) {
  58731. this.soundCollection[0].dispose();
  58732. }
  58733. if (this._outputAudioNode) {
  58734. this._outputAudioNode.disconnect();
  58735. }
  58736. this._outputAudioNode = null;
  58737. }
  58738. };
  58739. SoundTrack.prototype.AddSound = function (sound) {
  58740. if (!this._isInitialized) {
  58741. this._initializeSoundTrackAudioGraph();
  58742. }
  58743. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58744. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58745. }
  58746. if (sound.soundTrackId) {
  58747. if (sound.soundTrackId === -1) {
  58748. this._scene.mainSoundTrack.RemoveSound(sound);
  58749. }
  58750. else {
  58751. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58752. }
  58753. }
  58754. this.soundCollection.push(sound);
  58755. sound.soundTrackId = this.id;
  58756. };
  58757. SoundTrack.prototype.RemoveSound = function (sound) {
  58758. var index = this.soundCollection.indexOf(sound);
  58759. if (index !== -1) {
  58760. this.soundCollection.splice(index, 1);
  58761. }
  58762. };
  58763. SoundTrack.prototype.setVolume = function (newVolume) {
  58764. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58765. this._outputAudioNode.gain.value = newVolume;
  58766. }
  58767. };
  58768. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58769. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58770. for (var i = 0; i < this.soundCollection.length; i++) {
  58771. this.soundCollection[i].switchPanningModelToHRTF();
  58772. }
  58773. }
  58774. };
  58775. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58776. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58777. for (var i = 0; i < this.soundCollection.length; i++) {
  58778. this.soundCollection[i].switchPanningModelToEqualPower();
  58779. }
  58780. }
  58781. };
  58782. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58783. if (this._connectedAnalyser) {
  58784. this._connectedAnalyser.stopDebugCanvas();
  58785. }
  58786. this._connectedAnalyser = analyser;
  58787. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58788. this._outputAudioNode.disconnect();
  58789. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58790. }
  58791. };
  58792. return SoundTrack;
  58793. }());
  58794. BABYLON.SoundTrack = SoundTrack;
  58795. })(BABYLON || (BABYLON = {}));
  58796. //# sourceMappingURL=babylon.soundtrack.js.map
  58797. "use strict";
  58798. var BABYLON;
  58799. (function (BABYLON) {
  58800. var Analyser = /** @class */ (function () {
  58801. function Analyser(scene) {
  58802. this.SMOOTHING = 0.75;
  58803. this.FFT_SIZE = 512;
  58804. this.BARGRAPHAMPLITUDE = 256;
  58805. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58806. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58807. this._scene = scene;
  58808. this._audioEngine = BABYLON.Engine.audioEngine;
  58809. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58810. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58811. this._webAudioAnalyser.minDecibels = -140;
  58812. this._webAudioAnalyser.maxDecibels = 0;
  58813. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58814. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58815. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58816. }
  58817. }
  58818. Analyser.prototype.getFrequencyBinCount = function () {
  58819. if (this._audioEngine.canUseWebAudio) {
  58820. return this._webAudioAnalyser.frequencyBinCount;
  58821. }
  58822. else {
  58823. return 0;
  58824. }
  58825. };
  58826. Analyser.prototype.getByteFrequencyData = function () {
  58827. if (this._audioEngine.canUseWebAudio) {
  58828. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58829. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58830. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58831. }
  58832. return this._byteFreqs;
  58833. };
  58834. Analyser.prototype.getByteTimeDomainData = function () {
  58835. if (this._audioEngine.canUseWebAudio) {
  58836. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58837. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58838. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58839. }
  58840. return this._byteTime;
  58841. };
  58842. Analyser.prototype.getFloatFrequencyData = function () {
  58843. if (this._audioEngine.canUseWebAudio) {
  58844. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58845. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58846. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58847. }
  58848. return this._floatFreqs;
  58849. };
  58850. Analyser.prototype.drawDebugCanvas = function () {
  58851. var _this = this;
  58852. if (this._audioEngine.canUseWebAudio) {
  58853. if (!this._debugCanvas) {
  58854. this._debugCanvas = document.createElement("canvas");
  58855. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58856. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58857. this._debugCanvas.style.position = "absolute";
  58858. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58859. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58860. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58861. document.body.appendChild(this._debugCanvas);
  58862. this._registerFunc = function () {
  58863. _this.drawDebugCanvas();
  58864. };
  58865. this._scene.registerBeforeRender(this._registerFunc);
  58866. }
  58867. if (this._registerFunc && this._debugCanvasContext) {
  58868. var workingArray = this.getByteFrequencyData();
  58869. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58870. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58871. // Draw the frequency domain chart.
  58872. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58873. var value = workingArray[i];
  58874. var percent = value / this.BARGRAPHAMPLITUDE;
  58875. var height = this.DEBUGCANVASSIZE.height * percent;
  58876. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58877. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58878. var hue = i / this.getFrequencyBinCount() * 360;
  58879. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58880. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58881. }
  58882. }
  58883. }
  58884. };
  58885. Analyser.prototype.stopDebugCanvas = function () {
  58886. if (this._debugCanvas) {
  58887. if (this._registerFunc) {
  58888. this._scene.unregisterBeforeRender(this._registerFunc);
  58889. this._registerFunc = null;
  58890. }
  58891. document.body.removeChild(this._debugCanvas);
  58892. this._debugCanvas = null;
  58893. this._debugCanvasContext = null;
  58894. }
  58895. };
  58896. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58897. if (this._audioEngine.canUseWebAudio) {
  58898. inputAudioNode.connect(this._webAudioAnalyser);
  58899. this._webAudioAnalyser.connect(outputAudioNode);
  58900. }
  58901. };
  58902. Analyser.prototype.dispose = function () {
  58903. if (this._audioEngine.canUseWebAudio) {
  58904. this._webAudioAnalyser.disconnect();
  58905. }
  58906. };
  58907. return Analyser;
  58908. }());
  58909. BABYLON.Analyser = Analyser;
  58910. })(BABYLON || (BABYLON = {}));
  58911. //# sourceMappingURL=babylon.analyser.js.map
  58912. "use strict";
  58913. var BABYLON;
  58914. (function (BABYLON) {
  58915. var CubeTexture = /** @class */ (function (_super) {
  58916. __extends(CubeTexture, _super);
  58917. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58918. if (extensions === void 0) { extensions = null; }
  58919. if (noMipmap === void 0) { noMipmap = false; }
  58920. if (files === void 0) { files = null; }
  58921. if (onLoad === void 0) { onLoad = null; }
  58922. if (onError === void 0) { onError = null; }
  58923. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58924. if (prefiltered === void 0) { prefiltered = false; }
  58925. if (forcedExtension === void 0) { forcedExtension = null; }
  58926. var _this = _super.call(this, scene) || this;
  58927. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58928. /**
  58929. * Gets or sets the center of the bounding box associated with the cube texture
  58930. * It must define where the camera used to render the texture was set
  58931. */
  58932. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58933. _this.name = rootUrl;
  58934. _this.url = rootUrl;
  58935. _this._noMipmap = noMipmap;
  58936. _this.hasAlpha = false;
  58937. _this._format = format;
  58938. _this._prefiltered = prefiltered;
  58939. _this.isCube = true;
  58940. _this._textureMatrix = BABYLON.Matrix.Identity();
  58941. if (prefiltered) {
  58942. _this.gammaSpace = false;
  58943. }
  58944. if (!rootUrl && !files) {
  58945. return _this;
  58946. }
  58947. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58948. var lastDot = rootUrl.lastIndexOf(".");
  58949. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58950. var isDDS = (extension === ".dds");
  58951. if (!files) {
  58952. if (!isDDS && !extensions) {
  58953. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58954. }
  58955. files = [];
  58956. if (extensions) {
  58957. for (var index = 0; index < extensions.length; index++) {
  58958. files.push(rootUrl + extensions[index]);
  58959. }
  58960. }
  58961. }
  58962. _this._files = files;
  58963. if (!_this._texture) {
  58964. if (!scene.useDelayedTextureLoading) {
  58965. if (prefiltered) {
  58966. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58967. }
  58968. else {
  58969. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58970. }
  58971. }
  58972. else {
  58973. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58974. }
  58975. }
  58976. else if (onLoad) {
  58977. if (_this._texture.isReady) {
  58978. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58979. }
  58980. else {
  58981. _this._texture.onLoadedObservable.add(onLoad);
  58982. }
  58983. }
  58984. return _this;
  58985. }
  58986. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58987. get: function () {
  58988. return this._boundingBoxSize;
  58989. },
  58990. /**
  58991. * Gets or sets the size of the bounding box associated with the cube texture
  58992. * When defined, the cubemap will switch to local mode
  58993. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58994. * @example https://www.babylonjs-playground.com/#RNASML
  58995. */
  58996. set: function (value) {
  58997. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58998. return;
  58999. }
  59000. this._boundingBoxSize = value;
  59001. var scene = this.getScene();
  59002. if (scene) {
  59003. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59004. }
  59005. },
  59006. enumerable: true,
  59007. configurable: true
  59008. });
  59009. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  59010. var rootUrlKey = "";
  59011. files.forEach(function (url) { return rootUrlKey += url; });
  59012. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  59013. };
  59014. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  59015. if (forcedExtension === void 0) { forcedExtension = null; }
  59016. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  59017. };
  59018. // Methods
  59019. CubeTexture.prototype.delayLoad = function () {
  59020. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59021. return;
  59022. }
  59023. var scene = this.getScene();
  59024. if (!scene) {
  59025. return;
  59026. }
  59027. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59028. this._texture = this._getFromCache(this.url, this._noMipmap);
  59029. if (!this._texture) {
  59030. if (this._prefiltered) {
  59031. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  59032. }
  59033. else {
  59034. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  59035. }
  59036. }
  59037. };
  59038. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  59039. return this._textureMatrix;
  59040. };
  59041. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  59042. this._textureMatrix = value;
  59043. };
  59044. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59045. var texture = BABYLON.SerializationHelper.Parse(function () {
  59046. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  59047. }, parsedTexture, scene);
  59048. // Local Cubemaps
  59049. if (parsedTexture.boundingBoxPosition) {
  59050. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  59051. }
  59052. if (parsedTexture.boundingBoxSize) {
  59053. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  59054. }
  59055. // Animations
  59056. if (parsedTexture.animations) {
  59057. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  59058. var parsedAnimation = parsedTexture.animations[animationIndex];
  59059. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59060. }
  59061. }
  59062. return texture;
  59063. };
  59064. CubeTexture.prototype.clone = function () {
  59065. var _this = this;
  59066. return BABYLON.SerializationHelper.Clone(function () {
  59067. var scene = _this.getScene();
  59068. if (!scene) {
  59069. return _this;
  59070. }
  59071. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  59072. }, this);
  59073. };
  59074. return CubeTexture;
  59075. }(BABYLON.BaseTexture));
  59076. BABYLON.CubeTexture = CubeTexture;
  59077. })(BABYLON || (BABYLON = {}));
  59078. //# sourceMappingURL=babylon.cubeTexture.js.map
  59079. "use strict";
  59080. var BABYLON;
  59081. (function (BABYLON) {
  59082. var RenderTargetTexture = /** @class */ (function (_super) {
  59083. __extends(RenderTargetTexture, _super);
  59084. /**
  59085. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  59086. * or used a shadow, depth texture...
  59087. * @param name The friendly name of the texture
  59088. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  59089. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  59090. * @param generateMipMaps True if mip maps need to be generated after render.
  59091. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  59092. * @param type The type of the buffer in the RTT (int, half float, float...)
  59093. * @param isCube True if a cube texture needs to be created
  59094. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  59095. * @param generateDepthBuffer True to generate a depth buffer
  59096. * @param generateStencilBuffer True to generate a stencil buffer
  59097. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  59098. */
  59099. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  59100. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  59101. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59102. if (isCube === void 0) { isCube = false; }
  59103. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59104. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59105. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  59106. if (isMulti === void 0) { isMulti = false; }
  59107. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59108. _this.isCube = isCube;
  59109. /**
  59110. * Use this list to define the list of mesh you want to render.
  59111. */
  59112. _this.renderList = new Array();
  59113. _this.renderParticles = true;
  59114. _this.renderSprites = false;
  59115. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  59116. _this.ignoreCameraViewport = false;
  59117. // Events
  59118. /**
  59119. * An event triggered when the texture is unbind.
  59120. * @type {BABYLON.Observable}
  59121. */
  59122. _this.onBeforeBindObservable = new BABYLON.Observable();
  59123. /**
  59124. * An event triggered when the texture is unbind.
  59125. * @type {BABYLON.Observable}
  59126. */
  59127. _this.onAfterUnbindObservable = new BABYLON.Observable();
  59128. /**
  59129. * An event triggered before rendering the texture
  59130. * @type {BABYLON.Observable}
  59131. */
  59132. _this.onBeforeRenderObservable = new BABYLON.Observable();
  59133. /**
  59134. * An event triggered after rendering the texture
  59135. * @type {BABYLON.Observable}
  59136. */
  59137. _this.onAfterRenderObservable = new BABYLON.Observable();
  59138. /**
  59139. * An event triggered after the texture clear
  59140. * @type {BABYLON.Observable}
  59141. */
  59142. _this.onClearObservable = new BABYLON.Observable();
  59143. _this._currentRefreshId = -1;
  59144. _this._refreshRate = 1;
  59145. _this._samples = 1;
  59146. /**
  59147. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  59148. * It must define where the camera used to render the texture is set
  59149. */
  59150. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  59151. scene = _this.getScene();
  59152. if (!scene) {
  59153. return _this;
  59154. }
  59155. _this._engine = scene.getEngine();
  59156. _this.name = name;
  59157. _this.isRenderTarget = true;
  59158. _this._initialSizeParameter = size;
  59159. _this._processSizeParameter(size);
  59160. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  59161. });
  59162. _this._generateMipMaps = generateMipMaps ? true : false;
  59163. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  59164. // Rendering groups
  59165. _this._renderingManager = new BABYLON.RenderingManager(scene);
  59166. if (isMulti) {
  59167. return _this;
  59168. }
  59169. _this._renderTargetOptions = {
  59170. generateMipMaps: generateMipMaps,
  59171. type: type,
  59172. samplingMode: samplingMode,
  59173. generateDepthBuffer: generateDepthBuffer,
  59174. generateStencilBuffer: generateStencilBuffer
  59175. };
  59176. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  59177. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59178. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59179. }
  59180. if (isCube) {
  59181. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  59182. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  59183. _this._textureMatrix = BABYLON.Matrix.Identity();
  59184. }
  59185. else {
  59186. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  59187. }
  59188. return _this;
  59189. }
  59190. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  59191. get: function () {
  59192. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  59193. },
  59194. enumerable: true,
  59195. configurable: true
  59196. });
  59197. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  59198. get: function () {
  59199. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  59200. },
  59201. enumerable: true,
  59202. configurable: true
  59203. });
  59204. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  59205. get: function () {
  59206. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  59207. },
  59208. enumerable: true,
  59209. configurable: true
  59210. });
  59211. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  59212. set: function (callback) {
  59213. if (this._onAfterUnbindObserver) {
  59214. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  59215. }
  59216. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  59217. },
  59218. enumerable: true,
  59219. configurable: true
  59220. });
  59221. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  59222. set: function (callback) {
  59223. if (this._onBeforeRenderObserver) {
  59224. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59225. }
  59226. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59227. },
  59228. enumerable: true,
  59229. configurable: true
  59230. });
  59231. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  59232. set: function (callback) {
  59233. if (this._onAfterRenderObserver) {
  59234. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59235. }
  59236. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59237. },
  59238. enumerable: true,
  59239. configurable: true
  59240. });
  59241. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  59242. set: function (callback) {
  59243. if (this._onClearObserver) {
  59244. this.onClearObservable.remove(this._onClearObserver);
  59245. }
  59246. this._onClearObserver = this.onClearObservable.add(callback);
  59247. },
  59248. enumerable: true,
  59249. configurable: true
  59250. });
  59251. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  59252. get: function () {
  59253. return this._renderTargetOptions;
  59254. },
  59255. enumerable: true,
  59256. configurable: true
  59257. });
  59258. RenderTargetTexture.prototype._onRatioRescale = function () {
  59259. if (this._sizeRatio) {
  59260. this.resize(this._initialSizeParameter);
  59261. }
  59262. };
  59263. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  59264. get: function () {
  59265. return this._boundingBoxSize;
  59266. },
  59267. /**
  59268. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  59269. * When defined, the cubemap will switch to local mode
  59270. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59271. * @example https://www.babylonjs-playground.com/#RNASML
  59272. */
  59273. set: function (value) {
  59274. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59275. return;
  59276. }
  59277. this._boundingBoxSize = value;
  59278. var scene = this.getScene();
  59279. if (scene) {
  59280. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59281. }
  59282. },
  59283. enumerable: true,
  59284. configurable: true
  59285. });
  59286. /**
  59287. * Creates a depth stencil texture.
  59288. * This is only available in WebGL 2 or with the depth texture extension available.
  59289. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  59290. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  59291. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  59292. */
  59293. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  59294. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  59295. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  59296. if (generateStencil === void 0) { generateStencil = false; }
  59297. if (!this.getScene()) {
  59298. return;
  59299. }
  59300. var engine = this.getScene().getEngine();
  59301. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  59302. bilinearFiltering: bilinearFiltering,
  59303. comparisonFunction: comparisonFunction,
  59304. generateStencil: generateStencil,
  59305. isCube: this.isCube
  59306. });
  59307. engine.setFrameBufferDepthStencilTexture(this);
  59308. };
  59309. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  59310. if (size.ratio) {
  59311. this._sizeRatio = size.ratio;
  59312. this._size = {
  59313. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  59314. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  59315. };
  59316. }
  59317. else {
  59318. this._size = size;
  59319. }
  59320. };
  59321. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  59322. get: function () {
  59323. return this._samples;
  59324. },
  59325. set: function (value) {
  59326. if (this._samples === value) {
  59327. return;
  59328. }
  59329. var scene = this.getScene();
  59330. if (!scene) {
  59331. return;
  59332. }
  59333. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  59334. },
  59335. enumerable: true,
  59336. configurable: true
  59337. });
  59338. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  59339. this._currentRefreshId = -1;
  59340. };
  59341. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  59342. get: function () {
  59343. return this._refreshRate;
  59344. },
  59345. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59346. set: function (value) {
  59347. this._refreshRate = value;
  59348. this.resetRefreshCounter();
  59349. },
  59350. enumerable: true,
  59351. configurable: true
  59352. });
  59353. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  59354. if (!this._postProcessManager) {
  59355. var scene = this.getScene();
  59356. if (!scene) {
  59357. return;
  59358. }
  59359. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  59360. this._postProcesses = new Array();
  59361. }
  59362. this._postProcesses.push(postProcess);
  59363. this._postProcesses[0].autoClear = false;
  59364. };
  59365. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  59366. if (!this._postProcesses) {
  59367. return;
  59368. }
  59369. if (dispose) {
  59370. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  59371. var postProcess = _a[_i];
  59372. postProcess.dispose();
  59373. }
  59374. }
  59375. this._postProcesses = [];
  59376. };
  59377. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  59378. if (!this._postProcesses) {
  59379. return;
  59380. }
  59381. var index = this._postProcesses.indexOf(postProcess);
  59382. if (index === -1) {
  59383. return;
  59384. }
  59385. this._postProcesses.splice(index, 1);
  59386. if (this._postProcesses.length > 0) {
  59387. this._postProcesses[0].autoClear = false;
  59388. }
  59389. };
  59390. RenderTargetTexture.prototype._shouldRender = function () {
  59391. if (this._currentRefreshId === -1) {
  59392. this._currentRefreshId = 1;
  59393. return true;
  59394. }
  59395. if (this.refreshRate === this._currentRefreshId) {
  59396. this._currentRefreshId = 1;
  59397. return true;
  59398. }
  59399. this._currentRefreshId++;
  59400. return false;
  59401. };
  59402. RenderTargetTexture.prototype.getRenderSize = function () {
  59403. if (this._size.width) {
  59404. return this._size.width;
  59405. }
  59406. return this._size;
  59407. };
  59408. RenderTargetTexture.prototype.getRenderWidth = function () {
  59409. if (this._size.width) {
  59410. return this._size.width;
  59411. }
  59412. return this._size;
  59413. };
  59414. RenderTargetTexture.prototype.getRenderHeight = function () {
  59415. if (this._size.width) {
  59416. return this._size.height;
  59417. }
  59418. return this._size;
  59419. };
  59420. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59421. get: function () {
  59422. return true;
  59423. },
  59424. enumerable: true,
  59425. configurable: true
  59426. });
  59427. RenderTargetTexture.prototype.scale = function (ratio) {
  59428. var newSize = this.getRenderSize() * ratio;
  59429. this.resize(newSize);
  59430. };
  59431. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59432. if (this.isCube) {
  59433. return this._textureMatrix;
  59434. }
  59435. return _super.prototype.getReflectionTextureMatrix.call(this);
  59436. };
  59437. RenderTargetTexture.prototype.resize = function (size) {
  59438. this.releaseInternalTexture();
  59439. var scene = this.getScene();
  59440. if (!scene) {
  59441. return;
  59442. }
  59443. this._processSizeParameter(size);
  59444. if (this.isCube) {
  59445. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59446. }
  59447. else {
  59448. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59449. }
  59450. };
  59451. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59452. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59453. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59454. var scene = this.getScene();
  59455. if (!scene) {
  59456. return;
  59457. }
  59458. var engine = scene.getEngine();
  59459. if (this.useCameraPostProcesses !== undefined) {
  59460. useCameraPostProcess = this.useCameraPostProcesses;
  59461. }
  59462. if (this._waitingRenderList) {
  59463. this.renderList = [];
  59464. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59465. var id = this._waitingRenderList[index];
  59466. var mesh_1 = scene.getMeshByID(id);
  59467. if (mesh_1) {
  59468. this.renderList.push(mesh_1);
  59469. }
  59470. }
  59471. delete this._waitingRenderList;
  59472. }
  59473. // Is predicate defined?
  59474. if (this.renderListPredicate) {
  59475. if (this.renderList) {
  59476. this.renderList.splice(0); // Clear previous renderList
  59477. }
  59478. else {
  59479. this.renderList = [];
  59480. }
  59481. var scene = this.getScene();
  59482. if (!scene) {
  59483. return;
  59484. }
  59485. var sceneMeshes = scene.meshes;
  59486. for (var index = 0; index < sceneMeshes.length; index++) {
  59487. var mesh = sceneMeshes[index];
  59488. if (this.renderListPredicate(mesh)) {
  59489. this.renderList.push(mesh);
  59490. }
  59491. }
  59492. }
  59493. this.onBeforeBindObservable.notifyObservers(this);
  59494. // Set custom projection.
  59495. // Needs to be before binding to prevent changing the aspect ratio.
  59496. var camera;
  59497. if (this.activeCamera) {
  59498. camera = this.activeCamera;
  59499. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59500. if (this.activeCamera !== scene.activeCamera) {
  59501. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59502. }
  59503. }
  59504. else {
  59505. camera = scene.activeCamera;
  59506. if (camera) {
  59507. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59508. }
  59509. }
  59510. // Prepare renderingManager
  59511. this._renderingManager.reset();
  59512. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59513. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59514. var sceneRenderId = scene.getRenderId();
  59515. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59516. var mesh = currentRenderList[meshIndex];
  59517. if (mesh) {
  59518. if (!mesh.isReady(this.refreshRate === 0)) {
  59519. this.resetRefreshCounter();
  59520. continue;
  59521. }
  59522. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59523. var isMasked = void 0;
  59524. if (!this.renderList && camera) {
  59525. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59526. }
  59527. else {
  59528. isMasked = false;
  59529. }
  59530. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59531. mesh._activate(sceneRenderId);
  59532. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59533. var subMesh = mesh.subMeshes[subIndex];
  59534. scene._activeIndices.addCount(subMesh.indexCount, false);
  59535. this._renderingManager.dispatch(subMesh, mesh);
  59536. }
  59537. }
  59538. }
  59539. }
  59540. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59541. var particleSystem = scene.particleSystems[particleIndex];
  59542. var emitter = particleSystem.emitter;
  59543. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59544. continue;
  59545. }
  59546. if (currentRenderList.indexOf(emitter) >= 0) {
  59547. this._renderingManager.dispatchParticles(particleSystem);
  59548. }
  59549. }
  59550. if (this.isCube) {
  59551. for (var face = 0; face < 6; face++) {
  59552. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59553. scene.incrementRenderId();
  59554. scene.resetCachedMaterial();
  59555. }
  59556. }
  59557. else {
  59558. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59559. }
  59560. this.onAfterUnbindObservable.notifyObservers(this);
  59561. if (scene.activeCamera) {
  59562. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59563. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59564. }
  59565. engine.setViewport(scene.activeCamera.viewport);
  59566. }
  59567. scene.resetCachedMaterial();
  59568. };
  59569. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59570. var minimum = 128;
  59571. var x = renderDimension * scale;
  59572. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59573. // Ensure we don't exceed the render dimension (while staying POT)
  59574. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59575. };
  59576. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59577. var _this = this;
  59578. if (!this._texture) {
  59579. return;
  59580. }
  59581. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59582. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59583. });
  59584. };
  59585. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59586. var scene = this.getScene();
  59587. if (!scene) {
  59588. return;
  59589. }
  59590. var engine = scene.getEngine();
  59591. if (!this._texture) {
  59592. return;
  59593. }
  59594. // Bind
  59595. if (this._postProcessManager) {
  59596. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59597. }
  59598. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59599. if (this._texture) {
  59600. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59601. }
  59602. }
  59603. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59604. // Clear
  59605. if (this.onClearObservable.hasObservers()) {
  59606. this.onClearObservable.notifyObservers(engine);
  59607. }
  59608. else {
  59609. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59610. }
  59611. if (!this._doNotChangeAspectRatio) {
  59612. scene.updateTransformMatrix(true);
  59613. }
  59614. // Render
  59615. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59616. if (this._postProcessManager) {
  59617. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59618. }
  59619. else if (useCameraPostProcess) {
  59620. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59621. }
  59622. if (!this._doNotChangeAspectRatio) {
  59623. scene.updateTransformMatrix(true);
  59624. }
  59625. // Dump ?
  59626. if (dumpForDebug) {
  59627. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59628. }
  59629. // Unbind
  59630. if (!this.isCube || faceIndex === 5) {
  59631. if (this.isCube) {
  59632. if (faceIndex === 5) {
  59633. engine.generateMipMapsForCubemap(this._texture);
  59634. }
  59635. }
  59636. this.unbindFrameBuffer(engine, faceIndex);
  59637. }
  59638. else {
  59639. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59640. }
  59641. };
  59642. /**
  59643. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59644. * This allowed control for front to back rendering or reversly depending of the special needs.
  59645. *
  59646. * @param renderingGroupId The rendering group id corresponding to its index
  59647. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59648. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59649. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59650. */
  59651. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59652. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59653. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59654. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59655. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59656. };
  59657. /**
  59658. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59659. *
  59660. * @param renderingGroupId The rendering group id corresponding to its index
  59661. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59662. */
  59663. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59664. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59665. };
  59666. RenderTargetTexture.prototype.clone = function () {
  59667. var textureSize = this.getSize();
  59668. 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);
  59669. // Base texture
  59670. newTexture.hasAlpha = this.hasAlpha;
  59671. newTexture.level = this.level;
  59672. // RenderTarget Texture
  59673. newTexture.coordinatesMode = this.coordinatesMode;
  59674. if (this.renderList) {
  59675. newTexture.renderList = this.renderList.slice(0);
  59676. }
  59677. return newTexture;
  59678. };
  59679. RenderTargetTexture.prototype.serialize = function () {
  59680. if (!this.name) {
  59681. return null;
  59682. }
  59683. var serializationObject = _super.prototype.serialize.call(this);
  59684. serializationObject.renderTargetSize = this.getRenderSize();
  59685. serializationObject.renderList = [];
  59686. if (this.renderList) {
  59687. for (var index = 0; index < this.renderList.length; index++) {
  59688. serializationObject.renderList.push(this.renderList[index].id);
  59689. }
  59690. }
  59691. return serializationObject;
  59692. };
  59693. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59694. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59695. var objBuffer = this.getInternalTexture();
  59696. var scene = this.getScene();
  59697. if (objBuffer && scene) {
  59698. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59699. }
  59700. };
  59701. RenderTargetTexture.prototype.dispose = function () {
  59702. if (this._postProcessManager) {
  59703. this._postProcessManager.dispose();
  59704. this._postProcessManager = null;
  59705. }
  59706. this.clearPostProcesses(true);
  59707. if (this._resizeObserver) {
  59708. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59709. this._resizeObserver = null;
  59710. }
  59711. this.renderList = null;
  59712. // Remove from custom render targets
  59713. var scene = this.getScene();
  59714. if (!scene) {
  59715. return;
  59716. }
  59717. var index = scene.customRenderTargets.indexOf(this);
  59718. if (index >= 0) {
  59719. scene.customRenderTargets.splice(index, 1);
  59720. }
  59721. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59722. var camera = _a[_i];
  59723. index = camera.customRenderTargets.indexOf(this);
  59724. if (index >= 0) {
  59725. camera.customRenderTargets.splice(index, 1);
  59726. }
  59727. }
  59728. _super.prototype.dispose.call(this);
  59729. };
  59730. RenderTargetTexture.prototype._rebuild = function () {
  59731. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59732. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59733. }
  59734. if (this._postProcessManager) {
  59735. this._postProcessManager._rebuild();
  59736. }
  59737. };
  59738. /**
  59739. * Clear the info related to rendering groups preventing retention point in material dispose.
  59740. */
  59741. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59742. if (this._renderingManager) {
  59743. this._renderingManager.freeRenderingGroups();
  59744. }
  59745. };
  59746. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59747. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59748. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59749. return RenderTargetTexture;
  59750. }(BABYLON.Texture));
  59751. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59752. })(BABYLON || (BABYLON = {}));
  59753. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59754. "use strict";
  59755. var BABYLON;
  59756. (function (BABYLON) {
  59757. ;
  59758. var MultiRenderTarget = /** @class */ (function (_super) {
  59759. __extends(MultiRenderTarget, _super);
  59760. function MultiRenderTarget(name, size, count, scene, options) {
  59761. var _this = this;
  59762. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59763. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59764. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59765. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59766. _this._engine = scene.getEngine();
  59767. if (!_this.isSupported) {
  59768. _this.dispose();
  59769. return;
  59770. }
  59771. var types = [];
  59772. var samplingModes = [];
  59773. for (var i = 0; i < count; i++) {
  59774. if (options && options.types && options.types[i] !== undefined) {
  59775. types.push(options.types[i]);
  59776. }
  59777. else {
  59778. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59779. }
  59780. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59781. samplingModes.push(options.samplingModes[i]);
  59782. }
  59783. else {
  59784. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59785. }
  59786. }
  59787. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59788. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59789. _this._size = size;
  59790. _this._multiRenderTargetOptions = {
  59791. samplingModes: samplingModes,
  59792. generateMipMaps: generateMipMaps,
  59793. generateDepthBuffer: generateDepthBuffer,
  59794. generateStencilBuffer: generateStencilBuffer,
  59795. generateDepthTexture: generateDepthTexture,
  59796. types: types,
  59797. textureCount: count
  59798. };
  59799. _this._createInternalTextures();
  59800. _this._createTextures();
  59801. return _this;
  59802. }
  59803. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59804. get: function () {
  59805. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59806. },
  59807. enumerable: true,
  59808. configurable: true
  59809. });
  59810. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59811. get: function () {
  59812. return this._textures;
  59813. },
  59814. enumerable: true,
  59815. configurable: true
  59816. });
  59817. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59818. get: function () {
  59819. return this._textures[this._textures.length - 1];
  59820. },
  59821. enumerable: true,
  59822. configurable: true
  59823. });
  59824. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59825. set: function (wrap) {
  59826. if (this._textures) {
  59827. for (var i = 0; i < this._textures.length; i++) {
  59828. this._textures[i].wrapU = wrap;
  59829. }
  59830. }
  59831. },
  59832. enumerable: true,
  59833. configurable: true
  59834. });
  59835. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59836. set: function (wrap) {
  59837. if (this._textures) {
  59838. for (var i = 0; i < this._textures.length; i++) {
  59839. this._textures[i].wrapV = wrap;
  59840. }
  59841. }
  59842. },
  59843. enumerable: true,
  59844. configurable: true
  59845. });
  59846. MultiRenderTarget.prototype._rebuild = function () {
  59847. this.releaseInternalTextures();
  59848. this._createInternalTextures();
  59849. for (var i = 0; i < this._internalTextures.length; i++) {
  59850. var texture = this._textures[i];
  59851. texture._texture = this._internalTextures[i];
  59852. }
  59853. // Keeps references to frame buffer and stencil/depth buffer
  59854. this._texture = this._internalTextures[0];
  59855. };
  59856. MultiRenderTarget.prototype._createInternalTextures = function () {
  59857. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59858. };
  59859. MultiRenderTarget.prototype._createTextures = function () {
  59860. this._textures = [];
  59861. for (var i = 0; i < this._internalTextures.length; i++) {
  59862. var texture = new BABYLON.Texture(null, this.getScene());
  59863. texture._texture = this._internalTextures[i];
  59864. this._textures.push(texture);
  59865. }
  59866. // Keeps references to frame buffer and stencil/depth buffer
  59867. this._texture = this._internalTextures[0];
  59868. };
  59869. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59870. get: function () {
  59871. return this._samples;
  59872. },
  59873. set: function (value) {
  59874. if (this._samples === value) {
  59875. return;
  59876. }
  59877. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59878. },
  59879. enumerable: true,
  59880. configurable: true
  59881. });
  59882. MultiRenderTarget.prototype.resize = function (size) {
  59883. this.releaseInternalTextures();
  59884. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59885. this._createInternalTextures();
  59886. };
  59887. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59888. var _this = this;
  59889. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59890. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59891. });
  59892. };
  59893. MultiRenderTarget.prototype.dispose = function () {
  59894. this.releaseInternalTextures();
  59895. _super.prototype.dispose.call(this);
  59896. };
  59897. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59898. if (!this._internalTextures) {
  59899. return;
  59900. }
  59901. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59902. if (this._internalTextures[i] !== undefined) {
  59903. this._internalTextures[i].dispose();
  59904. this._internalTextures.splice(i, 1);
  59905. }
  59906. }
  59907. };
  59908. return MultiRenderTarget;
  59909. }(BABYLON.RenderTargetTexture));
  59910. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59911. })(BABYLON || (BABYLON = {}));
  59912. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59913. "use strict";
  59914. var BABYLON;
  59915. (function (BABYLON) {
  59916. var MirrorTexture = /** @class */ (function (_super) {
  59917. __extends(MirrorTexture, _super);
  59918. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59919. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59920. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59921. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59922. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59923. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59924. _this._transformMatrix = BABYLON.Matrix.Zero();
  59925. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59926. _this._adaptiveBlurKernel = 0;
  59927. _this._blurKernelX = 0;
  59928. _this._blurKernelY = 0;
  59929. _this._blurRatio = 1.0;
  59930. _this.ignoreCameraViewport = true;
  59931. _this.onBeforeRenderObservable.add(function () {
  59932. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59933. _this._savedViewMatrix = scene.getViewMatrix();
  59934. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59935. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59936. scene.clipPlane = _this.mirrorPlane;
  59937. scene.getEngine().cullBackFaces = false;
  59938. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59939. });
  59940. _this.onAfterRenderObservable.add(function () {
  59941. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59942. scene.getEngine().cullBackFaces = true;
  59943. scene._mirroredCameraPosition = null;
  59944. delete scene.clipPlane;
  59945. });
  59946. return _this;
  59947. }
  59948. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59949. get: function () {
  59950. return this._blurRatio;
  59951. },
  59952. set: function (value) {
  59953. if (this._blurRatio === value) {
  59954. return;
  59955. }
  59956. this._blurRatio = value;
  59957. this._preparePostProcesses();
  59958. },
  59959. enumerable: true,
  59960. configurable: true
  59961. });
  59962. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59963. set: function (value) {
  59964. this._adaptiveBlurKernel = value;
  59965. this._autoComputeBlurKernel();
  59966. },
  59967. enumerable: true,
  59968. configurable: true
  59969. });
  59970. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59971. set: function (value) {
  59972. this.blurKernelX = value;
  59973. this.blurKernelY = value;
  59974. },
  59975. enumerable: true,
  59976. configurable: true
  59977. });
  59978. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59979. get: function () {
  59980. return this._blurKernelX;
  59981. },
  59982. set: function (value) {
  59983. if (this._blurKernelX === value) {
  59984. return;
  59985. }
  59986. this._blurKernelX = value;
  59987. this._preparePostProcesses();
  59988. },
  59989. enumerable: true,
  59990. configurable: true
  59991. });
  59992. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59993. get: function () {
  59994. return this._blurKernelY;
  59995. },
  59996. set: function (value) {
  59997. if (this._blurKernelY === value) {
  59998. return;
  59999. }
  60000. this._blurKernelY = value;
  60001. this._preparePostProcesses();
  60002. },
  60003. enumerable: true,
  60004. configurable: true
  60005. });
  60006. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  60007. var engine = this.getScene().getEngine();
  60008. var dw = this.getRenderWidth() / engine.getRenderWidth();
  60009. var dh = this.getRenderHeight() / engine.getRenderHeight();
  60010. this.blurKernelX = this._adaptiveBlurKernel * dw;
  60011. this.blurKernelY = this._adaptiveBlurKernel * dh;
  60012. };
  60013. MirrorTexture.prototype._onRatioRescale = function () {
  60014. if (this._sizeRatio) {
  60015. this.resize(this._initialSizeParameter);
  60016. if (!this._adaptiveBlurKernel) {
  60017. this._preparePostProcesses();
  60018. }
  60019. }
  60020. if (this._adaptiveBlurKernel) {
  60021. this._autoComputeBlurKernel();
  60022. }
  60023. };
  60024. MirrorTexture.prototype._preparePostProcesses = function () {
  60025. this.clearPostProcesses(true);
  60026. if (this._blurKernelX && this._blurKernelY) {
  60027. var engine = this.getScene().getEngine();
  60028. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60029. 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);
  60030. this._blurX.autoClear = false;
  60031. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  60032. this._blurX.inputTexture = this._texture;
  60033. }
  60034. else {
  60035. this._blurX.alwaysForcePOT = true;
  60036. }
  60037. 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);
  60038. this._blurY.autoClear = false;
  60039. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  60040. this.addPostProcess(this._blurX);
  60041. this.addPostProcess(this._blurY);
  60042. }
  60043. else {
  60044. if (this._blurY) {
  60045. this.removePostProcess(this._blurY);
  60046. this._blurY.dispose();
  60047. this._blurY = null;
  60048. }
  60049. if (this._blurX) {
  60050. this.removePostProcess(this._blurX);
  60051. this._blurX.dispose();
  60052. this._blurX = null;
  60053. }
  60054. }
  60055. };
  60056. MirrorTexture.prototype.clone = function () {
  60057. var scene = this.getScene();
  60058. if (!scene) {
  60059. return this;
  60060. }
  60061. var textureSize = this.getSize();
  60062. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  60063. // Base texture
  60064. newTexture.hasAlpha = this.hasAlpha;
  60065. newTexture.level = this.level;
  60066. // Mirror Texture
  60067. newTexture.mirrorPlane = this.mirrorPlane.clone();
  60068. if (this.renderList) {
  60069. newTexture.renderList = this.renderList.slice(0);
  60070. }
  60071. return newTexture;
  60072. };
  60073. MirrorTexture.prototype.serialize = function () {
  60074. if (!this.name) {
  60075. return null;
  60076. }
  60077. var serializationObject = _super.prototype.serialize.call(this);
  60078. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  60079. return serializationObject;
  60080. };
  60081. return MirrorTexture;
  60082. }(BABYLON.RenderTargetTexture));
  60083. BABYLON.MirrorTexture = MirrorTexture;
  60084. })(BABYLON || (BABYLON = {}));
  60085. //# sourceMappingURL=babylon.mirrorTexture.js.map
  60086. "use strict";
  60087. var BABYLON;
  60088. (function (BABYLON) {
  60089. /**
  60090. * Creates a refraction texture used by refraction channel of the standard material.
  60091. * @param name the texture name
  60092. * @param size size of the underlying texture
  60093. * @param scene root scene
  60094. */
  60095. var RefractionTexture = /** @class */ (function (_super) {
  60096. __extends(RefractionTexture, _super);
  60097. function RefractionTexture(name, size, scene, generateMipMaps) {
  60098. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  60099. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  60100. _this.depth = 2.0;
  60101. _this.onBeforeRenderObservable.add(function () {
  60102. scene.clipPlane = _this.refractionPlane;
  60103. });
  60104. _this.onAfterRenderObservable.add(function () {
  60105. delete scene.clipPlane;
  60106. });
  60107. return _this;
  60108. }
  60109. RefractionTexture.prototype.clone = function () {
  60110. var scene = this.getScene();
  60111. if (!scene) {
  60112. return this;
  60113. }
  60114. var textureSize = this.getSize();
  60115. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  60116. // Base texture
  60117. newTexture.hasAlpha = this.hasAlpha;
  60118. newTexture.level = this.level;
  60119. // Refraction Texture
  60120. newTexture.refractionPlane = this.refractionPlane.clone();
  60121. if (this.renderList) {
  60122. newTexture.renderList = this.renderList.slice(0);
  60123. }
  60124. newTexture.depth = this.depth;
  60125. return newTexture;
  60126. };
  60127. RefractionTexture.prototype.serialize = function () {
  60128. if (!this.name) {
  60129. return null;
  60130. }
  60131. var serializationObject = _super.prototype.serialize.call(this);
  60132. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  60133. serializationObject.depth = this.depth;
  60134. return serializationObject;
  60135. };
  60136. return RefractionTexture;
  60137. }(BABYLON.RenderTargetTexture));
  60138. BABYLON.RefractionTexture = RefractionTexture;
  60139. })(BABYLON || (BABYLON = {}));
  60140. //# sourceMappingURL=babylon.refractionTexture.js.map
  60141. "use strict";
  60142. var BABYLON;
  60143. (function (BABYLON) {
  60144. /**
  60145. * A class extending {BABYLON.Texture} allowing drawing on a texture
  60146. * @see http://doc.babylonjs.com/how_to/dynamictexture
  60147. */
  60148. var DynamicTexture = /** @class */ (function (_super) {
  60149. __extends(DynamicTexture, _super);
  60150. /**
  60151. * Creates a {BABYLON.DynamicTexture}
  60152. * @param name defines the name of the texture
  60153. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  60154. * @param scene defines the scene where you want the texture
  60155. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  60156. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  60157. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  60158. */
  60159. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  60160. if (scene === void 0) { scene = null; }
  60161. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60162. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  60163. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  60164. _this.name = name;
  60165. _this._engine = _this.getScene().getEngine();
  60166. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60167. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60168. _this._generateMipMaps = generateMipMaps;
  60169. if (options.getContext) {
  60170. _this._canvas = options;
  60171. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60172. }
  60173. else {
  60174. _this._canvas = document.createElement("canvas");
  60175. if (options.width) {
  60176. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60177. }
  60178. else {
  60179. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  60180. }
  60181. }
  60182. var textureSize = _this.getSize();
  60183. _this._canvas.width = textureSize.width;
  60184. _this._canvas.height = textureSize.height;
  60185. _this._context = _this._canvas.getContext("2d");
  60186. return _this;
  60187. }
  60188. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  60189. /**
  60190. * Gets the current state of canRescale
  60191. */
  60192. get: function () {
  60193. return true;
  60194. },
  60195. enumerable: true,
  60196. configurable: true
  60197. });
  60198. DynamicTexture.prototype._recreate = function (textureSize) {
  60199. this._canvas.width = textureSize.width;
  60200. this._canvas.height = textureSize.height;
  60201. this.releaseInternalTexture();
  60202. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  60203. };
  60204. /**
  60205. * Scales the texture
  60206. * @param ratio the scale factor to apply to both width and height
  60207. */
  60208. DynamicTexture.prototype.scale = function (ratio) {
  60209. var textureSize = this.getSize();
  60210. textureSize.width *= ratio;
  60211. textureSize.height *= ratio;
  60212. this._recreate(textureSize);
  60213. };
  60214. /**
  60215. * Resizes the texture
  60216. * @param width the new width
  60217. * @param height the new height
  60218. */
  60219. DynamicTexture.prototype.scaleTo = function (width, height) {
  60220. var textureSize = this.getSize();
  60221. textureSize.width = width;
  60222. textureSize.height = height;
  60223. this._recreate(textureSize);
  60224. };
  60225. /**
  60226. * Gets the context of the canvas used by the texture
  60227. * @returns the canvas context of the dynamic texture
  60228. */
  60229. DynamicTexture.prototype.getContext = function () {
  60230. return this._context;
  60231. };
  60232. /**
  60233. * Clears the texture
  60234. */
  60235. DynamicTexture.prototype.clear = function () {
  60236. var size = this.getSize();
  60237. this._context.fillRect(0, 0, size.width, size.height);
  60238. };
  60239. /**
  60240. * Updates the texture
  60241. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60242. */
  60243. DynamicTexture.prototype.update = function (invertY) {
  60244. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  60245. };
  60246. /**
  60247. * Draws text onto the texture
  60248. * @param text defines the text to be drawn
  60249. * @param x defines the placement of the text from the left
  60250. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  60251. * @param font defines the font to be used with font-style, font-size, font-name
  60252. * @param color defines the color used for the text
  60253. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  60254. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60255. * @param update defines whether texture is immediately update (default is true)
  60256. */
  60257. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  60258. if (update === void 0) { update = true; }
  60259. var size = this.getSize();
  60260. if (clearColor) {
  60261. this._context.fillStyle = clearColor;
  60262. this._context.fillRect(0, 0, size.width, size.height);
  60263. }
  60264. this._context.font = font;
  60265. if (x === null || x === undefined) {
  60266. var textSize = this._context.measureText(text);
  60267. x = (size.width - textSize.width) / 2;
  60268. }
  60269. if (y === null || y === undefined) {
  60270. var fontSize = parseInt((font.replace(/\D/g, '')));
  60271. ;
  60272. y = (size.height / 2) + (fontSize / 3.65);
  60273. }
  60274. this._context.fillStyle = color;
  60275. this._context.fillText(text, x, y);
  60276. if (update) {
  60277. this.update(invertY);
  60278. }
  60279. };
  60280. /**
  60281. * Clones the texture
  60282. * @returns the clone of the texture.
  60283. */
  60284. DynamicTexture.prototype.clone = function () {
  60285. var scene = this.getScene();
  60286. if (!scene) {
  60287. return this;
  60288. }
  60289. var textureSize = this.getSize();
  60290. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  60291. // Base texture
  60292. newTexture.hasAlpha = this.hasAlpha;
  60293. newTexture.level = this.level;
  60294. // Dynamic Texture
  60295. newTexture.wrapU = this.wrapU;
  60296. newTexture.wrapV = this.wrapV;
  60297. return newTexture;
  60298. };
  60299. /** @ignore */
  60300. DynamicTexture.prototype._rebuild = function () {
  60301. this.update();
  60302. };
  60303. return DynamicTexture;
  60304. }(BABYLON.Texture));
  60305. BABYLON.DynamicTexture = DynamicTexture;
  60306. })(BABYLON || (BABYLON = {}));
  60307. //# sourceMappingURL=babylon.dynamicTexture.js.map
  60308. "use strict";
  60309. var BABYLON;
  60310. (function (BABYLON) {
  60311. var VideoTexture = /** @class */ (function (_super) {
  60312. __extends(VideoTexture, _super);
  60313. /**
  60314. * Creates a video texture.
  60315. * Sample : https://doc.babylonjs.com/how_to/video_texture
  60316. * @param {string | null} name optional name, will detect from video source, if not defined
  60317. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  60318. * @param {BABYLON.Scene} scene is obviously the current scene.
  60319. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  60320. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  60321. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  60322. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  60323. */
  60324. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  60325. if (generateMipMaps === void 0) { generateMipMaps = false; }
  60326. if (invertY === void 0) { invertY = false; }
  60327. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60328. if (settings === void 0) { settings = {
  60329. autoPlay: true,
  60330. loop: true,
  60331. autoUpdateTexture: true,
  60332. }; }
  60333. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60334. _this._createInternalTexture = function () {
  60335. if (_this._texture != null) {
  60336. return;
  60337. }
  60338. if (!_this._engine.needPOTTextures ||
  60339. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  60340. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60341. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60342. }
  60343. else {
  60344. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60345. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60346. _this._generateMipMaps = false;
  60347. }
  60348. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  60349. _this._texture.isReady = true;
  60350. _this._updateInternalTexture();
  60351. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  60352. _this.onLoadObservable.notifyObservers(_this);
  60353. }
  60354. };
  60355. _this.reset = function () {
  60356. if (_this._texture == null) {
  60357. return;
  60358. }
  60359. _this._texture.dispose();
  60360. _this._texture = null;
  60361. };
  60362. _this._updateInternalTexture = function (e) {
  60363. if (_this._texture == null || !_this._texture.isReady) {
  60364. return;
  60365. }
  60366. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  60367. return;
  60368. }
  60369. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  60370. };
  60371. _this._engine = _this.getScene().getEngine();
  60372. _this._generateMipMaps = generateMipMaps;
  60373. _this._samplingMode = samplingMode;
  60374. _this.autoUpdateTexture = settings.autoUpdateTexture;
  60375. _this.name = name || _this._getName(src);
  60376. _this.video = _this._getVideo(src);
  60377. if (settings.autoPlay !== undefined) {
  60378. _this.video.autoplay = settings.autoPlay;
  60379. }
  60380. if (settings.loop !== undefined) {
  60381. _this.video.loop = settings.loop;
  60382. }
  60383. _this.video.addEventListener("canplay", _this._createInternalTexture);
  60384. _this.video.addEventListener("paused", _this._updateInternalTexture);
  60385. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  60386. _this.video.addEventListener("emptied", _this.reset);
  60387. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  60388. _this._createInternalTexture();
  60389. }
  60390. return _this;
  60391. }
  60392. VideoTexture.prototype._getName = function (src) {
  60393. if (src instanceof HTMLVideoElement) {
  60394. return src.currentSrc;
  60395. }
  60396. if (typeof src === "object") {
  60397. return src.toString();
  60398. }
  60399. return src;
  60400. };
  60401. ;
  60402. VideoTexture.prototype._getVideo = function (src) {
  60403. if (src instanceof HTMLVideoElement) {
  60404. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  60405. return src;
  60406. }
  60407. var video = document.createElement("video");
  60408. if (typeof src === "string") {
  60409. BABYLON.Tools.SetCorsBehavior(src, video);
  60410. video.src = src;
  60411. }
  60412. else {
  60413. BABYLON.Tools.SetCorsBehavior(src[0], video);
  60414. src.forEach(function (url) {
  60415. var source = document.createElement("source");
  60416. source.src = url;
  60417. video.appendChild(source);
  60418. });
  60419. }
  60420. return video;
  60421. };
  60422. ;
  60423. /**
  60424. * Internal method to initiate `update`.
  60425. */
  60426. VideoTexture.prototype._rebuild = function () {
  60427. this.update();
  60428. };
  60429. /**
  60430. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  60431. */
  60432. VideoTexture.prototype.update = function () {
  60433. if (!this.autoUpdateTexture) {
  60434. // Expecting user to call `updateTexture` manually
  60435. return;
  60436. }
  60437. this.updateTexture(true);
  60438. };
  60439. /**
  60440. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  60441. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  60442. */
  60443. VideoTexture.prototype.updateTexture = function (isVisible) {
  60444. if (!isVisible) {
  60445. return;
  60446. }
  60447. if (this.video.paused) {
  60448. return;
  60449. }
  60450. this._updateInternalTexture();
  60451. };
  60452. /**
  60453. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  60454. * @param url New url.
  60455. */
  60456. VideoTexture.prototype.updateURL = function (url) {
  60457. this.video.src = url;
  60458. };
  60459. VideoTexture.prototype.dispose = function () {
  60460. _super.prototype.dispose.call(this);
  60461. this.video.removeEventListener("canplay", this._createInternalTexture);
  60462. this.video.removeEventListener("paused", this._updateInternalTexture);
  60463. this.video.removeEventListener("seeked", this._updateInternalTexture);
  60464. this.video.removeEventListener("emptied", this.reset);
  60465. this.video.pause();
  60466. };
  60467. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  60468. var video = document.createElement("video");
  60469. var constraintsDeviceId;
  60470. if (constraints && constraints.deviceId) {
  60471. constraintsDeviceId = {
  60472. exact: constraints.deviceId,
  60473. };
  60474. }
  60475. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60476. if (navigator.mediaDevices) {
  60477. navigator.mediaDevices.getUserMedia({ video: constraints })
  60478. .then(function (stream) {
  60479. if (video.mozSrcObject !== undefined) {
  60480. // hack for Firefox < 19
  60481. video.mozSrcObject = stream;
  60482. }
  60483. else {
  60484. video.srcObject = stream;
  60485. }
  60486. var onPlaying = function () {
  60487. if (onReady) {
  60488. onReady(new VideoTexture("video", video, scene, true, true));
  60489. }
  60490. video.removeEventListener("playing", onPlaying);
  60491. };
  60492. video.addEventListener("playing", onPlaying);
  60493. video.play();
  60494. })
  60495. .catch(function (err) {
  60496. BABYLON.Tools.Error(err.name);
  60497. });
  60498. }
  60499. else {
  60500. navigator.getUserMedia =
  60501. navigator.getUserMedia ||
  60502. navigator.webkitGetUserMedia ||
  60503. navigator.mozGetUserMedia ||
  60504. navigator.msGetUserMedia;
  60505. if (navigator.getUserMedia) {
  60506. navigator.getUserMedia({
  60507. video: {
  60508. deviceId: constraintsDeviceId,
  60509. width: {
  60510. min: (constraints && constraints.minWidth) || 256,
  60511. max: (constraints && constraints.maxWidth) || 640,
  60512. },
  60513. height: {
  60514. min: (constraints && constraints.minHeight) || 256,
  60515. max: (constraints && constraints.maxHeight) || 480,
  60516. },
  60517. },
  60518. }, function (stream) {
  60519. if (video.mozSrcObject !== undefined) {
  60520. // hack for Firefox < 19
  60521. video.mozSrcObject = stream;
  60522. }
  60523. else {
  60524. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60525. }
  60526. video.play();
  60527. if (onReady) {
  60528. onReady(new VideoTexture("video", video, scene, true, true));
  60529. }
  60530. }, function (e) {
  60531. BABYLON.Tools.Error(e.name);
  60532. });
  60533. }
  60534. }
  60535. };
  60536. return VideoTexture;
  60537. }(BABYLON.Texture));
  60538. BABYLON.VideoTexture = VideoTexture;
  60539. })(BABYLON || (BABYLON = {}));
  60540. //# sourceMappingURL=babylon.videoTexture.js.map
  60541. "use strict";
  60542. var BABYLON;
  60543. (function (BABYLON) {
  60544. var RawTexture = /** @class */ (function (_super) {
  60545. __extends(RawTexture, _super);
  60546. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60547. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60548. if (invertY === void 0) { invertY = false; }
  60549. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60550. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60551. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60552. _this.format = format;
  60553. _this._engine = scene.getEngine();
  60554. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60555. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60556. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60557. return _this;
  60558. }
  60559. RawTexture.prototype.update = function (data) {
  60560. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60561. };
  60562. // Statics
  60563. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60564. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60565. if (invertY === void 0) { invertY = false; }
  60566. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60567. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60568. };
  60569. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60570. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60571. if (invertY === void 0) { invertY = false; }
  60572. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60573. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60574. };
  60575. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60576. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60577. if (invertY === void 0) { invertY = false; }
  60578. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60579. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60580. };
  60581. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60582. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60583. if (invertY === void 0) { invertY = false; }
  60584. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60585. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60586. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60587. };
  60588. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60589. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60590. if (invertY === void 0) { invertY = false; }
  60591. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60592. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60593. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60594. };
  60595. return RawTexture;
  60596. }(BABYLON.Texture));
  60597. BABYLON.RawTexture = RawTexture;
  60598. })(BABYLON || (BABYLON = {}));
  60599. //# sourceMappingURL=babylon.rawTexture.js.map
  60600. "use strict";
  60601. var BABYLON;
  60602. (function (BABYLON) {
  60603. /**
  60604. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60605. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60606. */
  60607. var PostProcess = /** @class */ (function () {
  60608. /**
  60609. * Creates a new instance of @see PostProcess
  60610. * @param name The name of the PostProcess.
  60611. * @param fragmentUrl The url of the fragment shader to be used.
  60612. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60613. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60614. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60615. * @param camera The camera to apply the render pass to.
  60616. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60617. * @param engine The engine which the post process will be applied. (default: current engine)
  60618. * @param reusable If the post process can be reused on the same frame. (default: false)
  60619. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60620. * @param textureType Type of textures used when performing the post process. (default: 0)
  60621. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60622. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  60623. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60624. */
  60625. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60626. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60627. if (defines === void 0) { defines = null; }
  60628. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60629. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60630. if (blockCompilation === void 0) { blockCompilation = false; }
  60631. this.name = name;
  60632. /**
  60633. * Width of the texture to apply the post process on
  60634. */
  60635. this.width = -1;
  60636. /**
  60637. * Height of the texture to apply the post process on
  60638. */
  60639. this.height = -1;
  60640. /**
  60641. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  60642. */
  60643. this._outputTexture = null;
  60644. /**
  60645. * If the buffer needs to be cleared before applying the post process. (default: true)
  60646. * Should be set to false if shader will overwrite all previous pixels.
  60647. */
  60648. this.autoClear = true;
  60649. /**
  60650. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60651. */
  60652. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60653. /**
  60654. * Animations to be used for the post processing
  60655. */
  60656. this.animations = new Array();
  60657. /**
  60658. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60659. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60660. */
  60661. this.enablePixelPerfectMode = false;
  60662. /**
  60663. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60664. */
  60665. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60666. /**
  60667. * Force textures to be a power of two (default: false)
  60668. */
  60669. this.alwaysForcePOT = false;
  60670. /**
  60671. * Number of sample textures (default: 1)
  60672. */
  60673. this.samples = 1;
  60674. /**
  60675. * Modify the scale of the post process to be the same as the viewport (default: false)
  60676. */
  60677. this.adaptScaleToCurrentViewport = false;
  60678. this._reusable = false;
  60679. /**
  60680. * Smart array of input and output textures for the post process.
  60681. */
  60682. this._textures = new BABYLON.SmartArray(2);
  60683. /**
  60684. * The index in _textures that corresponds to the output texture.
  60685. */
  60686. this._currentRenderTextureInd = 0;
  60687. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60688. this._texelSize = BABYLON.Vector2.Zero();
  60689. // Events
  60690. /**
  60691. * An event triggered when the postprocess is activated.
  60692. * @type {BABYLON.Observable}
  60693. */
  60694. this.onActivateObservable = new BABYLON.Observable();
  60695. /**
  60696. * An event triggered when the postprocess changes its size.
  60697. * @type {BABYLON.Observable}
  60698. */
  60699. this.onSizeChangedObservable = new BABYLON.Observable();
  60700. /**
  60701. * An event triggered when the postprocess applies its effect.
  60702. * @type {BABYLON.Observable}
  60703. */
  60704. this.onApplyObservable = new BABYLON.Observable();
  60705. /**
  60706. * An event triggered before rendering the postprocess
  60707. * @type {BABYLON.Observable}
  60708. */
  60709. this.onBeforeRenderObservable = new BABYLON.Observable();
  60710. /**
  60711. * An event triggered after rendering the postprocess
  60712. * @type {BABYLON.Observable}
  60713. */
  60714. this.onAfterRenderObservable = new BABYLON.Observable();
  60715. if (camera != null) {
  60716. this._camera = camera;
  60717. this._scene = camera.getScene();
  60718. camera.attachPostProcess(this);
  60719. this._engine = this._scene.getEngine();
  60720. this._scene.postProcesses.push(this);
  60721. }
  60722. else if (engine) {
  60723. this._engine = engine;
  60724. this._engine.postProcesses.push(this);
  60725. }
  60726. this._options = options;
  60727. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60728. this._reusable = reusable || false;
  60729. this._textureType = textureType;
  60730. this._samplers = samplers || [];
  60731. this._samplers.push("textureSampler");
  60732. this._fragmentUrl = fragmentUrl;
  60733. this._vertexUrl = vertexUrl;
  60734. this._parameters = parameters || [];
  60735. this._parameters.push("scale");
  60736. this._indexParameters = indexParameters;
  60737. if (!blockCompilation) {
  60738. this.updateEffect(defines);
  60739. }
  60740. }
  60741. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60742. /**
  60743. * A function that is added to the onActivateObservable
  60744. */
  60745. set: function (callback) {
  60746. if (this._onActivateObserver) {
  60747. this.onActivateObservable.remove(this._onActivateObserver);
  60748. }
  60749. if (callback) {
  60750. this._onActivateObserver = this.onActivateObservable.add(callback);
  60751. }
  60752. },
  60753. enumerable: true,
  60754. configurable: true
  60755. });
  60756. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60757. /**
  60758. * A function that is added to the onSizeChangedObservable
  60759. */
  60760. set: function (callback) {
  60761. if (this._onSizeChangedObserver) {
  60762. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60763. }
  60764. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60765. },
  60766. enumerable: true,
  60767. configurable: true
  60768. });
  60769. Object.defineProperty(PostProcess.prototype, "onApply", {
  60770. /**
  60771. * A function that is added to the onApplyObservable
  60772. */
  60773. set: function (callback) {
  60774. if (this._onApplyObserver) {
  60775. this.onApplyObservable.remove(this._onApplyObserver);
  60776. }
  60777. this._onApplyObserver = this.onApplyObservable.add(callback);
  60778. },
  60779. enumerable: true,
  60780. configurable: true
  60781. });
  60782. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60783. /**
  60784. * A function that is added to the onBeforeRenderObservable
  60785. */
  60786. set: function (callback) {
  60787. if (this._onBeforeRenderObserver) {
  60788. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60789. }
  60790. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60791. },
  60792. enumerable: true,
  60793. configurable: true
  60794. });
  60795. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60796. /**
  60797. * A function that is added to the onAfterRenderObservable
  60798. */
  60799. set: function (callback) {
  60800. if (this._onAfterRenderObserver) {
  60801. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60802. }
  60803. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60804. },
  60805. enumerable: true,
  60806. configurable: true
  60807. });
  60808. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60809. /**
  60810. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  60811. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60812. */
  60813. get: function () {
  60814. return this._textures.data[this._currentRenderTextureInd];
  60815. },
  60816. set: function (value) {
  60817. this._forcedOutputTexture = value;
  60818. },
  60819. enumerable: true,
  60820. configurable: true
  60821. });
  60822. /**
  60823. * Gets the camera which post process is applied to.
  60824. * @returns The camera the post process is applied to.
  60825. */
  60826. PostProcess.prototype.getCamera = function () {
  60827. return this._camera;
  60828. };
  60829. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60830. /**
  60831. * Gets the texel size of the postprocess.
  60832. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60833. */
  60834. get: function () {
  60835. if (this._shareOutputWithPostProcess) {
  60836. return this._shareOutputWithPostProcess.texelSize;
  60837. }
  60838. if (this._forcedOutputTexture) {
  60839. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60840. }
  60841. return this._texelSize;
  60842. },
  60843. enumerable: true,
  60844. configurable: true
  60845. });
  60846. /**
  60847. * Gets the engine which this post process belongs to.
  60848. * @returns The engine the post process was enabled with.
  60849. */
  60850. PostProcess.prototype.getEngine = function () {
  60851. return this._engine;
  60852. };
  60853. /**
  60854. * The effect that is created when initializing the post process.
  60855. * @returns The created effect corrisponding the the postprocess.
  60856. */
  60857. PostProcess.prototype.getEffect = function () {
  60858. return this._effect;
  60859. };
  60860. /**
  60861. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60862. * @param postProcess The post process to share the output with.
  60863. * @returns This post process.
  60864. */
  60865. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60866. this._disposeTextures();
  60867. this._shareOutputWithPostProcess = postProcess;
  60868. return this;
  60869. };
  60870. /**
  60871. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60872. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60873. */
  60874. PostProcess.prototype.useOwnOutput = function () {
  60875. if (this._textures.length == 0) {
  60876. this._textures = new BABYLON.SmartArray(2);
  60877. }
  60878. this._shareOutputWithPostProcess = null;
  60879. };
  60880. /**
  60881. * Updates the effect with the current post process compile time values and recompiles the shader.
  60882. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60883. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60884. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60885. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  60886. * @param onCompiled Called when the shader has been compiled.
  60887. * @param onError Called if there is an error when compiling a shader.
  60888. */
  60889. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60890. if (defines === void 0) { defines = null; }
  60891. if (uniforms === void 0) { uniforms = null; }
  60892. if (samplers === void 0) { samplers = null; }
  60893. 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);
  60894. };
  60895. /**
  60896. * The post process is reusable if it can be used multiple times within one frame.
  60897. * @returns If the post process is reusable
  60898. */
  60899. PostProcess.prototype.isReusable = function () {
  60900. return this._reusable;
  60901. };
  60902. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60903. PostProcess.prototype.markTextureDirty = function () {
  60904. this.width = -1;
  60905. };
  60906. /**
  60907. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60908. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  60909. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60910. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60911. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60912. * @returns The target texture that was bound to be written to.
  60913. */
  60914. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60915. var _this = this;
  60916. if (sourceTexture === void 0) { sourceTexture = null; }
  60917. camera = camera || this._camera;
  60918. var scene = camera.getScene();
  60919. var engine = scene.getEngine();
  60920. var maxSize = engine.getCaps().maxTextureSize;
  60921. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60922. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60923. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  60924. var webVRCamera = camera.parent;
  60925. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60926. requiredWidth /= 2;
  60927. }
  60928. var desiredWidth = (this._options.width || requiredWidth);
  60929. var desiredHeight = this._options.height || requiredHeight;
  60930. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60931. if (this.adaptScaleToCurrentViewport) {
  60932. var currentViewport = engine.currentViewport;
  60933. if (currentViewport) {
  60934. desiredWidth *= currentViewport.width;
  60935. desiredHeight *= currentViewport.height;
  60936. }
  60937. }
  60938. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60939. if (!this._options.width) {
  60940. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60941. }
  60942. if (!this._options.height) {
  60943. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60944. }
  60945. }
  60946. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60947. if (this._textures.length > 0) {
  60948. for (var i = 0; i < this._textures.length; i++) {
  60949. this._engine._releaseTexture(this._textures.data[i]);
  60950. }
  60951. this._textures.reset();
  60952. }
  60953. this.width = desiredWidth;
  60954. this.height = desiredHeight;
  60955. var textureSize = { width: this.width, height: this.height };
  60956. var textureOptions = {
  60957. generateMipMaps: false,
  60958. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60959. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60960. samplingMode: this.renderTargetSamplingMode,
  60961. type: this._textureType
  60962. };
  60963. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60964. if (this._reusable) {
  60965. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60966. }
  60967. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60968. this.onSizeChangedObservable.notifyObservers(this);
  60969. }
  60970. this._textures.forEach(function (texture) {
  60971. if (texture.samples !== _this.samples) {
  60972. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60973. }
  60974. });
  60975. }
  60976. var target;
  60977. if (this._shareOutputWithPostProcess) {
  60978. target = this._shareOutputWithPostProcess.inputTexture;
  60979. }
  60980. else if (this._forcedOutputTexture) {
  60981. target = this._forcedOutputTexture;
  60982. this.width = this._forcedOutputTexture.width;
  60983. this.height = this._forcedOutputTexture.height;
  60984. }
  60985. else {
  60986. target = this.inputTexture;
  60987. }
  60988. // Bind the input of this post process to be used as the output of the previous post process.
  60989. if (this.enablePixelPerfectMode) {
  60990. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60991. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60992. }
  60993. else {
  60994. this._scaleRatio.copyFromFloats(1, 1);
  60995. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60996. }
  60997. this.onActivateObservable.notifyObservers(camera);
  60998. // Clear
  60999. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  61000. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  61001. }
  61002. if (this._reusable) {
  61003. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  61004. }
  61005. return target;
  61006. };
  61007. Object.defineProperty(PostProcess.prototype, "isSupported", {
  61008. /**
  61009. * If the post process is supported.
  61010. */
  61011. get: function () {
  61012. return this._effect.isSupported;
  61013. },
  61014. enumerable: true,
  61015. configurable: true
  61016. });
  61017. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  61018. /**
  61019. * The aspect ratio of the output texture.
  61020. */
  61021. get: function () {
  61022. if (this._shareOutputWithPostProcess) {
  61023. return this._shareOutputWithPostProcess.aspectRatio;
  61024. }
  61025. if (this._forcedOutputTexture) {
  61026. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  61027. }
  61028. return this.width / this.height;
  61029. },
  61030. enumerable: true,
  61031. configurable: true
  61032. });
  61033. /**
  61034. * Get a value indicating if the post-process is ready to be used
  61035. * @returns true if the post-process is ready (shader is compiled)
  61036. */
  61037. PostProcess.prototype.isReady = function () {
  61038. return this._effect && this._effect.isReady();
  61039. };
  61040. /**
  61041. * Binds all textures and uniforms to the shader, this will be run on every pass.
  61042. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  61043. */
  61044. PostProcess.prototype.apply = function () {
  61045. // Check
  61046. if (!this._effect || !this._effect.isReady())
  61047. return null;
  61048. // States
  61049. this._engine.enableEffect(this._effect);
  61050. this._engine.setState(false);
  61051. this._engine.setDepthBuffer(false);
  61052. this._engine.setDepthWrite(false);
  61053. // Alpha
  61054. this._engine.setAlphaMode(this.alphaMode);
  61055. if (this.alphaConstants) {
  61056. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  61057. }
  61058. // Bind the output texture of the preivous post process as the input to this post process.
  61059. var source;
  61060. if (this._shareOutputWithPostProcess) {
  61061. source = this._shareOutputWithPostProcess.inputTexture;
  61062. }
  61063. else if (this._forcedOutputTexture) {
  61064. source = this._forcedOutputTexture;
  61065. }
  61066. else {
  61067. source = this.inputTexture;
  61068. }
  61069. this._effect._bindTexture("textureSampler", source);
  61070. // Parameters
  61071. this._effect.setVector2("scale", this._scaleRatio);
  61072. this.onApplyObservable.notifyObservers(this._effect);
  61073. return this._effect;
  61074. };
  61075. PostProcess.prototype._disposeTextures = function () {
  61076. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  61077. return;
  61078. }
  61079. if (this._textures.length > 0) {
  61080. for (var i = 0; i < this._textures.length; i++) {
  61081. this._engine._releaseTexture(this._textures.data[i]);
  61082. }
  61083. }
  61084. this._textures.dispose();
  61085. };
  61086. /**
  61087. * Disposes the post process.
  61088. * @param camera The camera to dispose the post process on.
  61089. */
  61090. PostProcess.prototype.dispose = function (camera) {
  61091. camera = camera || this._camera;
  61092. this._disposeTextures();
  61093. if (this._scene) {
  61094. var index_1 = this._scene.postProcesses.indexOf(this);
  61095. if (index_1 !== -1) {
  61096. this._scene.postProcesses.splice(index_1, 1);
  61097. }
  61098. }
  61099. else {
  61100. var index_2 = this._engine.postProcesses.indexOf(this);
  61101. if (index_2 !== -1) {
  61102. this._engine.postProcesses.splice(index_2, 1);
  61103. }
  61104. }
  61105. if (!camera) {
  61106. return;
  61107. }
  61108. camera.detachPostProcess(this);
  61109. var index = camera._postProcesses.indexOf(this);
  61110. if (index === 0 && camera._postProcesses.length > 0) {
  61111. var firstPostProcess = this._camera._getFirstPostProcess();
  61112. if (firstPostProcess) {
  61113. firstPostProcess.markTextureDirty();
  61114. }
  61115. }
  61116. this.onActivateObservable.clear();
  61117. this.onAfterRenderObservable.clear();
  61118. this.onApplyObservable.clear();
  61119. this.onBeforeRenderObservable.clear();
  61120. this.onSizeChangedObservable.clear();
  61121. };
  61122. return PostProcess;
  61123. }());
  61124. BABYLON.PostProcess = PostProcess;
  61125. })(BABYLON || (BABYLON = {}));
  61126. //# sourceMappingURL=babylon.postProcess.js.map
  61127. "use strict";
  61128. var BABYLON;
  61129. (function (BABYLON) {
  61130. var PassPostProcess = /** @class */ (function (_super) {
  61131. __extends(PassPostProcess, _super);
  61132. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  61133. if (camera === void 0) { camera = null; }
  61134. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61135. if (blockCompilation === void 0) { blockCompilation = false; }
  61136. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  61137. }
  61138. return PassPostProcess;
  61139. }(BABYLON.PostProcess));
  61140. BABYLON.PassPostProcess = PassPostProcess;
  61141. })(BABYLON || (BABYLON = {}));
  61142. //# sourceMappingURL=babylon.passPostProcess.js.map
  61143. "use strict";
  61144. var __assign = (this && this.__assign) || Object.assign || function(t) {
  61145. for (var s, i = 1, n = arguments.length; i < n; i++) {
  61146. s = arguments[i];
  61147. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  61148. t[p] = s[p];
  61149. }
  61150. return t;
  61151. };
  61152. var BABYLON;
  61153. (function (BABYLON) {
  61154. /**
  61155. * Default implementation of @see IShadowGenerator.
  61156. * This is the main object responsible of generating shadows in the framework.
  61157. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  61158. */
  61159. var ShadowGenerator = /** @class */ (function () {
  61160. /**
  61161. * Creates a ShadowGenerator object.
  61162. * A ShadowGenerator is the required tool to use the shadows.
  61163. * Each light casting shadows needs to use its own ShadowGenerator.
  61164. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  61165. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  61166. * @param light The light object generating the shadows.
  61167. * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  61168. */
  61169. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  61170. this._bias = 0.00005;
  61171. this._normalBias = 0;
  61172. this._blurBoxOffset = 1;
  61173. this._blurScale = 2;
  61174. this._blurKernel = 1;
  61175. this._useKernelBlur = false;
  61176. this._filter = ShadowGenerator.FILTER_NONE;
  61177. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  61178. this._contactHardeningLightSizeUVRatio = 0.1;
  61179. this._darkness = 0;
  61180. this._transparencyShadow = false;
  61181. /**
  61182. * Controls the extent to which the shadows fade out at the edge of the frustum
  61183. * Used only by directionals and spots
  61184. */
  61185. this.frustumEdgeFalloff = 0;
  61186. /**
  61187. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  61188. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  61189. * It might on the other hand introduce peter panning.
  61190. */
  61191. this.forceBackFacesOnly = false;
  61192. this._lightDirection = BABYLON.Vector3.Zero();
  61193. this._viewMatrix = BABYLON.Matrix.Zero();
  61194. this._projectionMatrix = BABYLON.Matrix.Zero();
  61195. this._transformMatrix = BABYLON.Matrix.Zero();
  61196. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61197. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61198. this._currentFaceIndex = 0;
  61199. this._currentFaceIndexCache = 0;
  61200. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  61201. this._mapSize = mapSize;
  61202. this._light = light;
  61203. this._scene = light.getScene();
  61204. light._shadowGenerator = this;
  61205. // Texture type fallback from float to int if not supported.
  61206. var caps = this._scene.getEngine().getCaps();
  61207. if (!useFullFloatFirst) {
  61208. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61209. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61210. }
  61211. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61212. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61213. }
  61214. else {
  61215. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61216. }
  61217. }
  61218. else {
  61219. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61220. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61221. }
  61222. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61223. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61224. }
  61225. else {
  61226. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61227. }
  61228. }
  61229. this._initializeGenerator();
  61230. this._applyFilterValues();
  61231. }
  61232. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  61233. /**
  61234. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  61235. */
  61236. get: function () {
  61237. return this._bias;
  61238. },
  61239. /**
  61240. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  61241. */
  61242. set: function (bias) {
  61243. this._bias = bias;
  61244. },
  61245. enumerable: true,
  61246. configurable: true
  61247. });
  61248. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  61249. /**
  61250. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61251. */
  61252. get: function () {
  61253. return this._normalBias;
  61254. },
  61255. /**
  61256. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61257. */
  61258. set: function (normalBias) {
  61259. this._normalBias = normalBias;
  61260. },
  61261. enumerable: true,
  61262. configurable: true
  61263. });
  61264. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  61265. /**
  61266. * Gets the blur box offset: offset applied during the blur pass.
  61267. * Only usefull if useKernelBlur = false
  61268. */
  61269. get: function () {
  61270. return this._blurBoxOffset;
  61271. },
  61272. /**
  61273. * Sets the blur box offset: offset applied during the blur pass.
  61274. * Only usefull if useKernelBlur = false
  61275. */
  61276. set: function (value) {
  61277. if (this._blurBoxOffset === value) {
  61278. return;
  61279. }
  61280. this._blurBoxOffset = value;
  61281. this._disposeBlurPostProcesses();
  61282. },
  61283. enumerable: true,
  61284. configurable: true
  61285. });
  61286. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  61287. /**
  61288. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  61289. * 2 means half of the size.
  61290. */
  61291. get: function () {
  61292. return this._blurScale;
  61293. },
  61294. /**
  61295. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  61296. * 2 means half of the size.
  61297. */
  61298. set: function (value) {
  61299. if (this._blurScale === value) {
  61300. return;
  61301. }
  61302. this._blurScale = value;
  61303. this._disposeBlurPostProcesses();
  61304. },
  61305. enumerable: true,
  61306. configurable: true
  61307. });
  61308. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  61309. /**
  61310. * Gets the blur kernel: kernel size of the blur pass.
  61311. * Only usefull if useKernelBlur = true
  61312. */
  61313. get: function () {
  61314. return this._blurKernel;
  61315. },
  61316. /**
  61317. * Sets the blur kernel: kernel size of the blur pass.
  61318. * Only usefull if useKernelBlur = true
  61319. */
  61320. set: function (value) {
  61321. if (this._blurKernel === value) {
  61322. return;
  61323. }
  61324. this._blurKernel = value;
  61325. this._disposeBlurPostProcesses();
  61326. },
  61327. enumerable: true,
  61328. configurable: true
  61329. });
  61330. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  61331. /**
  61332. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  61333. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61334. */
  61335. get: function () {
  61336. return this._useKernelBlur;
  61337. },
  61338. /**
  61339. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  61340. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61341. */
  61342. set: function (value) {
  61343. if (this._useKernelBlur === value) {
  61344. return;
  61345. }
  61346. this._useKernelBlur = value;
  61347. this._disposeBlurPostProcesses();
  61348. },
  61349. enumerable: true,
  61350. configurable: true
  61351. });
  61352. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  61353. /**
  61354. * Gets the depth scale used in ESM mode.
  61355. */
  61356. get: function () {
  61357. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  61358. },
  61359. /**
  61360. * Sets the depth scale used in ESM mode.
  61361. * This can override the scale stored on the light.
  61362. */
  61363. set: function (value) {
  61364. this._depthScale = value;
  61365. },
  61366. enumerable: true,
  61367. configurable: true
  61368. });
  61369. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  61370. /**
  61371. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  61372. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61373. */
  61374. get: function () {
  61375. return this._filter;
  61376. },
  61377. /**
  61378. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  61379. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61380. */
  61381. set: function (value) {
  61382. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  61383. if (this._light.needCube()) {
  61384. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61385. this.useExponentialShadowMap = true;
  61386. return;
  61387. }
  61388. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61389. this.useCloseExponentialShadowMap = true;
  61390. return;
  61391. }
  61392. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61393. this.usePoissonSampling = true;
  61394. return;
  61395. }
  61396. }
  61397. // Weblg1 fallback for PCF.
  61398. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61399. if (this._scene.getEngine().webGLVersion === 1) {
  61400. this.usePoissonSampling = true;
  61401. return;
  61402. }
  61403. }
  61404. if (this._filter === value) {
  61405. return;
  61406. }
  61407. this._filter = value;
  61408. this._disposeBlurPostProcesses();
  61409. this._applyFilterValues();
  61410. this._light._markMeshesAsLightDirty();
  61411. },
  61412. enumerable: true,
  61413. configurable: true
  61414. });
  61415. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  61416. /**
  61417. * Gets if the current filter is set to Poisson Sampling.
  61418. */
  61419. get: function () {
  61420. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  61421. },
  61422. /**
  61423. * Sets the current filter to Poisson Sampling.
  61424. */
  61425. set: function (value) {
  61426. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  61427. return;
  61428. }
  61429. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  61430. },
  61431. enumerable: true,
  61432. configurable: true
  61433. });
  61434. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  61435. /**
  61436. * Gets if the current filter is set to VSM.
  61437. * DEPRECATED. Should use useExponentialShadowMap instead.
  61438. */
  61439. get: function () {
  61440. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61441. return this.useExponentialShadowMap;
  61442. },
  61443. /**
  61444. * Sets the current filter is to VSM.
  61445. * DEPRECATED. Should use useExponentialShadowMap instead.
  61446. */
  61447. set: function (value) {
  61448. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61449. this.useExponentialShadowMap = value;
  61450. },
  61451. enumerable: true,
  61452. configurable: true
  61453. });
  61454. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  61455. /**
  61456. * Gets if the current filter is set to blurred VSM.
  61457. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61458. */
  61459. get: function () {
  61460. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61461. return this.useBlurExponentialShadowMap;
  61462. },
  61463. /**
  61464. * Sets the current filter is to blurred VSM.
  61465. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61466. */
  61467. set: function (value) {
  61468. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61469. this.useBlurExponentialShadowMap = value;
  61470. },
  61471. enumerable: true,
  61472. configurable: true
  61473. });
  61474. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  61475. /**
  61476. * Gets if the current filter is set to ESM.
  61477. */
  61478. get: function () {
  61479. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  61480. },
  61481. /**
  61482. * Sets the current filter is to ESM.
  61483. */
  61484. set: function (value) {
  61485. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61486. return;
  61487. }
  61488. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61489. },
  61490. enumerable: true,
  61491. configurable: true
  61492. });
  61493. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61494. /**
  61495. * Gets if the current filter is set to filtered ESM.
  61496. */
  61497. get: function () {
  61498. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61499. },
  61500. /**
  61501. * Gets if the current filter is set to filtered ESM.
  61502. */
  61503. set: function (value) {
  61504. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61505. return;
  61506. }
  61507. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61508. },
  61509. enumerable: true,
  61510. configurable: true
  61511. });
  61512. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61513. /**
  61514. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61515. * exponential to prevent steep falloff artifacts).
  61516. */
  61517. get: function () {
  61518. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61519. },
  61520. /**
  61521. * Sets the current filter to "close ESM" (using the inverse of the
  61522. * exponential to prevent steep falloff artifacts).
  61523. */
  61524. set: function (value) {
  61525. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61526. return;
  61527. }
  61528. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61529. },
  61530. enumerable: true,
  61531. configurable: true
  61532. });
  61533. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61534. /**
  61535. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61536. * exponential to prevent steep falloff artifacts).
  61537. */
  61538. get: function () {
  61539. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61540. },
  61541. /**
  61542. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61543. * exponential to prevent steep falloff artifacts).
  61544. */
  61545. set: function (value) {
  61546. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61547. return;
  61548. }
  61549. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61550. },
  61551. enumerable: true,
  61552. configurable: true
  61553. });
  61554. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61555. /**
  61556. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61557. */
  61558. get: function () {
  61559. return this.filter === ShadowGenerator.FILTER_PCF;
  61560. },
  61561. /**
  61562. * Sets the current filter to "PCF" (percentage closer filtering).
  61563. */
  61564. set: function (value) {
  61565. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61566. return;
  61567. }
  61568. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61569. },
  61570. enumerable: true,
  61571. configurable: true
  61572. });
  61573. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61574. /**
  61575. * Gets the PCF or PCSS Quality.
  61576. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61577. */
  61578. get: function () {
  61579. return this._filteringQuality;
  61580. },
  61581. /**
  61582. * Sets the PCF or PCSS Quality.
  61583. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61584. */
  61585. set: function (filteringQuality) {
  61586. this._filteringQuality = filteringQuality;
  61587. },
  61588. enumerable: true,
  61589. configurable: true
  61590. });
  61591. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61592. /**
  61593. * Gets if the current filter is set to "PCSS" (contact hardening).
  61594. */
  61595. get: function () {
  61596. return this.filter === ShadowGenerator.FILTER_PCSS;
  61597. },
  61598. /**
  61599. * Sets the current filter to "PCSS" (contact hardening).
  61600. */
  61601. set: function (value) {
  61602. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61603. return;
  61604. }
  61605. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61606. },
  61607. enumerable: true,
  61608. configurable: true
  61609. });
  61610. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61611. /**
  61612. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61613. * Using a ratio helps keeping shape stability independently of the map size.
  61614. *
  61615. * It does not account for the light projection as it was having too much
  61616. * instability during the light setup or during light position changes.
  61617. *
  61618. * Only valid if useContactHardeningShadow is true.
  61619. */
  61620. get: function () {
  61621. return this._contactHardeningLightSizeUVRatio;
  61622. },
  61623. /**
  61624. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61625. * Using a ratio helps keeping shape stability independently of the map size.
  61626. *
  61627. * It does not account for the light projection as it was having too much
  61628. * instability during the light setup or during light position changes.
  61629. *
  61630. * Only valid if useContactHardeningShadow is true.
  61631. */
  61632. set: function (contactHardeningLightSizeUVRatio) {
  61633. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61634. },
  61635. enumerable: true,
  61636. configurable: true
  61637. });
  61638. /**
  61639. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61640. * 0 means strongest and 1 would means no shadow.
  61641. * @returns the darkness.
  61642. */
  61643. ShadowGenerator.prototype.getDarkness = function () {
  61644. return this._darkness;
  61645. };
  61646. /**
  61647. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61648. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61649. * @returns the shadow generator allowing fluent coding.
  61650. */
  61651. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61652. if (darkness >= 1.0)
  61653. this._darkness = 1.0;
  61654. else if (darkness <= 0.0)
  61655. this._darkness = 0.0;
  61656. else
  61657. this._darkness = darkness;
  61658. return this;
  61659. };
  61660. /**
  61661. * Sets the ability to have transparent shadow (boolean).
  61662. * @param transparent True if transparent else False
  61663. * @returns the shadow generator allowing fluent coding
  61664. */
  61665. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61666. this._transparencyShadow = transparent;
  61667. return this;
  61668. };
  61669. /**
  61670. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61671. * @returns The render target texture if present otherwise, null
  61672. */
  61673. ShadowGenerator.prototype.getShadowMap = function () {
  61674. return this._shadowMap;
  61675. };
  61676. /**
  61677. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61678. * @returns The render target texture if the shadow map is present otherwise, null
  61679. */
  61680. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61681. if (this._shadowMap2) {
  61682. return this._shadowMap2;
  61683. }
  61684. return this._shadowMap;
  61685. };
  61686. /**
  61687. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61688. * @param mesh Mesh to add
  61689. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61690. * @returns the Shadow Generator itself
  61691. */
  61692. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61693. if (includeDescendants === void 0) { includeDescendants = true; }
  61694. if (!this._shadowMap) {
  61695. return this;
  61696. }
  61697. if (!this._shadowMap.renderList) {
  61698. this._shadowMap.renderList = [];
  61699. }
  61700. this._shadowMap.renderList.push(mesh);
  61701. if (includeDescendants) {
  61702. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61703. }
  61704. return this;
  61705. var _a;
  61706. };
  61707. /**
  61708. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61709. * @param mesh Mesh to remove
  61710. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61711. * @returns the Shadow Generator itself
  61712. */
  61713. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61714. if (includeDescendants === void 0) { includeDescendants = true; }
  61715. if (!this._shadowMap || !this._shadowMap.renderList) {
  61716. return this;
  61717. }
  61718. var index = this._shadowMap.renderList.indexOf(mesh);
  61719. if (index !== -1) {
  61720. this._shadowMap.renderList.splice(index, 1);
  61721. }
  61722. if (includeDescendants) {
  61723. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61724. var child = _a[_i];
  61725. this.removeShadowCaster(child);
  61726. }
  61727. }
  61728. return this;
  61729. };
  61730. /**
  61731. * Returns the associated light object.
  61732. * @returns the light generating the shadow
  61733. */
  61734. ShadowGenerator.prototype.getLight = function () {
  61735. return this._light;
  61736. };
  61737. ShadowGenerator.prototype._initializeGenerator = function () {
  61738. this._light._markMeshesAsLightDirty();
  61739. this._initializeShadowMap();
  61740. };
  61741. ShadowGenerator.prototype._initializeShadowMap = function () {
  61742. var _this = this;
  61743. // Render target
  61744. var engine = this._scene.getEngine();
  61745. if (engine.webGLVersion > 1) {
  61746. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61747. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61748. }
  61749. else {
  61750. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61751. }
  61752. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61753. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61754. this._shadowMap.anisotropicFilteringLevel = 1;
  61755. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61756. this._shadowMap.renderParticles = false;
  61757. this._shadowMap.ignoreCameraViewport = true;
  61758. // Record Face Index before render.
  61759. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61760. _this._currentFaceIndex = faceIndex;
  61761. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61762. engine.setColorWrite(false);
  61763. }
  61764. });
  61765. // Custom render function.
  61766. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61767. // Blur if required afer render.
  61768. this._shadowMap.onAfterUnbindObservable.add(function () {
  61769. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61770. engine.setColorWrite(true);
  61771. }
  61772. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61773. return;
  61774. }
  61775. var shadowMap = _this.getShadowMapForRendering();
  61776. if (shadowMap) {
  61777. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61778. }
  61779. });
  61780. // Clear according to the chosen filter.
  61781. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61782. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61783. this._shadowMap.onClearObservable.add(function (engine) {
  61784. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61785. engine.clear(clearOne, false, true, false);
  61786. }
  61787. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61788. engine.clear(clearZero, true, true, false);
  61789. }
  61790. else {
  61791. engine.clear(clearOne, true, true, false);
  61792. }
  61793. });
  61794. };
  61795. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61796. var _this = this;
  61797. var engine = this._scene.getEngine();
  61798. var targetSize = this._mapSize / this.blurScale;
  61799. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61800. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61801. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61802. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61803. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61804. }
  61805. if (this.useKernelBlur) {
  61806. 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);
  61807. this._kernelBlurXPostprocess.width = targetSize;
  61808. this._kernelBlurXPostprocess.height = targetSize;
  61809. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61810. effect.setTexture("textureSampler", _this._shadowMap);
  61811. });
  61812. 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);
  61813. this._kernelBlurXPostprocess.autoClear = false;
  61814. this._kernelBlurYPostprocess.autoClear = false;
  61815. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61816. this._kernelBlurXPostprocess.packedFloat = true;
  61817. this._kernelBlurYPostprocess.packedFloat = true;
  61818. }
  61819. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61820. }
  61821. else {
  61822. 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);
  61823. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61824. effect.setFloat2("screenSize", targetSize, targetSize);
  61825. effect.setTexture("textureSampler", _this._shadowMap);
  61826. });
  61827. this._boxBlurPostprocess.autoClear = false;
  61828. this._blurPostProcesses = [this._boxBlurPostprocess];
  61829. }
  61830. };
  61831. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61832. var index;
  61833. var engine = this._scene.getEngine();
  61834. if (depthOnlySubMeshes.length) {
  61835. engine.setColorWrite(false);
  61836. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61837. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61838. }
  61839. engine.setColorWrite(true);
  61840. }
  61841. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61842. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61843. }
  61844. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61845. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61846. }
  61847. if (this._transparencyShadow) {
  61848. for (index = 0; index < transparentSubMeshes.length; index++) {
  61849. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61850. }
  61851. }
  61852. };
  61853. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61854. var _this = this;
  61855. var mesh = subMesh.getRenderingMesh();
  61856. var scene = this._scene;
  61857. var engine = scene.getEngine();
  61858. var material = subMesh.getMaterial();
  61859. if (!material) {
  61860. return;
  61861. }
  61862. // Culling
  61863. engine.setState(material.backFaceCulling);
  61864. // Managing instances
  61865. var batch = mesh._getInstancesRenderList(subMesh._id);
  61866. if (batch.mustReturn) {
  61867. return;
  61868. }
  61869. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61870. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61871. engine.enableEffect(this._effect);
  61872. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61873. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61874. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61875. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61876. this._effect.setVector3("lightData", this._cachedDirection);
  61877. }
  61878. else {
  61879. this._effect.setVector3("lightData", this._cachedPosition);
  61880. }
  61881. if (scene.activeCamera) {
  61882. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61883. }
  61884. // Alpha test
  61885. if (material && material.needAlphaTesting()) {
  61886. var alphaTexture = material.getAlphaTestTexture();
  61887. if (alphaTexture) {
  61888. this._effect.setTexture("diffuseSampler", alphaTexture);
  61889. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61890. }
  61891. }
  61892. // Bones
  61893. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61894. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61895. }
  61896. // Morph targets
  61897. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  61898. if (this.forceBackFacesOnly) {
  61899. engine.setState(true, 0, false, true);
  61900. }
  61901. // Draw
  61902. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61903. if (this.forceBackFacesOnly) {
  61904. engine.setState(true, 0, false, false);
  61905. }
  61906. }
  61907. else {
  61908. // Need to reset refresh rate of the shadowMap
  61909. if (this._shadowMap) {
  61910. this._shadowMap.resetRefreshCounter();
  61911. }
  61912. }
  61913. };
  61914. ShadowGenerator.prototype._applyFilterValues = function () {
  61915. if (!this._shadowMap) {
  61916. return;
  61917. }
  61918. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61919. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61920. }
  61921. else {
  61922. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61923. }
  61924. };
  61925. /**
  61926. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61927. * @param onCompiled Callback triggered at the and of the effects compilation
  61928. * @param options Sets of optional options forcing the compilation with different modes
  61929. */
  61930. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61931. var _this = this;
  61932. var localOptions = __assign({ useInstances: false }, options);
  61933. var shadowMap = this.getShadowMap();
  61934. if (!shadowMap) {
  61935. if (onCompiled) {
  61936. onCompiled(this);
  61937. }
  61938. return;
  61939. }
  61940. var renderList = shadowMap.renderList;
  61941. if (!renderList) {
  61942. if (onCompiled) {
  61943. onCompiled(this);
  61944. }
  61945. return;
  61946. }
  61947. var subMeshes = new Array();
  61948. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61949. var mesh = renderList_1[_i];
  61950. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61951. }
  61952. if (subMeshes.length === 0) {
  61953. if (onCompiled) {
  61954. onCompiled(this);
  61955. }
  61956. return;
  61957. }
  61958. var currentIndex = 0;
  61959. var checkReady = function () {
  61960. if (!_this._scene || !_this._scene.getEngine()) {
  61961. return;
  61962. }
  61963. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61964. currentIndex++;
  61965. if (currentIndex >= subMeshes.length) {
  61966. if (onCompiled) {
  61967. onCompiled(_this);
  61968. }
  61969. return;
  61970. }
  61971. }
  61972. setTimeout(checkReady, 16);
  61973. };
  61974. checkReady();
  61975. };
  61976. /**
  61977. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61978. * @param options Sets of optional options forcing the compilation with different modes
  61979. * @returns A promise that resolves when the compilation completes
  61980. */
  61981. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61982. var _this = this;
  61983. return new Promise(function (resolve) {
  61984. _this.forceCompilation(function () {
  61985. resolve();
  61986. }, options);
  61987. });
  61988. };
  61989. /**
  61990. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61991. * @param subMesh The submesh we want to render in the shadow map
  61992. * @param useInstances Defines wether will draw in the map using instances
  61993. * @returns true if ready otherwise, false
  61994. */
  61995. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61996. var defines = [];
  61997. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61998. defines.push("#define FLOAT");
  61999. }
  62000. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62001. defines.push("#define ESM");
  62002. }
  62003. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  62004. defines.push("#define DEPTHTEXTURE");
  62005. }
  62006. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62007. var mesh = subMesh.getMesh();
  62008. var material = subMesh.getMaterial();
  62009. // Normal bias.
  62010. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  62011. attribs.push(BABYLON.VertexBuffer.NormalKind);
  62012. defines.push("#define NORMAL");
  62013. if (mesh.nonUniformScaling) {
  62014. defines.push("#define NONUNIFORMSCALING");
  62015. }
  62016. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  62017. defines.push("#define DIRECTIONINLIGHTDATA");
  62018. }
  62019. }
  62020. // Alpha test
  62021. if (material && material.needAlphaTesting()) {
  62022. var alphaTexture = material.getAlphaTestTexture();
  62023. if (alphaTexture) {
  62024. defines.push("#define ALPHATEST");
  62025. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62026. attribs.push(BABYLON.VertexBuffer.UVKind);
  62027. defines.push("#define UV1");
  62028. }
  62029. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62030. if (alphaTexture.coordinatesIndex === 1) {
  62031. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62032. defines.push("#define UV2");
  62033. }
  62034. }
  62035. }
  62036. }
  62037. // Bones
  62038. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62039. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62040. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62041. if (mesh.numBoneInfluencers > 4) {
  62042. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62043. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62044. }
  62045. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62046. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  62047. }
  62048. else {
  62049. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62050. }
  62051. // Morph targets
  62052. var manager = mesh.morphTargetManager;
  62053. var morphInfluencers = 0;
  62054. if (manager) {
  62055. if (manager.numInfluencers > 0) {
  62056. defines.push("#define MORPHTARGETS");
  62057. morphInfluencers = manager.numInfluencers;
  62058. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  62059. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  62060. }
  62061. }
  62062. // Instances
  62063. if (useInstances) {
  62064. defines.push("#define INSTANCES");
  62065. attribs.push("world0");
  62066. attribs.push("world1");
  62067. attribs.push("world2");
  62068. attribs.push("world3");
  62069. }
  62070. // Get correct effect
  62071. var join = defines.join("\n");
  62072. if (this._cachedDefines !== join) {
  62073. this._cachedDefines = join;
  62074. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  62075. }
  62076. if (!this._effect.isReady()) {
  62077. return false;
  62078. }
  62079. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62080. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  62081. this._initializeBlurRTTAndPostProcesses();
  62082. }
  62083. }
  62084. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  62085. return false;
  62086. }
  62087. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  62088. return false;
  62089. }
  62090. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  62091. return false;
  62092. }
  62093. return true;
  62094. };
  62095. /**
  62096. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  62097. * @param defines Defines of the material we want to update
  62098. * @param lightIndex Index of the light in the enabled light list of the material
  62099. */
  62100. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  62101. var scene = this._scene;
  62102. var light = this._light;
  62103. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62104. return;
  62105. }
  62106. defines["SHADOW" + lightIndex] = true;
  62107. if (this.useContactHardeningShadow) {
  62108. defines["SHADOWPCSS" + lightIndex] = true;
  62109. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62110. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62111. }
  62112. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62113. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62114. }
  62115. // else default to high.
  62116. }
  62117. if (this.usePercentageCloserFiltering) {
  62118. defines["SHADOWPCF" + lightIndex] = true;
  62119. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62120. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62121. }
  62122. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62123. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62124. }
  62125. // else default to high.
  62126. }
  62127. else if (this.usePoissonSampling) {
  62128. defines["SHADOWPOISSON" + lightIndex] = true;
  62129. }
  62130. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62131. defines["SHADOWESM" + lightIndex] = true;
  62132. }
  62133. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62134. defines["SHADOWCLOSEESM" + lightIndex] = true;
  62135. }
  62136. if (light.needCube()) {
  62137. defines["SHADOWCUBE" + lightIndex] = true;
  62138. }
  62139. };
  62140. /**
  62141. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  62142. * defined in the generator but impacting the effect).
  62143. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  62144. * @param effect The effect we are binfing the information for
  62145. */
  62146. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  62147. var light = this._light;
  62148. var scene = this._scene;
  62149. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62150. return;
  62151. }
  62152. var camera = scene.activeCamera;
  62153. if (!camera) {
  62154. return;
  62155. }
  62156. var shadowMap = this.getShadowMap();
  62157. if (!shadowMap) {
  62158. return;
  62159. }
  62160. if (!light.needCube()) {
  62161. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  62162. }
  62163. // Only PCF uses depth stencil texture.
  62164. if (this._filter === ShadowGenerator.FILTER_PCF) {
  62165. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62166. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62167. }
  62168. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  62169. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62170. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  62171. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62172. }
  62173. else {
  62174. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62175. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  62176. }
  62177. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  62178. };
  62179. /**
  62180. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  62181. * (eq to shadow prjection matrix * light transform matrix)
  62182. * @returns The transform matrix used to create the shadow map
  62183. */
  62184. ShadowGenerator.prototype.getTransformMatrix = function () {
  62185. var scene = this._scene;
  62186. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  62187. return this._transformMatrix;
  62188. }
  62189. this._currentRenderID = scene.getRenderId();
  62190. this._currentFaceIndexCache = this._currentFaceIndex;
  62191. var lightPosition = this._light.position;
  62192. if (this._light.computeTransformedInformation()) {
  62193. lightPosition = this._light.transformedPosition;
  62194. }
  62195. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  62196. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  62197. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  62198. }
  62199. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  62200. this._cachedPosition.copyFrom(lightPosition);
  62201. this._cachedDirection.copyFrom(this._lightDirection);
  62202. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  62203. var shadowMap = this.getShadowMap();
  62204. if (shadowMap) {
  62205. var renderList = shadowMap.renderList;
  62206. if (renderList) {
  62207. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  62208. }
  62209. }
  62210. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  62211. }
  62212. return this._transformMatrix;
  62213. };
  62214. /**
  62215. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  62216. * Cube and 2D textures for instance.
  62217. */
  62218. ShadowGenerator.prototype.recreateShadowMap = function () {
  62219. var shadowMap = this._shadowMap;
  62220. if (!shadowMap) {
  62221. return;
  62222. }
  62223. // Track render list.
  62224. var renderList = shadowMap.renderList;
  62225. // Clean up existing data.
  62226. this._disposeRTTandPostProcesses();
  62227. // Reinitializes.
  62228. this._initializeGenerator();
  62229. // Reaffect the filter to ensure a correct fallback if necessary.
  62230. this.filter = this.filter;
  62231. // Reaffect the filter.
  62232. this._applyFilterValues();
  62233. // Reaffect Render List.
  62234. this._shadowMap.renderList = renderList;
  62235. };
  62236. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  62237. if (this._shadowMap2) {
  62238. this._shadowMap2.dispose();
  62239. this._shadowMap2 = null;
  62240. }
  62241. if (this._boxBlurPostprocess) {
  62242. this._boxBlurPostprocess.dispose();
  62243. this._boxBlurPostprocess = null;
  62244. }
  62245. if (this._kernelBlurXPostprocess) {
  62246. this._kernelBlurXPostprocess.dispose();
  62247. this._kernelBlurXPostprocess = null;
  62248. }
  62249. if (this._kernelBlurYPostprocess) {
  62250. this._kernelBlurYPostprocess.dispose();
  62251. this._kernelBlurYPostprocess = null;
  62252. }
  62253. this._blurPostProcesses = [];
  62254. };
  62255. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  62256. if (this._shadowMap) {
  62257. this._shadowMap.dispose();
  62258. this._shadowMap = null;
  62259. }
  62260. this._disposeBlurPostProcesses();
  62261. };
  62262. /**
  62263. * Disposes the ShadowGenerator.
  62264. * Returns nothing.
  62265. */
  62266. ShadowGenerator.prototype.dispose = function () {
  62267. this._disposeRTTandPostProcesses();
  62268. if (this._light) {
  62269. this._light._shadowGenerator = null;
  62270. this._light._markMeshesAsLightDirty();
  62271. }
  62272. };
  62273. /**
  62274. * Serializes the shadow generator setup to a json object.
  62275. * @returns The serialized JSON object
  62276. */
  62277. ShadowGenerator.prototype.serialize = function () {
  62278. var serializationObject = {};
  62279. var shadowMap = this.getShadowMap();
  62280. if (!shadowMap) {
  62281. return serializationObject;
  62282. }
  62283. serializationObject.lightId = this._light.id;
  62284. serializationObject.mapSize = shadowMap.getRenderSize();
  62285. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  62286. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  62287. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62288. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62289. serializationObject.usePoissonSampling = this.usePoissonSampling;
  62290. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  62291. serializationObject.depthScale = this.depthScale;
  62292. serializationObject.darkness = this.getDarkness();
  62293. serializationObject.blurBoxOffset = this.blurBoxOffset;
  62294. serializationObject.blurKernel = this.blurKernel;
  62295. serializationObject.blurScale = this.blurScale;
  62296. serializationObject.useKernelBlur = this.useKernelBlur;
  62297. serializationObject.transparencyShadow = this._transparencyShadow;
  62298. serializationObject.bias = this.bias;
  62299. serializationObject.normalBias = this.normalBias;
  62300. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  62301. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  62302. serializationObject.filteringQuality = this.filteringQuality;
  62303. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  62304. serializationObject.renderList = [];
  62305. if (shadowMap.renderList) {
  62306. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  62307. var mesh = shadowMap.renderList[meshIndex];
  62308. serializationObject.renderList.push(mesh.id);
  62309. }
  62310. }
  62311. return serializationObject;
  62312. };
  62313. /**
  62314. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  62315. * @param parsedShadowGenerator The JSON object to parse
  62316. * @param scene The scene to create the shadow map for
  62317. * @returns The parsed shadow generator
  62318. */
  62319. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  62320. //casting to point light, as light is missing the position attr and typescript complains.
  62321. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  62322. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  62323. var shadowMap = shadowGenerator.getShadowMap();
  62324. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  62325. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  62326. meshes.forEach(function (mesh) {
  62327. if (!shadowMap) {
  62328. return;
  62329. }
  62330. if (!shadowMap.renderList) {
  62331. shadowMap.renderList = [];
  62332. }
  62333. shadowMap.renderList.push(mesh);
  62334. });
  62335. }
  62336. if (parsedShadowGenerator.usePoissonSampling) {
  62337. shadowGenerator.usePoissonSampling = true;
  62338. }
  62339. else if (parsedShadowGenerator.useExponentialShadowMap) {
  62340. shadowGenerator.useExponentialShadowMap = true;
  62341. }
  62342. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  62343. shadowGenerator.useBlurExponentialShadowMap = true;
  62344. }
  62345. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  62346. shadowGenerator.useCloseExponentialShadowMap = true;
  62347. }
  62348. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  62349. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  62350. }
  62351. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  62352. shadowGenerator.usePercentageCloserFiltering = true;
  62353. }
  62354. else if (parsedShadowGenerator.useContactHardeningShadow) {
  62355. shadowGenerator.useContactHardeningShadow = true;
  62356. }
  62357. if (parsedShadowGenerator.filteringQuality) {
  62358. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  62359. }
  62360. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  62361. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  62362. }
  62363. else if (parsedShadowGenerator.useVarianceShadowMap) {
  62364. shadowGenerator.useExponentialShadowMap = true;
  62365. }
  62366. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  62367. shadowGenerator.useBlurExponentialShadowMap = true;
  62368. }
  62369. if (parsedShadowGenerator.depthScale) {
  62370. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  62371. }
  62372. if (parsedShadowGenerator.blurScale) {
  62373. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  62374. }
  62375. if (parsedShadowGenerator.blurBoxOffset) {
  62376. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  62377. }
  62378. if (parsedShadowGenerator.useKernelBlur) {
  62379. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  62380. }
  62381. if (parsedShadowGenerator.blurKernel) {
  62382. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  62383. }
  62384. if (parsedShadowGenerator.bias !== undefined) {
  62385. shadowGenerator.bias = parsedShadowGenerator.bias;
  62386. }
  62387. if (parsedShadowGenerator.normalBias !== undefined) {
  62388. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  62389. }
  62390. if (parsedShadowGenerator.darkness) {
  62391. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  62392. }
  62393. if (parsedShadowGenerator.transparencyShadow) {
  62394. shadowGenerator.setTransparencyShadow(true);
  62395. }
  62396. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  62397. return shadowGenerator;
  62398. };
  62399. /**
  62400. * Shadow generator mode None: no filtering applied.
  62401. */
  62402. ShadowGenerator.FILTER_NONE = 0;
  62403. /**
  62404. * Shadow generator mode ESM: Exponential Shadow Mapping.
  62405. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62406. */
  62407. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  62408. /**
  62409. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  62410. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  62411. */
  62412. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  62413. /**
  62414. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  62415. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62416. */
  62417. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  62418. /**
  62419. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  62420. * edge artifacts on steep falloff.
  62421. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62422. */
  62423. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  62424. /**
  62425. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  62426. * edge artifacts on steep falloff.
  62427. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62428. */
  62429. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  62430. /**
  62431. * Shadow generator mode PCF: Percentage Closer Filtering
  62432. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62433. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  62434. */
  62435. ShadowGenerator.FILTER_PCF = 6;
  62436. /**
  62437. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  62438. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62439. * Contact Hardening
  62440. */
  62441. ShadowGenerator.FILTER_PCSS = 7;
  62442. /**
  62443. * Reserved for PCF and PCSS
  62444. * Highest Quality.
  62445. *
  62446. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  62447. *
  62448. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  62449. */
  62450. ShadowGenerator.QUALITY_HIGH = 0;
  62451. /**
  62452. * Reserved for PCF and PCSS
  62453. * Good tradeoff for quality/perf cross devices
  62454. *
  62455. * Execute PCF on a 3*3 kernel.
  62456. *
  62457. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  62458. */
  62459. ShadowGenerator.QUALITY_MEDIUM = 1;
  62460. /**
  62461. * Reserved for PCF and PCSS
  62462. * The lowest quality but the fastest.
  62463. *
  62464. * Execute PCF on a 1*1 kernel.
  62465. *
  62466. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  62467. */
  62468. ShadowGenerator.QUALITY_LOW = 2;
  62469. return ShadowGenerator;
  62470. }());
  62471. BABYLON.ShadowGenerator = ShadowGenerator;
  62472. })(BABYLON || (BABYLON = {}));
  62473. //# sourceMappingURL=babylon.shadowGenerator.js.map
  62474. "use strict";
  62475. var BABYLON;
  62476. (function (BABYLON) {
  62477. var DefaultLoadingScreen = /** @class */ (function () {
  62478. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  62479. if (_loadingText === void 0) { _loadingText = ""; }
  62480. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  62481. var _this = this;
  62482. this._renderingCanvas = _renderingCanvas;
  62483. this._loadingText = _loadingText;
  62484. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  62485. // Resize
  62486. this._resizeLoadingUI = function () {
  62487. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  62488. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  62489. if (!_this._loadingDiv) {
  62490. return;
  62491. }
  62492. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  62493. _this._loadingDiv.style.left = canvasRect.left + "px";
  62494. _this._loadingDiv.style.top = canvasRect.top + "px";
  62495. _this._loadingDiv.style.width = canvasRect.width + "px";
  62496. _this._loadingDiv.style.height = canvasRect.height + "px";
  62497. };
  62498. }
  62499. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62500. if (this._loadingDiv) {
  62501. // Do not add a loading screen if there is already one
  62502. return;
  62503. }
  62504. this._loadingDiv = document.createElement("div");
  62505. this._loadingDiv.id = "babylonjsLoadingDiv";
  62506. this._loadingDiv.style.opacity = "0";
  62507. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62508. this._loadingDiv.style.pointerEvents = "none";
  62509. // Loading text
  62510. this._loadingTextDiv = document.createElement("div");
  62511. this._loadingTextDiv.style.position = "absolute";
  62512. this._loadingTextDiv.style.left = "0";
  62513. this._loadingTextDiv.style.top = "50%";
  62514. this._loadingTextDiv.style.marginTop = "80px";
  62515. this._loadingTextDiv.style.width = "100%";
  62516. this._loadingTextDiv.style.height = "20px";
  62517. this._loadingTextDiv.style.fontFamily = "Arial";
  62518. this._loadingTextDiv.style.fontSize = "14px";
  62519. this._loadingTextDiv.style.color = "white";
  62520. this._loadingTextDiv.style.textAlign = "center";
  62521. this._loadingTextDiv.innerHTML = "Loading";
  62522. this._loadingDiv.appendChild(this._loadingTextDiv);
  62523. //set the predefined text
  62524. this._loadingTextDiv.innerHTML = this._loadingText;
  62525. // Generating keyframes
  62526. var style = document.createElement('style');
  62527. style.type = 'text/css';
  62528. 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 }";
  62529. style.innerHTML = keyFrames;
  62530. document.getElementsByTagName('head')[0].appendChild(style);
  62531. // Loading img
  62532. var imgBack = new Image();
  62533. 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";
  62534. imgBack.style.position = "absolute";
  62535. imgBack.style.left = "50%";
  62536. imgBack.style.top = "50%";
  62537. imgBack.style.marginLeft = "-60px";
  62538. imgBack.style.marginTop = "-60px";
  62539. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62540. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62541. imgBack.style.transformOrigin = "50% 50%";
  62542. imgBack.style.webkitTransformOrigin = "50% 50%";
  62543. this._loadingDiv.appendChild(imgBack);
  62544. this._resizeLoadingUI();
  62545. window.addEventListener("resize", this._resizeLoadingUI);
  62546. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62547. document.body.appendChild(this._loadingDiv);
  62548. this._loadingDiv.style.opacity = "1";
  62549. };
  62550. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62551. var _this = this;
  62552. if (!this._loadingDiv) {
  62553. return;
  62554. }
  62555. var onTransitionEnd = function () {
  62556. if (!_this._loadingDiv) {
  62557. return;
  62558. }
  62559. document.body.removeChild(_this._loadingDiv);
  62560. window.removeEventListener("resize", _this._resizeLoadingUI);
  62561. _this._loadingDiv = null;
  62562. };
  62563. this._loadingDiv.style.opacity = "0";
  62564. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62565. };
  62566. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62567. set: function (text) {
  62568. this._loadingText = text;
  62569. if (this._loadingTextDiv) {
  62570. this._loadingTextDiv.innerHTML = this._loadingText;
  62571. }
  62572. },
  62573. enumerable: true,
  62574. configurable: true
  62575. });
  62576. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62577. get: function () {
  62578. return this._loadingDivBackgroundColor;
  62579. },
  62580. set: function (color) {
  62581. this._loadingDivBackgroundColor = color;
  62582. if (!this._loadingDiv) {
  62583. return;
  62584. }
  62585. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62586. },
  62587. enumerable: true,
  62588. configurable: true
  62589. });
  62590. return DefaultLoadingScreen;
  62591. }());
  62592. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62593. })(BABYLON || (BABYLON = {}));
  62594. //# sourceMappingURL=babylon.loadingScreen.js.map
  62595. "use strict";
  62596. var BABYLON;
  62597. (function (BABYLON) {
  62598. var SceneLoaderProgressEvent = /** @class */ (function () {
  62599. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62600. this.lengthComputable = lengthComputable;
  62601. this.loaded = loaded;
  62602. this.total = total;
  62603. }
  62604. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62605. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62606. };
  62607. return SceneLoaderProgressEvent;
  62608. }());
  62609. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62610. var SceneLoader = /** @class */ (function () {
  62611. function SceneLoader() {
  62612. }
  62613. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62614. get: function () {
  62615. return 0;
  62616. },
  62617. enumerable: true,
  62618. configurable: true
  62619. });
  62620. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62621. get: function () {
  62622. return 1;
  62623. },
  62624. enumerable: true,
  62625. configurable: true
  62626. });
  62627. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62628. get: function () {
  62629. return 2;
  62630. },
  62631. enumerable: true,
  62632. configurable: true
  62633. });
  62634. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62635. get: function () {
  62636. return 3;
  62637. },
  62638. enumerable: true,
  62639. configurable: true
  62640. });
  62641. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62642. get: function () {
  62643. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62644. },
  62645. set: function (value) {
  62646. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62647. },
  62648. enumerable: true,
  62649. configurable: true
  62650. });
  62651. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62652. get: function () {
  62653. return SceneLoader._ShowLoadingScreen;
  62654. },
  62655. set: function (value) {
  62656. SceneLoader._ShowLoadingScreen = value;
  62657. },
  62658. enumerable: true,
  62659. configurable: true
  62660. });
  62661. Object.defineProperty(SceneLoader, "loggingLevel", {
  62662. get: function () {
  62663. return SceneLoader._loggingLevel;
  62664. },
  62665. set: function (value) {
  62666. SceneLoader._loggingLevel = value;
  62667. },
  62668. enumerable: true,
  62669. configurable: true
  62670. });
  62671. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62672. get: function () {
  62673. return SceneLoader._CleanBoneMatrixWeights;
  62674. },
  62675. set: function (value) {
  62676. SceneLoader._CleanBoneMatrixWeights = value;
  62677. },
  62678. enumerable: true,
  62679. configurable: true
  62680. });
  62681. SceneLoader._getDefaultPlugin = function () {
  62682. return SceneLoader._registeredPlugins[".babylon"];
  62683. };
  62684. SceneLoader._getPluginForExtension = function (extension) {
  62685. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62686. if (registeredPlugin) {
  62687. return registeredPlugin;
  62688. }
  62689. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62690. return SceneLoader._getDefaultPlugin();
  62691. };
  62692. SceneLoader._getPluginForDirectLoad = function (data) {
  62693. for (var extension in SceneLoader._registeredPlugins) {
  62694. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62695. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62696. return SceneLoader._registeredPlugins[extension];
  62697. }
  62698. }
  62699. return SceneLoader._getDefaultPlugin();
  62700. };
  62701. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62702. if (sceneFilename.name) {
  62703. sceneFilename = sceneFilename.name;
  62704. }
  62705. var queryStringPosition = sceneFilename.indexOf("?");
  62706. if (queryStringPosition !== -1) {
  62707. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62708. }
  62709. var dotPosition = sceneFilename.lastIndexOf(".");
  62710. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62711. return SceneLoader._getPluginForExtension(extension);
  62712. };
  62713. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62714. SceneLoader._getDirectLoad = function (sceneFilename) {
  62715. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62716. return sceneFilename.substr(5);
  62717. }
  62718. return null;
  62719. };
  62720. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62721. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62722. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62723. var plugin;
  62724. if (registeredPlugin.plugin.createPlugin) {
  62725. plugin = registeredPlugin.plugin.createPlugin();
  62726. }
  62727. else {
  62728. plugin = registeredPlugin.plugin;
  62729. }
  62730. var useArrayBuffer = registeredPlugin.isBinary;
  62731. var database;
  62732. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62733. var dataCallback = function (data, responseURL) {
  62734. if (scene.isDisposed) {
  62735. onError("Scene has been disposed");
  62736. return;
  62737. }
  62738. scene.database = database;
  62739. onSuccess(plugin, data, responseURL);
  62740. };
  62741. var request = null;
  62742. var pluginDisposed = false;
  62743. var onDisposeObservable = plugin.onDisposeObservable;
  62744. if (onDisposeObservable) {
  62745. onDisposeObservable.add(function () {
  62746. pluginDisposed = true;
  62747. if (request) {
  62748. request.abort();
  62749. request = null;
  62750. }
  62751. onDispose();
  62752. });
  62753. }
  62754. var manifestChecked = function () {
  62755. if (pluginDisposed) {
  62756. return;
  62757. }
  62758. var url = rootUrl + sceneFilename;
  62759. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62760. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62761. } : undefined, database, useArrayBuffer, function (request, exception) {
  62762. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62763. });
  62764. };
  62765. if (directLoad) {
  62766. dataCallback(directLoad);
  62767. return plugin;
  62768. }
  62769. if (rootUrl.indexOf("file:") === -1) {
  62770. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  62771. if (canUseOfflineSupport) {
  62772. // Also check for exceptions
  62773. var exceptionFound = false;
  62774. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  62775. var regex = _a[_i];
  62776. if (regex.test(rootUrl + sceneFilename)) {
  62777. exceptionFound = true;
  62778. break;
  62779. }
  62780. }
  62781. canUseOfflineSupport = !exceptionFound;
  62782. }
  62783. if (canUseOfflineSupport) {
  62784. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62785. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62786. }
  62787. else {
  62788. manifestChecked();
  62789. }
  62790. }
  62791. else {
  62792. var fileOrString = sceneFilename;
  62793. if (fileOrString.name) {
  62794. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62795. }
  62796. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62797. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62798. }
  62799. else {
  62800. onError("Unable to find file named " + sceneFilename);
  62801. }
  62802. }
  62803. return plugin;
  62804. };
  62805. // Public functions
  62806. SceneLoader.GetPluginForExtension = function (extension) {
  62807. return SceneLoader._getPluginForExtension(extension).plugin;
  62808. };
  62809. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62810. return !!SceneLoader._registeredPlugins[extension];
  62811. };
  62812. SceneLoader.RegisterPlugin = function (plugin) {
  62813. if (typeof plugin.extensions === "string") {
  62814. var extension = plugin.extensions;
  62815. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62816. plugin: plugin,
  62817. isBinary: false
  62818. };
  62819. }
  62820. else {
  62821. var extensions = plugin.extensions;
  62822. Object.keys(extensions).forEach(function (extension) {
  62823. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62824. plugin: plugin,
  62825. isBinary: extensions[extension].isBinary
  62826. };
  62827. });
  62828. }
  62829. };
  62830. /**
  62831. * Import meshes into a scene
  62832. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62833. * @param rootUrl a string that defines the root url for scene and resources
  62834. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62835. * @param scene the instance of BABYLON.Scene to append to
  62836. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62837. * @param onProgress a callback with a progress event for each file being loaded
  62838. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62839. * @param pluginExtension the extension used to determine the plugin
  62840. * @returns The loaded plugin
  62841. */
  62842. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62843. if (onSuccess === void 0) { onSuccess = null; }
  62844. if (onProgress === void 0) { onProgress = null; }
  62845. if (onError === void 0) { onError = null; }
  62846. if (pluginExtension === void 0) { pluginExtension = null; }
  62847. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62848. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62849. return null;
  62850. }
  62851. var loadingToken = {};
  62852. scene._addPendingData(loadingToken);
  62853. var disposeHandler = function () {
  62854. scene._removePendingData(loadingToken);
  62855. };
  62856. var errorHandler = function (message, exception) {
  62857. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62858. if (onError) {
  62859. onError(scene, errorMessage, exception);
  62860. }
  62861. else {
  62862. BABYLON.Tools.Error(errorMessage);
  62863. // should the exception be thrown?
  62864. }
  62865. disposeHandler();
  62866. };
  62867. var progressHandler = onProgress ? function (event) {
  62868. try {
  62869. onProgress(event);
  62870. }
  62871. catch (e) {
  62872. errorHandler("Error in onProgress callback", e);
  62873. }
  62874. } : undefined;
  62875. var successHandler = function (meshes, particleSystems, skeletons) {
  62876. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62877. if (onSuccess) {
  62878. try {
  62879. onSuccess(meshes, particleSystems, skeletons);
  62880. }
  62881. catch (e) {
  62882. errorHandler("Error in onSuccess callback", e);
  62883. }
  62884. }
  62885. scene._removePendingData(loadingToken);
  62886. };
  62887. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62888. if (plugin.rewriteRootURL) {
  62889. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62890. }
  62891. if (sceneFilename === "") {
  62892. if (sceneFilename === "") {
  62893. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62894. }
  62895. }
  62896. if (plugin.importMesh) {
  62897. var syncedPlugin = plugin;
  62898. var meshes = new Array();
  62899. var particleSystems = new Array();
  62900. var skeletons = new Array();
  62901. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62902. return;
  62903. }
  62904. scene.loadingPluginName = plugin.name;
  62905. successHandler(meshes, particleSystems, skeletons);
  62906. }
  62907. else {
  62908. var asyncedPlugin = plugin;
  62909. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62910. scene.loadingPluginName = plugin.name;
  62911. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62912. }).catch(function (error) {
  62913. errorHandler(error.message, error);
  62914. });
  62915. }
  62916. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62917. };
  62918. /**
  62919. * Import meshes into a scene
  62920. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62921. * @param rootUrl a string that defines the root url for scene and resources
  62922. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62923. * @param scene the instance of BABYLON.Scene to append to
  62924. * @param onProgress a callback with a progress event for each file being loaded
  62925. * @param pluginExtension the extension used to determine the plugin
  62926. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62927. */
  62928. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62929. if (onProgress === void 0) { onProgress = null; }
  62930. if (pluginExtension === void 0) { pluginExtension = null; }
  62931. return new Promise(function (resolve, reject) {
  62932. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62933. resolve({
  62934. meshes: meshes,
  62935. particleSystems: particleSystems,
  62936. skeletons: skeletons
  62937. });
  62938. }, onProgress, function (scene, message, exception) {
  62939. reject(exception || new Error(message));
  62940. });
  62941. });
  62942. };
  62943. /**
  62944. * Load a scene
  62945. * @param rootUrl a string that defines the root url for scene and resources
  62946. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62947. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62948. * @param onSuccess a callback with the scene when import succeeds
  62949. * @param onProgress a callback with a progress event for each file being loaded
  62950. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62951. * @param pluginExtension the extension used to determine the plugin
  62952. * @returns The loaded plugin
  62953. */
  62954. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62955. if (onSuccess === void 0) { onSuccess = null; }
  62956. if (onProgress === void 0) { onProgress = null; }
  62957. if (onError === void 0) { onError = null; }
  62958. if (pluginExtension === void 0) { pluginExtension = null; }
  62959. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62960. };
  62961. /**
  62962. * Load a scene
  62963. * @param rootUrl a string that defines the root url for scene and resources
  62964. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62965. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62966. * @param onProgress a callback with a progress event for each file being loaded
  62967. * @param pluginExtension the extension used to determine the plugin
  62968. * @returns The loaded scene
  62969. */
  62970. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  62971. if (onProgress === void 0) { onProgress = null; }
  62972. if (pluginExtension === void 0) { pluginExtension = null; }
  62973. return new Promise(function (resolve, reject) {
  62974. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  62975. resolve(scene);
  62976. }, onProgress, function (scene, message, exception) {
  62977. reject(exception || new Error(message));
  62978. }, pluginExtension);
  62979. });
  62980. };
  62981. /**
  62982. * Append a scene
  62983. * @param rootUrl a string that defines the root url for scene and resources
  62984. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62985. * @param scene is the instance of BABYLON.Scene to append to
  62986. * @param onSuccess a callback with the scene when import succeeds
  62987. * @param onProgress a callback with a progress event for each file being loaded
  62988. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62989. * @param pluginExtension the extension used to determine the plugin
  62990. * @returns The loaded plugin
  62991. */
  62992. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62993. if (onSuccess === void 0) { onSuccess = null; }
  62994. if (onProgress === void 0) { onProgress = null; }
  62995. if (onError === void 0) { onError = null; }
  62996. if (pluginExtension === void 0) { pluginExtension = null; }
  62997. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62998. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62999. return null;
  63000. }
  63001. if (SceneLoader.ShowLoadingScreen) {
  63002. scene.getEngine().displayLoadingUI();
  63003. }
  63004. var loadingToken = {};
  63005. scene._addPendingData(loadingToken);
  63006. var disposeHandler = function () {
  63007. scene._removePendingData(loadingToken);
  63008. scene.getEngine().hideLoadingUI();
  63009. };
  63010. var errorHandler = function (message, exception) {
  63011. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63012. if (onError) {
  63013. onError(scene, errorMessage, exception);
  63014. }
  63015. else {
  63016. BABYLON.Tools.Error(errorMessage);
  63017. // should the exception be thrown?
  63018. }
  63019. disposeHandler();
  63020. };
  63021. var progressHandler = onProgress ? function (event) {
  63022. try {
  63023. onProgress(event);
  63024. }
  63025. catch (e) {
  63026. errorHandler("Error in onProgress callback", e);
  63027. }
  63028. } : undefined;
  63029. var successHandler = function () {
  63030. if (onSuccess) {
  63031. try {
  63032. onSuccess(scene);
  63033. }
  63034. catch (e) {
  63035. errorHandler("Error in onSuccess callback", e);
  63036. }
  63037. }
  63038. scene._removePendingData(loadingToken);
  63039. };
  63040. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63041. if (sceneFilename === "") {
  63042. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  63043. }
  63044. if (plugin.load) {
  63045. var syncedPlugin = plugin;
  63046. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  63047. return;
  63048. }
  63049. scene.loadingPluginName = plugin.name;
  63050. successHandler();
  63051. }
  63052. else {
  63053. var asyncedPlugin = plugin;
  63054. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  63055. scene.loadingPluginName = plugin.name;
  63056. successHandler();
  63057. }).catch(function (error) {
  63058. errorHandler(error.message, error);
  63059. });
  63060. }
  63061. if (SceneLoader.ShowLoadingScreen) {
  63062. scene.executeWhenReady(function () {
  63063. scene.getEngine().hideLoadingUI();
  63064. });
  63065. }
  63066. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63067. };
  63068. /**
  63069. * Append a scene
  63070. * @param rootUrl a string that defines the root url for scene and resources
  63071. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63072. * @param scene is the instance of BABYLON.Scene to append to
  63073. * @param onProgress a callback with a progress event for each file being loaded
  63074. * @param pluginExtension the extension used to determine the plugin
  63075. * @returns The given scene
  63076. */
  63077. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63078. if (onProgress === void 0) { onProgress = null; }
  63079. if (pluginExtension === void 0) { pluginExtension = null; }
  63080. return new Promise(function (resolve, reject) {
  63081. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  63082. resolve(scene);
  63083. }, onProgress, function (scene, message, exception) {
  63084. reject(exception || new Error(message));
  63085. }, pluginExtension);
  63086. });
  63087. };
  63088. /**
  63089. * Load a scene into an asset container
  63090. * @param rootUrl a string that defines the root url for scene and resources
  63091. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63092. * @param scene is the instance of BABYLON.Scene to append to
  63093. * @param onSuccess a callback with the scene when import succeeds
  63094. * @param onProgress a callback with a progress event for each file being loaded
  63095. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63096. * @param pluginExtension the extension used to determine the plugin
  63097. * @returns The loaded plugin
  63098. */
  63099. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63100. if (onSuccess === void 0) { onSuccess = null; }
  63101. if (onProgress === void 0) { onProgress = null; }
  63102. if (onError === void 0) { onError = null; }
  63103. if (pluginExtension === void 0) { pluginExtension = null; }
  63104. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63105. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63106. return null;
  63107. }
  63108. var loadingToken = {};
  63109. scene._addPendingData(loadingToken);
  63110. var disposeHandler = function () {
  63111. scene._removePendingData(loadingToken);
  63112. };
  63113. var errorHandler = function (message, exception) {
  63114. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63115. if (onError) {
  63116. onError(scene, errorMessage, exception);
  63117. }
  63118. else {
  63119. BABYLON.Tools.Error(errorMessage);
  63120. // should the exception be thrown?
  63121. }
  63122. disposeHandler();
  63123. };
  63124. var progressHandler = onProgress ? function (event) {
  63125. try {
  63126. onProgress(event);
  63127. }
  63128. catch (e) {
  63129. errorHandler("Error in onProgress callback", e);
  63130. }
  63131. } : undefined;
  63132. var successHandler = function (assets) {
  63133. if (onSuccess) {
  63134. try {
  63135. onSuccess(assets);
  63136. }
  63137. catch (e) {
  63138. errorHandler("Error in onSuccess callback", e);
  63139. }
  63140. }
  63141. scene._removePendingData(loadingToken);
  63142. };
  63143. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63144. if (plugin.loadAssetContainer) {
  63145. var syncedPlugin = plugin;
  63146. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  63147. if (!assetContainer) {
  63148. return;
  63149. }
  63150. scene.loadingPluginName = plugin.name;
  63151. successHandler(assetContainer);
  63152. }
  63153. else if (plugin.loadAssetContainerAsync) {
  63154. var asyncedPlugin = plugin;
  63155. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  63156. scene.loadingPluginName = plugin.name;
  63157. successHandler(assetContainer);
  63158. }).catch(function (error) {
  63159. errorHandler(error.message, error);
  63160. });
  63161. }
  63162. else {
  63163. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  63164. }
  63165. if (SceneLoader.ShowLoadingScreen) {
  63166. scene.executeWhenReady(function () {
  63167. scene.getEngine().hideLoadingUI();
  63168. });
  63169. }
  63170. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63171. };
  63172. /**
  63173. * Load a scene into an asset container
  63174. * @param rootUrl a string that defines the root url for scene and resources
  63175. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63176. * @param scene is the instance of BABYLON.Scene to append to
  63177. * @param onProgress a callback with a progress event for each file being loaded
  63178. * @param pluginExtension the extension used to determine the plugin
  63179. * @returns The loaded asset container
  63180. */
  63181. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63182. if (onProgress === void 0) { onProgress = null; }
  63183. if (pluginExtension === void 0) { pluginExtension = null; }
  63184. return new Promise(function (resolve, reject) {
  63185. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  63186. resolve(assetContainer);
  63187. }, onProgress, function (scene, message, exception) {
  63188. reject(exception || new Error(message));
  63189. }, pluginExtension);
  63190. });
  63191. };
  63192. // Flags
  63193. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  63194. SceneLoader._ShowLoadingScreen = true;
  63195. SceneLoader._CleanBoneMatrixWeights = false;
  63196. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  63197. // Members
  63198. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  63199. SceneLoader._registeredPlugins = {};
  63200. return SceneLoader;
  63201. }());
  63202. BABYLON.SceneLoader = SceneLoader;
  63203. ;
  63204. })(BABYLON || (BABYLON = {}));
  63205. //# sourceMappingURL=babylon.sceneLoader.js.map
  63206. "use strict";
  63207. var BABYLON;
  63208. (function (BABYLON) {
  63209. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  63210. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63211. var parsedMaterial = parsedData.materials[index];
  63212. if (parsedMaterial.id === id) {
  63213. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63214. }
  63215. }
  63216. return null;
  63217. };
  63218. var isDescendantOf = function (mesh, names, hierarchyIds) {
  63219. for (var i in names) {
  63220. if (mesh.name === names[i]) {
  63221. hierarchyIds.push(mesh.id);
  63222. return true;
  63223. }
  63224. }
  63225. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  63226. hierarchyIds.push(mesh.id);
  63227. return true;
  63228. }
  63229. return false;
  63230. };
  63231. var logOperation = function (operation, producer) {
  63232. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  63233. };
  63234. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  63235. if (addToScene === void 0) { addToScene = false; }
  63236. var container = new BABYLON.AssetContainer(scene);
  63237. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63238. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63239. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63240. // and avoid problems with multiple concurrent .babylon loads.
  63241. var log = "importScene has failed JSON parse";
  63242. try {
  63243. var parsedData = JSON.parse(data);
  63244. log = "";
  63245. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63246. var index;
  63247. var cache;
  63248. // Lights
  63249. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  63250. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  63251. var parsedLight = parsedData.lights[index];
  63252. var light = BABYLON.Light.Parse(parsedLight, scene);
  63253. if (light) {
  63254. container.lights.push(light);
  63255. log += (index === 0 ? "\n\tLights:" : "");
  63256. log += "\n\t\t" + light.toString(fullDetails);
  63257. }
  63258. }
  63259. }
  63260. // Animations
  63261. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  63262. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  63263. var parsedAnimation = parsedData.animations[index];
  63264. var animation = BABYLON.Animation.Parse(parsedAnimation);
  63265. scene.animations.push(animation);
  63266. container.animations.push(animation);
  63267. log += (index === 0 ? "\n\tAnimations:" : "");
  63268. log += "\n\t\t" + animation.toString(fullDetails);
  63269. }
  63270. }
  63271. // Materials
  63272. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  63273. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63274. var parsedMaterial = parsedData.materials[index];
  63275. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63276. container.materials.push(mat);
  63277. log += (index === 0 ? "\n\tMaterials:" : "");
  63278. log += "\n\t\t" + mat.toString(fullDetails);
  63279. }
  63280. }
  63281. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63282. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  63283. var parsedMultiMaterial = parsedData.multiMaterials[index];
  63284. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63285. container.multiMaterials.push(mmat);
  63286. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  63287. log += "\n\t\t" + mmat.toString(fullDetails);
  63288. }
  63289. }
  63290. // Morph targets
  63291. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  63292. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  63293. var managerData = _a[_i];
  63294. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  63295. }
  63296. }
  63297. // Skeletons
  63298. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63299. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  63300. var parsedSkeleton = parsedData.skeletons[index];
  63301. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63302. container.skeletons.push(skeleton);
  63303. log += (index === 0 ? "\n\tSkeletons:" : "");
  63304. log += "\n\t\t" + skeleton.toString(fullDetails);
  63305. }
  63306. }
  63307. // Geometries
  63308. var geometries = parsedData.geometries;
  63309. if (geometries !== undefined && geometries !== null) {
  63310. var addedGeometry = new Array();
  63311. // Boxes
  63312. var boxes = geometries.boxes;
  63313. if (boxes !== undefined && boxes !== null) {
  63314. for (index = 0, cache = boxes.length; index < cache; index++) {
  63315. var parsedBox = boxes[index];
  63316. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  63317. }
  63318. }
  63319. // Spheres
  63320. var spheres = geometries.spheres;
  63321. if (spheres !== undefined && spheres !== null) {
  63322. for (index = 0, cache = spheres.length; index < cache; index++) {
  63323. var parsedSphere = spheres[index];
  63324. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  63325. }
  63326. }
  63327. // Cylinders
  63328. var cylinders = geometries.cylinders;
  63329. if (cylinders !== undefined && cylinders !== null) {
  63330. for (index = 0, cache = cylinders.length; index < cache; index++) {
  63331. var parsedCylinder = cylinders[index];
  63332. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  63333. }
  63334. }
  63335. // Toruses
  63336. var toruses = geometries.toruses;
  63337. if (toruses !== undefined && toruses !== null) {
  63338. for (index = 0, cache = toruses.length; index < cache; index++) {
  63339. var parsedTorus = toruses[index];
  63340. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  63341. }
  63342. }
  63343. // Grounds
  63344. var grounds = geometries.grounds;
  63345. if (grounds !== undefined && grounds !== null) {
  63346. for (index = 0, cache = grounds.length; index < cache; index++) {
  63347. var parsedGround = grounds[index];
  63348. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  63349. }
  63350. }
  63351. // Planes
  63352. var planes = geometries.planes;
  63353. if (planes !== undefined && planes !== null) {
  63354. for (index = 0, cache = planes.length; index < cache; index++) {
  63355. var parsedPlane = planes[index];
  63356. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  63357. }
  63358. }
  63359. // TorusKnots
  63360. var torusKnots = geometries.torusKnots;
  63361. if (torusKnots !== undefined && torusKnots !== null) {
  63362. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  63363. var parsedTorusKnot = torusKnots[index];
  63364. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  63365. }
  63366. }
  63367. // VertexData
  63368. var vertexData = geometries.vertexData;
  63369. if (vertexData !== undefined && vertexData !== null) {
  63370. for (index = 0, cache = vertexData.length; index < cache; index++) {
  63371. var parsedVertexData = vertexData[index];
  63372. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  63373. }
  63374. }
  63375. addedGeometry.forEach(function (g) {
  63376. if (g) {
  63377. container.geometries.push(g);
  63378. }
  63379. });
  63380. }
  63381. // Transform nodes
  63382. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  63383. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  63384. var parsedTransformNode = parsedData.transformNodes[index];
  63385. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  63386. container.transformNodes.push(node);
  63387. }
  63388. }
  63389. // Meshes
  63390. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63391. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63392. var parsedMesh = parsedData.meshes[index];
  63393. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63394. container.meshes.push(mesh);
  63395. log += (index === 0 ? "\n\tMeshes:" : "");
  63396. log += "\n\t\t" + mesh.toString(fullDetails);
  63397. }
  63398. }
  63399. // Cameras
  63400. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  63401. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  63402. var parsedCamera = parsedData.cameras[index];
  63403. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  63404. container.cameras.push(camera);
  63405. log += (index === 0 ? "\n\tCameras:" : "");
  63406. log += "\n\t\t" + camera.toString(fullDetails);
  63407. }
  63408. }
  63409. // Browsing all the graph to connect the dots
  63410. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  63411. var camera = scene.cameras[index];
  63412. if (camera._waitingParentId) {
  63413. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  63414. camera._waitingParentId = null;
  63415. }
  63416. }
  63417. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63418. var light_1 = scene.lights[index];
  63419. if (light_1 && light_1._waitingParentId) {
  63420. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  63421. light_1._waitingParentId = null;
  63422. }
  63423. }
  63424. // Sounds
  63425. // TODO: add sound
  63426. var loadedSounds = [];
  63427. var loadedSound;
  63428. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  63429. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  63430. var parsedSound = parsedData.sounds[index];
  63431. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63432. if (!parsedSound.url)
  63433. parsedSound.url = parsedSound.name;
  63434. if (!loadedSounds[parsedSound.url]) {
  63435. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  63436. loadedSounds[parsedSound.url] = loadedSound;
  63437. container.sounds.push(loadedSound);
  63438. }
  63439. else {
  63440. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  63441. }
  63442. }
  63443. else {
  63444. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  63445. }
  63446. }
  63447. }
  63448. loadedSounds = [];
  63449. // Connect parents & children and parse actions
  63450. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  63451. var transformNode = scene.transformNodes[index];
  63452. if (transformNode._waitingParentId) {
  63453. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  63454. transformNode._waitingParentId = null;
  63455. }
  63456. }
  63457. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63458. var mesh = scene.meshes[index];
  63459. if (mesh._waitingParentId) {
  63460. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  63461. mesh._waitingParentId = null;
  63462. }
  63463. if (mesh._waitingActions) {
  63464. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  63465. mesh._waitingActions = null;
  63466. }
  63467. }
  63468. // freeze world matrix application
  63469. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63470. var currentMesh = scene.meshes[index];
  63471. if (currentMesh._waitingFreezeWorldMatrix) {
  63472. currentMesh.freezeWorldMatrix();
  63473. currentMesh._waitingFreezeWorldMatrix = null;
  63474. }
  63475. else {
  63476. currentMesh.computeWorldMatrix(true);
  63477. }
  63478. }
  63479. // Particles Systems
  63480. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63481. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63482. var parsedParticleSystem = parsedData.particleSystems[index];
  63483. if (parsedParticleSystem.activeParticleCount) {
  63484. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63485. container.particleSystems.push(ps);
  63486. }
  63487. else {
  63488. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63489. container.particleSystems.push(ps);
  63490. }
  63491. }
  63492. }
  63493. // Lens flares
  63494. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  63495. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  63496. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  63497. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  63498. container.lensFlareSystems.push(lf);
  63499. }
  63500. }
  63501. // Shadows
  63502. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  63503. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  63504. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  63505. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  63506. container.shadowGenerators.push(sg);
  63507. }
  63508. }
  63509. // Lights exclusions / inclusions
  63510. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63511. var light_2 = scene.lights[index];
  63512. // Excluded check
  63513. if (light_2._excludedMeshesIds.length > 0) {
  63514. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63515. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63516. if (excludedMesh) {
  63517. light_2.excludedMeshes.push(excludedMesh);
  63518. }
  63519. }
  63520. light_2._excludedMeshesIds = [];
  63521. }
  63522. // Included check
  63523. if (light_2._includedOnlyMeshesIds.length > 0) {
  63524. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63525. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63526. if (includedOnlyMesh) {
  63527. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63528. }
  63529. }
  63530. light_2._includedOnlyMeshesIds = [];
  63531. }
  63532. }
  63533. // Actions (scene)
  63534. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63535. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63536. }
  63537. if (!addToScene) {
  63538. container.removeAllFromScene();
  63539. }
  63540. }
  63541. catch (err) {
  63542. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63543. if (onError) {
  63544. onError(msg, err);
  63545. }
  63546. else {
  63547. BABYLON.Tools.Log(msg);
  63548. throw err;
  63549. }
  63550. }
  63551. finally {
  63552. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63553. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63554. }
  63555. }
  63556. return container;
  63557. };
  63558. BABYLON.SceneLoader.RegisterPlugin({
  63559. name: "babylon.js",
  63560. extensions: ".babylon",
  63561. canDirectLoad: function (data) {
  63562. if (data.indexOf("babylon") !== -1) {
  63563. return true;
  63564. }
  63565. return false;
  63566. },
  63567. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63568. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63569. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63570. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63571. // and avoid problems with multiple concurrent .babylon loads.
  63572. var log = "importMesh has failed JSON parse";
  63573. try {
  63574. var parsedData = JSON.parse(data);
  63575. log = "";
  63576. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63577. if (!meshesNames) {
  63578. meshesNames = null;
  63579. }
  63580. else if (!Array.isArray(meshesNames)) {
  63581. meshesNames = [meshesNames];
  63582. }
  63583. var hierarchyIds = new Array();
  63584. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63585. var loadedSkeletonsIds = [];
  63586. var loadedMaterialsIds = [];
  63587. var index;
  63588. var cache;
  63589. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63590. var parsedMesh = parsedData.meshes[index];
  63591. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63592. if (meshesNames !== null) {
  63593. // Remove found mesh name from list.
  63594. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63595. }
  63596. //Geometry?
  63597. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63598. //does the file contain geometries?
  63599. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63600. //find the correct geometry and add it to the scene
  63601. var found = false;
  63602. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63603. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63604. return;
  63605. }
  63606. else {
  63607. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63608. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63609. switch (geometryType) {
  63610. case "boxes":
  63611. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63612. break;
  63613. case "spheres":
  63614. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63615. break;
  63616. case "cylinders":
  63617. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63618. break;
  63619. case "toruses":
  63620. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63621. break;
  63622. case "grounds":
  63623. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63624. break;
  63625. case "planes":
  63626. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63627. break;
  63628. case "torusKnots":
  63629. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63630. break;
  63631. case "vertexData":
  63632. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63633. break;
  63634. }
  63635. found = true;
  63636. }
  63637. });
  63638. }
  63639. });
  63640. if (found === false) {
  63641. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63642. }
  63643. }
  63644. }
  63645. // Material ?
  63646. if (parsedMesh.materialId) {
  63647. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63648. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63649. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63650. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63651. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63652. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63653. var subMatId = parsedMultiMaterial.materials[matIndex];
  63654. loadedMaterialsIds.push(subMatId);
  63655. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63656. if (mat) {
  63657. log += "\n\tMaterial " + mat.toString(fullDetails);
  63658. }
  63659. }
  63660. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63661. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63662. if (mmat) {
  63663. materialFound = true;
  63664. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63665. }
  63666. break;
  63667. }
  63668. }
  63669. }
  63670. if (materialFound === false) {
  63671. loadedMaterialsIds.push(parsedMesh.materialId);
  63672. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63673. if (!mat) {
  63674. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63675. }
  63676. else {
  63677. log += "\n\tMaterial " + mat.toString(fullDetails);
  63678. }
  63679. }
  63680. }
  63681. // Skeleton ?
  63682. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63683. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63684. if (skeletonAlreadyLoaded === false) {
  63685. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63686. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63687. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63688. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63689. skeletons.push(skeleton);
  63690. loadedSkeletonsIds.push(parsedSkeleton.id);
  63691. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63692. }
  63693. }
  63694. }
  63695. }
  63696. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63697. meshes.push(mesh);
  63698. log += "\n\tMesh " + mesh.toString(fullDetails);
  63699. }
  63700. }
  63701. // Connecting parents
  63702. var currentMesh;
  63703. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63704. currentMesh = scene.meshes[index];
  63705. if (currentMesh._waitingParentId) {
  63706. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63707. currentMesh._waitingParentId = null;
  63708. }
  63709. }
  63710. // freeze and compute world matrix application
  63711. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63712. currentMesh = scene.meshes[index];
  63713. if (currentMesh._waitingFreezeWorldMatrix) {
  63714. currentMesh.freezeWorldMatrix();
  63715. currentMesh._waitingFreezeWorldMatrix = null;
  63716. }
  63717. else {
  63718. currentMesh.computeWorldMatrix(true);
  63719. }
  63720. }
  63721. }
  63722. // Particles
  63723. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63724. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63725. var parsedParticleSystem = parsedData.particleSystems[index];
  63726. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63727. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63728. }
  63729. }
  63730. }
  63731. return true;
  63732. }
  63733. catch (err) {
  63734. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63735. if (onError) {
  63736. onError(msg, err);
  63737. }
  63738. else {
  63739. BABYLON.Tools.Log(msg);
  63740. throw err;
  63741. }
  63742. }
  63743. finally {
  63744. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63745. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63746. }
  63747. }
  63748. return false;
  63749. },
  63750. load: function (scene, data, rootUrl, onError) {
  63751. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63752. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63753. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63754. // and avoid problems with multiple concurrent .babylon loads.
  63755. var log = "importScene has failed JSON parse";
  63756. try {
  63757. var parsedData = JSON.parse(data);
  63758. log = "";
  63759. // Scene
  63760. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63761. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63762. }
  63763. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63764. scene.autoClear = parsedData.autoClear;
  63765. }
  63766. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63767. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63768. }
  63769. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63770. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63771. }
  63772. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63773. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63774. }
  63775. // Fog
  63776. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63777. scene.fogMode = parsedData.fogMode;
  63778. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63779. scene.fogStart = parsedData.fogStart;
  63780. scene.fogEnd = parsedData.fogEnd;
  63781. scene.fogDensity = parsedData.fogDensity;
  63782. log += "\tFog mode for scene: ";
  63783. switch (scene.fogMode) {
  63784. // getters not compiling, so using hardcoded
  63785. case 1:
  63786. log += "exp\n";
  63787. break;
  63788. case 2:
  63789. log += "exp2\n";
  63790. break;
  63791. case 3:
  63792. log += "linear\n";
  63793. break;
  63794. }
  63795. }
  63796. //Physics
  63797. if (parsedData.physicsEnabled) {
  63798. var physicsPlugin;
  63799. if (parsedData.physicsEngine === "cannon") {
  63800. physicsPlugin = new BABYLON.CannonJSPlugin();
  63801. }
  63802. else if (parsedData.physicsEngine === "oimo") {
  63803. physicsPlugin = new BABYLON.OimoJSPlugin();
  63804. }
  63805. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63806. //else - default engine, which is currently oimo
  63807. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63808. scene.enablePhysics(physicsGravity, physicsPlugin);
  63809. }
  63810. // Metadata
  63811. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63812. scene.metadata = parsedData.metadata;
  63813. }
  63814. //collisions, if defined. otherwise, default is true
  63815. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63816. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63817. }
  63818. scene.workerCollisions = !!parsedData.workerCollisions;
  63819. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63820. if (!container) {
  63821. return false;
  63822. }
  63823. if (parsedData.autoAnimate) {
  63824. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63825. }
  63826. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63827. scene.setActiveCameraByID(parsedData.activeCameraID);
  63828. }
  63829. // Environment texture
  63830. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63831. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63832. if (parsedData.createDefaultSkybox === true) {
  63833. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63834. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63835. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63836. }
  63837. }
  63838. // Finish
  63839. return true;
  63840. }
  63841. catch (err) {
  63842. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63843. if (onError) {
  63844. onError(msg, err);
  63845. }
  63846. else {
  63847. BABYLON.Tools.Log(msg);
  63848. throw err;
  63849. }
  63850. }
  63851. finally {
  63852. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63853. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63854. }
  63855. }
  63856. return false;
  63857. },
  63858. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63859. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63860. return container;
  63861. }
  63862. });
  63863. })(BABYLON || (BABYLON = {}));
  63864. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63865. "use strict";
  63866. var BABYLON;
  63867. (function (BABYLON) {
  63868. var FilesInput = /** @class */ (function () {
  63869. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63870. this.onProcessFileCallback = function () { return true; };
  63871. this._engine = engine;
  63872. this._currentScene = scene;
  63873. this._sceneLoadedCallback = sceneLoadedCallback;
  63874. this._progressCallback = progressCallback;
  63875. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63876. this._textureLoadingCallback = textureLoadingCallback;
  63877. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63878. this._onReloadCallback = onReloadCallback;
  63879. this._errorCallback = errorCallback;
  63880. }
  63881. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63882. var _this = this;
  63883. if (elementToMonitor) {
  63884. this._elementToMonitor = elementToMonitor;
  63885. this._dragEnterHandler = function (e) { _this.drag(e); };
  63886. this._dragOverHandler = function (e) { _this.drag(e); };
  63887. this._dropHandler = function (e) { _this.drop(e); };
  63888. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63889. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63890. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63891. }
  63892. };
  63893. FilesInput.prototype.dispose = function () {
  63894. if (!this._elementToMonitor) {
  63895. return;
  63896. }
  63897. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63898. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63899. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63900. };
  63901. FilesInput.prototype.renderFunction = function () {
  63902. if (this._additionalRenderLoopLogicCallback) {
  63903. this._additionalRenderLoopLogicCallback();
  63904. }
  63905. if (this._currentScene) {
  63906. if (this._textureLoadingCallback) {
  63907. var remaining = this._currentScene.getWaitingItemsCount();
  63908. if (remaining > 0) {
  63909. this._textureLoadingCallback(remaining);
  63910. }
  63911. }
  63912. this._currentScene.render();
  63913. }
  63914. };
  63915. FilesInput.prototype.drag = function (e) {
  63916. e.stopPropagation();
  63917. e.preventDefault();
  63918. };
  63919. FilesInput.prototype.drop = function (eventDrop) {
  63920. eventDrop.stopPropagation();
  63921. eventDrop.preventDefault();
  63922. this.loadFiles(eventDrop);
  63923. };
  63924. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63925. var _this = this;
  63926. var reader = folder.createReader();
  63927. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63928. reader.readEntries(function (entries) {
  63929. remaining.count += entries.length;
  63930. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63931. var entry = entries_1[_i];
  63932. if (entry.isFile) {
  63933. entry.file(function (file) {
  63934. file.correctName = relativePath + file.name;
  63935. files.push(file);
  63936. if (--remaining.count === 0) {
  63937. callback();
  63938. }
  63939. });
  63940. }
  63941. else if (entry.isDirectory) {
  63942. _this._traverseFolder(entry, files, remaining, callback);
  63943. }
  63944. }
  63945. if (--remaining.count) {
  63946. callback();
  63947. }
  63948. });
  63949. };
  63950. FilesInput.prototype._processFiles = function (files) {
  63951. for (var i = 0; i < files.length; i++) {
  63952. var name = files[i].correctName.toLowerCase();
  63953. var extension = name.split('.').pop();
  63954. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63955. continue;
  63956. }
  63957. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63958. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63959. this._sceneFileToLoad = files[i];
  63960. }
  63961. else {
  63962. FilesInput.FilesToLoad[name] = files[i];
  63963. }
  63964. }
  63965. };
  63966. FilesInput.prototype.loadFiles = function (event) {
  63967. var _this = this;
  63968. if (this._startingProcessingFilesCallback)
  63969. this._startingProcessingFilesCallback();
  63970. // Handling data transfer via drag'n'drop
  63971. if (event && event.dataTransfer && event.dataTransfer.files) {
  63972. this._filesToLoad = event.dataTransfer.files;
  63973. }
  63974. // Handling files from input files
  63975. if (event && event.target && event.target.files) {
  63976. this._filesToLoad = event.target.files;
  63977. }
  63978. if (this._filesToLoad && this._filesToLoad.length > 0) {
  63979. var files_1 = new Array();
  63980. var folders = [];
  63981. var items = event.dataTransfer ? event.dataTransfer.items : null;
  63982. for (var i = 0; i < this._filesToLoad.length; i++) {
  63983. var fileToLoad = this._filesToLoad[i];
  63984. var name_1 = fileToLoad.name.toLowerCase();
  63985. var entry = void 0;
  63986. fileToLoad.correctName = name_1;
  63987. if (items) {
  63988. var item = items[i];
  63989. if (item.getAsEntry) {
  63990. entry = item.getAsEntry();
  63991. }
  63992. else if (item.webkitGetAsEntry) {
  63993. entry = item.webkitGetAsEntry();
  63994. }
  63995. }
  63996. if (!entry) {
  63997. files_1.push(fileToLoad);
  63998. }
  63999. else {
  64000. if (entry.isDirectory) {
  64001. folders.push(entry);
  64002. }
  64003. else {
  64004. files_1.push(fileToLoad);
  64005. }
  64006. }
  64007. }
  64008. if (folders.length === 0) {
  64009. this._processFiles(files_1);
  64010. this._processReload();
  64011. }
  64012. else {
  64013. var remaining = { count: folders.length };
  64014. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  64015. var folder = folders_1[_i];
  64016. this._traverseFolder(folder, files_1, remaining, function () {
  64017. _this._processFiles(files_1);
  64018. if (remaining.count === 0) {
  64019. _this._processReload();
  64020. }
  64021. });
  64022. }
  64023. }
  64024. }
  64025. };
  64026. FilesInput.prototype._processReload = function () {
  64027. if (this._onReloadCallback) {
  64028. this._onReloadCallback(this._sceneFileToLoad);
  64029. }
  64030. else {
  64031. this.reload();
  64032. }
  64033. };
  64034. FilesInput.prototype.reload = function () {
  64035. var _this = this;
  64036. // If a scene file has been provided
  64037. if (this._sceneFileToLoad) {
  64038. if (this._currentScene) {
  64039. if (BABYLON.Tools.errorsCount > 0) {
  64040. BABYLON.Tools.ClearLogCache();
  64041. }
  64042. this._engine.stopRenderLoop();
  64043. this._currentScene.dispose();
  64044. }
  64045. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  64046. if (_this._progressCallback) {
  64047. _this._progressCallback(progress);
  64048. }
  64049. }).then(function (scene) {
  64050. _this._currentScene = scene;
  64051. if (_this._sceneLoadedCallback) {
  64052. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  64053. }
  64054. // Wait for textures and shaders to be ready
  64055. _this._currentScene.executeWhenReady(function () {
  64056. _this._engine.runRenderLoop(function () {
  64057. _this.renderFunction();
  64058. });
  64059. });
  64060. }).catch(function (error) {
  64061. if (_this._errorCallback) {
  64062. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  64063. }
  64064. });
  64065. }
  64066. else {
  64067. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  64068. }
  64069. };
  64070. FilesInput.FilesToLoad = {};
  64071. return FilesInput;
  64072. }());
  64073. BABYLON.FilesInput = FilesInput;
  64074. })(BABYLON || (BABYLON = {}));
  64075. //# sourceMappingURL=babylon.filesInput.js.map
  64076. "use strict";
  64077. var BABYLON;
  64078. (function (BABYLON) {
  64079. /**
  64080. * This class implement a typical dictionary using a string as key and the generic type T as value.
  64081. * The underlying implementation relies on an associative array to ensure the best performances.
  64082. * The value can be anything including 'null' but except 'undefined'
  64083. */
  64084. var StringDictionary = /** @class */ (function () {
  64085. function StringDictionary() {
  64086. this._count = 0;
  64087. this._data = {};
  64088. }
  64089. /**
  64090. * This will clear this dictionary and copy the content from the 'source' one.
  64091. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  64092. * @param source the dictionary to take the content from and copy to this dictionary
  64093. */
  64094. StringDictionary.prototype.copyFrom = function (source) {
  64095. var _this = this;
  64096. this.clear();
  64097. source.forEach(function (t, v) { return _this.add(t, v); });
  64098. };
  64099. /**
  64100. * Get a value based from its key
  64101. * @param key the given key to get the matching value from
  64102. * @return the value if found, otherwise undefined is returned
  64103. */
  64104. StringDictionary.prototype.get = function (key) {
  64105. var val = this._data[key];
  64106. if (val !== undefined) {
  64107. return val;
  64108. }
  64109. return undefined;
  64110. };
  64111. /**
  64112. * Get a value from its key or add it if it doesn't exist.
  64113. * This method will ensure you that a given key/data will be present in the dictionary.
  64114. * @param key the given key to get the matching value from
  64115. * @param factory the factory that will create the value if the key is not present in the dictionary.
  64116. * The factory will only be invoked if there's no data for the given key.
  64117. * @return the value corresponding to the key.
  64118. */
  64119. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  64120. var val = this.get(key);
  64121. if (val !== undefined) {
  64122. return val;
  64123. }
  64124. val = factory(key);
  64125. if (val) {
  64126. this.add(key, val);
  64127. }
  64128. return val;
  64129. };
  64130. /**
  64131. * Get a value from its key if present in the dictionary otherwise add it
  64132. * @param key the key to get the value from
  64133. * @param val if there's no such key/value pair in the dictionary add it with this value
  64134. * @return the value corresponding to the key
  64135. */
  64136. StringDictionary.prototype.getOrAdd = function (key, val) {
  64137. var curVal = this.get(key);
  64138. if (curVal !== undefined) {
  64139. return curVal;
  64140. }
  64141. this.add(key, val);
  64142. return val;
  64143. };
  64144. /**
  64145. * Check if there's a given key in the dictionary
  64146. * @param key the key to check for
  64147. * @return true if the key is present, false otherwise
  64148. */
  64149. StringDictionary.prototype.contains = function (key) {
  64150. return this._data[key] !== undefined;
  64151. };
  64152. /**
  64153. * Add a new key and its corresponding value
  64154. * @param key the key to add
  64155. * @param value the value corresponding to the key
  64156. * @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
  64157. */
  64158. StringDictionary.prototype.add = function (key, value) {
  64159. if (this._data[key] !== undefined) {
  64160. return false;
  64161. }
  64162. this._data[key] = value;
  64163. ++this._count;
  64164. return true;
  64165. };
  64166. StringDictionary.prototype.set = function (key, value) {
  64167. if (this._data[key] === undefined) {
  64168. return false;
  64169. }
  64170. this._data[key] = value;
  64171. return true;
  64172. };
  64173. /**
  64174. * Get the element of the given key and remove it from the dictionary
  64175. * @param key
  64176. */
  64177. StringDictionary.prototype.getAndRemove = function (key) {
  64178. var val = this.get(key);
  64179. if (val !== undefined) {
  64180. delete this._data[key];
  64181. --this._count;
  64182. return val;
  64183. }
  64184. return null;
  64185. };
  64186. /**
  64187. * Remove a key/value from the dictionary.
  64188. * @param key the key to remove
  64189. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  64190. */
  64191. StringDictionary.prototype.remove = function (key) {
  64192. if (this.contains(key)) {
  64193. delete this._data[key];
  64194. --this._count;
  64195. return true;
  64196. }
  64197. return false;
  64198. };
  64199. /**
  64200. * Clear the whole content of the dictionary
  64201. */
  64202. StringDictionary.prototype.clear = function () {
  64203. this._data = {};
  64204. this._count = 0;
  64205. };
  64206. Object.defineProperty(StringDictionary.prototype, "count", {
  64207. get: function () {
  64208. return this._count;
  64209. },
  64210. enumerable: true,
  64211. configurable: true
  64212. });
  64213. /**
  64214. * Execute a callback on each key/val of the dictionary.
  64215. * Note that you can remove any element in this dictionary in the callback implementation
  64216. * @param callback the callback to execute on a given key/value pair
  64217. */
  64218. StringDictionary.prototype.forEach = function (callback) {
  64219. for (var cur in this._data) {
  64220. var val = this._data[cur];
  64221. callback(cur, val);
  64222. }
  64223. };
  64224. /**
  64225. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  64226. * If the callback returns null or undefined the method will iterate to the next key/value pair
  64227. * Note that you can remove any element in this dictionary in the callback implementation
  64228. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  64229. */
  64230. StringDictionary.prototype.first = function (callback) {
  64231. for (var cur in this._data) {
  64232. var val = this._data[cur];
  64233. var res = callback(cur, val);
  64234. if (res) {
  64235. return res;
  64236. }
  64237. }
  64238. return null;
  64239. };
  64240. return StringDictionary;
  64241. }());
  64242. BABYLON.StringDictionary = StringDictionary;
  64243. })(BABYLON || (BABYLON = {}));
  64244. //# sourceMappingURL=babylon.stringDictionary.js.map
  64245. "use strict";
  64246. var BABYLON;
  64247. (function (BABYLON) {
  64248. var Tags = /** @class */ (function () {
  64249. function Tags() {
  64250. }
  64251. Tags.EnableFor = function (obj) {
  64252. obj._tags = obj._tags || {};
  64253. obj.hasTags = function () {
  64254. return Tags.HasTags(obj);
  64255. };
  64256. obj.addTags = function (tagsString) {
  64257. return Tags.AddTagsTo(obj, tagsString);
  64258. };
  64259. obj.removeTags = function (tagsString) {
  64260. return Tags.RemoveTagsFrom(obj, tagsString);
  64261. };
  64262. obj.matchesTagsQuery = function (tagsQuery) {
  64263. return Tags.MatchesQuery(obj, tagsQuery);
  64264. };
  64265. };
  64266. Tags.DisableFor = function (obj) {
  64267. delete obj._tags;
  64268. delete obj.hasTags;
  64269. delete obj.addTags;
  64270. delete obj.removeTags;
  64271. delete obj.matchesTagsQuery;
  64272. };
  64273. Tags.HasTags = function (obj) {
  64274. if (!obj._tags) {
  64275. return false;
  64276. }
  64277. return !BABYLON.Tools.IsEmpty(obj._tags);
  64278. };
  64279. Tags.GetTags = function (obj, asString) {
  64280. if (asString === void 0) { asString = true; }
  64281. if (!obj._tags) {
  64282. return null;
  64283. }
  64284. if (asString) {
  64285. var tagsArray = [];
  64286. for (var tag in obj._tags) {
  64287. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  64288. tagsArray.push(tag);
  64289. }
  64290. }
  64291. return tagsArray.join(" ");
  64292. }
  64293. else {
  64294. return obj._tags;
  64295. }
  64296. };
  64297. // the tags 'true' and 'false' are reserved and cannot be used as tags
  64298. // a tag cannot start with '||', '&&', and '!'
  64299. // it cannot contain whitespaces
  64300. Tags.AddTagsTo = function (obj, tagsString) {
  64301. if (!tagsString) {
  64302. return;
  64303. }
  64304. if (typeof tagsString !== "string") {
  64305. return;
  64306. }
  64307. var tags = tagsString.split(" ");
  64308. tags.forEach(function (tag, index, array) {
  64309. Tags._AddTagTo(obj, tag);
  64310. });
  64311. };
  64312. Tags._AddTagTo = function (obj, tag) {
  64313. tag = tag.trim();
  64314. if (tag === "" || tag === "true" || tag === "false") {
  64315. return;
  64316. }
  64317. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  64318. return;
  64319. }
  64320. Tags.EnableFor(obj);
  64321. obj._tags[tag] = true;
  64322. };
  64323. Tags.RemoveTagsFrom = function (obj, tagsString) {
  64324. if (!Tags.HasTags(obj)) {
  64325. return;
  64326. }
  64327. var tags = tagsString.split(" ");
  64328. for (var t in tags) {
  64329. Tags._RemoveTagFrom(obj, tags[t]);
  64330. }
  64331. };
  64332. Tags._RemoveTagFrom = function (obj, tag) {
  64333. delete obj._tags[tag];
  64334. };
  64335. Tags.MatchesQuery = function (obj, tagsQuery) {
  64336. if (tagsQuery === undefined) {
  64337. return true;
  64338. }
  64339. if (tagsQuery === "") {
  64340. return Tags.HasTags(obj);
  64341. }
  64342. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  64343. };
  64344. return Tags;
  64345. }());
  64346. BABYLON.Tags = Tags;
  64347. })(BABYLON || (BABYLON = {}));
  64348. //# sourceMappingURL=babylon.tags.js.map
  64349. "use strict";
  64350. var BABYLON;
  64351. (function (BABYLON) {
  64352. var AndOrNotEvaluator = /** @class */ (function () {
  64353. function AndOrNotEvaluator() {
  64354. }
  64355. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  64356. if (!query.match(/\([^\(\)]*\)/g)) {
  64357. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  64358. }
  64359. else {
  64360. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  64361. // remove parenthesis
  64362. r = r.slice(1, r.length - 1);
  64363. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  64364. });
  64365. }
  64366. if (query === "true") {
  64367. return true;
  64368. }
  64369. if (query === "false") {
  64370. return false;
  64371. }
  64372. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  64373. };
  64374. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  64375. evaluateCallback = evaluateCallback || (function (r) {
  64376. return r === "true" ? true : false;
  64377. });
  64378. var result;
  64379. var or = parenthesisContent.split("||");
  64380. for (var i in or) {
  64381. if (or.hasOwnProperty(i)) {
  64382. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  64383. var and = ori.split("&&");
  64384. if (and.length > 1) {
  64385. for (var j = 0; j < and.length; ++j) {
  64386. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  64387. if (andj !== "true" && andj !== "false") {
  64388. if (andj[0] === "!") {
  64389. result = !evaluateCallback(andj.substring(1));
  64390. }
  64391. else {
  64392. result = evaluateCallback(andj);
  64393. }
  64394. }
  64395. else {
  64396. result = andj === "true" ? true : false;
  64397. }
  64398. if (!result) {
  64399. ori = "false";
  64400. break;
  64401. }
  64402. }
  64403. }
  64404. if (result || ori === "true") {
  64405. result = true;
  64406. break;
  64407. }
  64408. // result equals false (or undefined)
  64409. if (ori !== "true" && ori !== "false") {
  64410. if (ori[0] === "!") {
  64411. result = !evaluateCallback(ori.substring(1));
  64412. }
  64413. else {
  64414. result = evaluateCallback(ori);
  64415. }
  64416. }
  64417. else {
  64418. result = ori === "true" ? true : false;
  64419. }
  64420. }
  64421. }
  64422. // the whole parenthesis scope is replaced by 'true' or 'false'
  64423. return result ? "true" : "false";
  64424. };
  64425. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  64426. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  64427. // remove whitespaces
  64428. r = r.replace(/[\s]/g, function () { return ""; });
  64429. return r.length % 2 ? "!" : "";
  64430. });
  64431. booleanString = booleanString.trim();
  64432. if (booleanString === "!true") {
  64433. booleanString = "false";
  64434. }
  64435. else if (booleanString === "!false") {
  64436. booleanString = "true";
  64437. }
  64438. return booleanString;
  64439. };
  64440. return AndOrNotEvaluator;
  64441. }());
  64442. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  64443. })(BABYLON || (BABYLON = {}));
  64444. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  64445. "use strict";
  64446. var BABYLON;
  64447. (function (BABYLON) {
  64448. var Database = /** @class */ (function () {
  64449. function Database(urlToScene, callbackManifestChecked) {
  64450. // Handling various flavors of prefixed version of IndexedDB
  64451. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  64452. this.callbackManifestChecked = callbackManifestChecked;
  64453. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  64454. this.db = null;
  64455. this._enableSceneOffline = false;
  64456. this._enableTexturesOffline = false;
  64457. this.manifestVersionFound = 0;
  64458. this.mustUpdateRessources = false;
  64459. this.hasReachedQuota = false;
  64460. if (!Database.IDBStorageEnabled) {
  64461. this.callbackManifestChecked(true);
  64462. }
  64463. else {
  64464. this.checkManifestFile();
  64465. }
  64466. }
  64467. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  64468. get: function () {
  64469. return this._enableSceneOffline;
  64470. },
  64471. enumerable: true,
  64472. configurable: true
  64473. });
  64474. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  64475. get: function () {
  64476. return this._enableTexturesOffline;
  64477. },
  64478. enumerable: true,
  64479. configurable: true
  64480. });
  64481. Database.prototype.checkManifestFile = function () {
  64482. var _this = this;
  64483. var noManifestFile = function () {
  64484. _this._enableSceneOffline = false;
  64485. _this._enableTexturesOffline = false;
  64486. _this.callbackManifestChecked(false);
  64487. };
  64488. var timeStampUsed = false;
  64489. var manifestURL = this.currentSceneUrl + ".manifest";
  64490. var xhr = new XMLHttpRequest();
  64491. if (navigator.onLine) {
  64492. // Adding a timestamp to by-pass browsers' cache
  64493. timeStampUsed = true;
  64494. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  64495. }
  64496. xhr.open("GET", manifestURL, true);
  64497. xhr.addEventListener("load", function () {
  64498. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64499. try {
  64500. var manifestFile = JSON.parse(xhr.response);
  64501. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  64502. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  64503. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  64504. _this.manifestVersionFound = manifestFile.version;
  64505. }
  64506. if (_this.callbackManifestChecked) {
  64507. _this.callbackManifestChecked(true);
  64508. }
  64509. }
  64510. catch (ex) {
  64511. noManifestFile();
  64512. }
  64513. }
  64514. else {
  64515. noManifestFile();
  64516. }
  64517. }, false);
  64518. xhr.addEventListener("error", function (event) {
  64519. if (timeStampUsed) {
  64520. timeStampUsed = false;
  64521. // Let's retry without the timeStamp
  64522. // It could fail when coupled with HTML5 Offline API
  64523. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64524. xhr.open("GET", retryManifestURL, true);
  64525. xhr.send();
  64526. }
  64527. else {
  64528. noManifestFile();
  64529. }
  64530. }, false);
  64531. try {
  64532. xhr.send();
  64533. }
  64534. catch (ex) {
  64535. BABYLON.Tools.Error("Error on XHR send request.");
  64536. this.callbackManifestChecked(false);
  64537. }
  64538. };
  64539. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64540. var _this = this;
  64541. var handleError = function () {
  64542. _this.isSupported = false;
  64543. if (errorCallback)
  64544. errorCallback();
  64545. };
  64546. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64547. // Your browser doesn't support IndexedDB
  64548. this.isSupported = false;
  64549. if (errorCallback)
  64550. errorCallback();
  64551. }
  64552. else {
  64553. // If the DB hasn't been opened or created yet
  64554. if (!this.db) {
  64555. this.hasReachedQuota = false;
  64556. this.isSupported = true;
  64557. var request = this.idbFactory.open("babylonjs", 1);
  64558. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64559. request.onerror = function (event) {
  64560. handleError();
  64561. };
  64562. // executes when a version change transaction cannot complete due to other active transactions
  64563. request.onblocked = function (event) {
  64564. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64565. handleError();
  64566. };
  64567. // DB has been opened successfully
  64568. request.onsuccess = function (event) {
  64569. _this.db = request.result;
  64570. successCallback();
  64571. };
  64572. // Initialization of the DB. Creating Scenes & Textures stores
  64573. request.onupgradeneeded = function (event) {
  64574. _this.db = (event.target).result;
  64575. if (_this.db) {
  64576. try {
  64577. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64578. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64579. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64580. }
  64581. catch (ex) {
  64582. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64583. handleError();
  64584. }
  64585. }
  64586. };
  64587. }
  64588. else {
  64589. if (successCallback)
  64590. successCallback();
  64591. }
  64592. }
  64593. };
  64594. Database.prototype.loadImageFromDB = function (url, image) {
  64595. var _this = this;
  64596. var completeURL = Database.ReturnFullUrlLocation(url);
  64597. var saveAndLoadImage = function () {
  64598. if (!_this.hasReachedQuota && _this.db !== null) {
  64599. // the texture is not yet in the DB, let's try to save it
  64600. _this._saveImageIntoDBAsync(completeURL, image);
  64601. }
  64602. else {
  64603. image.src = url;
  64604. }
  64605. };
  64606. if (!this.mustUpdateRessources) {
  64607. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64608. }
  64609. else {
  64610. saveAndLoadImage();
  64611. }
  64612. };
  64613. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64614. if (this.isSupported && this.db !== null) {
  64615. var texture;
  64616. var transaction = this.db.transaction(["textures"]);
  64617. transaction.onabort = function (event) {
  64618. image.src = url;
  64619. };
  64620. transaction.oncomplete = function (event) {
  64621. var blobTextureURL;
  64622. if (texture) {
  64623. var URL = window.URL || window.webkitURL;
  64624. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64625. image.onerror = function () {
  64626. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64627. image.src = url;
  64628. };
  64629. image.src = blobTextureURL;
  64630. }
  64631. else {
  64632. notInDBCallback();
  64633. }
  64634. };
  64635. var getRequest = transaction.objectStore("textures").get(url);
  64636. getRequest.onsuccess = function (event) {
  64637. texture = (event.target).result;
  64638. };
  64639. getRequest.onerror = function (event) {
  64640. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64641. image.src = url;
  64642. };
  64643. }
  64644. else {
  64645. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64646. image.src = url;
  64647. }
  64648. };
  64649. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64650. var _this = this;
  64651. if (this.isSupported) {
  64652. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64653. var generateBlobUrl = function () {
  64654. var blobTextureURL;
  64655. if (blob) {
  64656. var URL = window.URL || window.webkitURL;
  64657. try {
  64658. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64659. }
  64660. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64661. catch (ex) {
  64662. blobTextureURL = URL.createObjectURL(blob);
  64663. }
  64664. }
  64665. if (blobTextureURL) {
  64666. image.src = blobTextureURL;
  64667. }
  64668. };
  64669. if (Database.IsUASupportingBlobStorage) {
  64670. var xhr = new XMLHttpRequest(), blob;
  64671. xhr.open("GET", url, true);
  64672. xhr.responseType = "blob";
  64673. xhr.addEventListener("load", function () {
  64674. if (xhr.status === 200 && _this.db) {
  64675. // Blob as response (XHR2)
  64676. blob = xhr.response;
  64677. var transaction = _this.db.transaction(["textures"], "readwrite");
  64678. // the transaction could abort because of a QuotaExceededError error
  64679. transaction.onabort = function (event) {
  64680. try {
  64681. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64682. var srcElement = (event.srcElement || event.target);
  64683. var error = srcElement.error;
  64684. if (error && error.name === "QuotaExceededError") {
  64685. _this.hasReachedQuota = true;
  64686. }
  64687. }
  64688. catch (ex) { }
  64689. generateBlobUrl();
  64690. };
  64691. transaction.oncomplete = function (event) {
  64692. generateBlobUrl();
  64693. };
  64694. var newTexture = { textureUrl: url, data: blob };
  64695. try {
  64696. // Put the blob into the dabase
  64697. var addRequest = transaction.objectStore("textures").put(newTexture);
  64698. addRequest.onsuccess = function (event) {
  64699. };
  64700. addRequest.onerror = function (event) {
  64701. generateBlobUrl();
  64702. };
  64703. }
  64704. catch (ex) {
  64705. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64706. if (ex.code === 25) {
  64707. Database.IsUASupportingBlobStorage = false;
  64708. }
  64709. image.src = url;
  64710. }
  64711. }
  64712. else {
  64713. image.src = url;
  64714. }
  64715. }, false);
  64716. xhr.addEventListener("error", function (event) {
  64717. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64718. image.src = url;
  64719. }, false);
  64720. xhr.send();
  64721. }
  64722. else {
  64723. image.src = url;
  64724. }
  64725. }
  64726. else {
  64727. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64728. image.src = url;
  64729. }
  64730. };
  64731. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64732. var _this = this;
  64733. var updateVersion = function () {
  64734. // the version is not yet in the DB or we need to update it
  64735. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64736. };
  64737. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64738. };
  64739. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64740. var _this = this;
  64741. if (this.isSupported && this.db) {
  64742. var version;
  64743. try {
  64744. var transaction = this.db.transaction(["versions"]);
  64745. transaction.oncomplete = function (event) {
  64746. if (version) {
  64747. // If the version in the JSON file is > than the version in DB
  64748. if (_this.manifestVersionFound > version.data) {
  64749. _this.mustUpdateRessources = true;
  64750. updateInDBCallback();
  64751. }
  64752. else {
  64753. callback(version.data);
  64754. }
  64755. }
  64756. else {
  64757. _this.mustUpdateRessources = true;
  64758. updateInDBCallback();
  64759. }
  64760. };
  64761. transaction.onabort = function (event) {
  64762. callback(-1);
  64763. };
  64764. var getRequest = transaction.objectStore("versions").get(url);
  64765. getRequest.onsuccess = function (event) {
  64766. version = (event.target).result;
  64767. };
  64768. getRequest.onerror = function (event) {
  64769. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64770. callback(-1);
  64771. };
  64772. }
  64773. catch (ex) {
  64774. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64775. callback(-1);
  64776. }
  64777. }
  64778. else {
  64779. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64780. callback(-1);
  64781. }
  64782. };
  64783. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64784. var _this = this;
  64785. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64786. try {
  64787. // Open a transaction to the database
  64788. var transaction = this.db.transaction(["versions"], "readwrite");
  64789. // the transaction could abort because of a QuotaExceededError error
  64790. transaction.onabort = function (event) {
  64791. try {
  64792. var error = event.srcElement['error'];
  64793. if (error && error.name === "QuotaExceededError") {
  64794. _this.hasReachedQuota = true;
  64795. }
  64796. }
  64797. catch (ex) { }
  64798. callback(-1);
  64799. };
  64800. transaction.oncomplete = function (event) {
  64801. callback(_this.manifestVersionFound);
  64802. };
  64803. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64804. // Put the scene into the database
  64805. var addRequest = transaction.objectStore("versions").put(newVersion);
  64806. addRequest.onsuccess = function (event) {
  64807. };
  64808. addRequest.onerror = function (event) {
  64809. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64810. };
  64811. }
  64812. catch (ex) {
  64813. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64814. callback(-1);
  64815. }
  64816. }
  64817. else {
  64818. callback(-1);
  64819. }
  64820. };
  64821. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64822. var _this = this;
  64823. var completeUrl = Database.ReturnFullUrlLocation(url);
  64824. var saveAndLoadFile = function () {
  64825. // the scene is not yet in the DB, let's try to save it
  64826. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64827. };
  64828. this._checkVersionFromDB(completeUrl, function (version) {
  64829. if (version !== -1) {
  64830. if (!_this.mustUpdateRessources) {
  64831. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64832. }
  64833. else {
  64834. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64835. }
  64836. }
  64837. else {
  64838. if (errorCallback) {
  64839. errorCallback();
  64840. }
  64841. }
  64842. });
  64843. };
  64844. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64845. if (this.isSupported && this.db) {
  64846. var targetStore;
  64847. if (url.indexOf(".babylon") !== -1) {
  64848. targetStore = "scenes";
  64849. }
  64850. else {
  64851. targetStore = "textures";
  64852. }
  64853. var file;
  64854. var transaction = this.db.transaction([targetStore]);
  64855. transaction.oncomplete = function (event) {
  64856. if (file) {
  64857. callback(file.data);
  64858. }
  64859. else {
  64860. notInDBCallback();
  64861. }
  64862. };
  64863. transaction.onabort = function (event) {
  64864. notInDBCallback();
  64865. };
  64866. var getRequest = transaction.objectStore(targetStore).get(url);
  64867. getRequest.onsuccess = function (event) {
  64868. file = (event.target).result;
  64869. };
  64870. getRequest.onerror = function (event) {
  64871. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64872. notInDBCallback();
  64873. };
  64874. }
  64875. else {
  64876. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64877. callback();
  64878. }
  64879. };
  64880. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64881. var _this = this;
  64882. if (this.isSupported) {
  64883. var targetStore;
  64884. if (url.indexOf(".babylon") !== -1) {
  64885. targetStore = "scenes";
  64886. }
  64887. else {
  64888. targetStore = "textures";
  64889. }
  64890. // Create XHR
  64891. var xhr = new XMLHttpRequest();
  64892. var fileData;
  64893. xhr.open("GET", url, true);
  64894. if (useArrayBuffer) {
  64895. xhr.responseType = "arraybuffer";
  64896. }
  64897. if (progressCallback) {
  64898. xhr.onprogress = progressCallback;
  64899. }
  64900. xhr.addEventListener("load", function () {
  64901. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64902. // Blob as response (XHR2)
  64903. //fileData = xhr.responseText;
  64904. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64905. if (!_this.hasReachedQuota && _this.db) {
  64906. // Open a transaction to the database
  64907. var transaction = _this.db.transaction([targetStore], "readwrite");
  64908. // the transaction could abort because of a QuotaExceededError error
  64909. transaction.onabort = function (event) {
  64910. try {
  64911. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64912. var error = event.srcElement['error'];
  64913. if (error && error.name === "QuotaExceededError") {
  64914. _this.hasReachedQuota = true;
  64915. }
  64916. }
  64917. catch (ex) { }
  64918. callback(fileData);
  64919. };
  64920. transaction.oncomplete = function (event) {
  64921. callback(fileData);
  64922. };
  64923. var newFile;
  64924. if (targetStore === "scenes") {
  64925. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64926. }
  64927. else {
  64928. newFile = { textureUrl: url, data: fileData };
  64929. }
  64930. try {
  64931. // Put the scene into the database
  64932. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64933. addRequest.onsuccess = function (event) {
  64934. };
  64935. addRequest.onerror = function (event) {
  64936. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64937. };
  64938. }
  64939. catch (ex) {
  64940. callback(fileData);
  64941. }
  64942. }
  64943. else {
  64944. callback(fileData);
  64945. }
  64946. }
  64947. else {
  64948. callback();
  64949. }
  64950. }, false);
  64951. xhr.addEventListener("error", function (event) {
  64952. BABYLON.Tools.Error("error on XHR request.");
  64953. callback();
  64954. }, false);
  64955. xhr.send();
  64956. }
  64957. else {
  64958. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64959. callback();
  64960. }
  64961. };
  64962. Database.IsUASupportingBlobStorage = true;
  64963. Database.IDBStorageEnabled = true;
  64964. Database.parseURL = function (url) {
  64965. var a = document.createElement('a');
  64966. a.href = url;
  64967. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64968. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  64969. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  64970. return absLocation;
  64971. };
  64972. Database.ReturnFullUrlLocation = function (url) {
  64973. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  64974. return (Database.parseURL(window.location.href) + url);
  64975. }
  64976. else {
  64977. return url;
  64978. }
  64979. };
  64980. return Database;
  64981. }());
  64982. BABYLON.Database = Database;
  64983. })(BABYLON || (BABYLON = {}));
  64984. //# sourceMappingURL=babylon.database.js.map
  64985. "use strict";
  64986. var BABYLON;
  64987. (function (BABYLON) {
  64988. var FresnelParameters = /** @class */ (function () {
  64989. function FresnelParameters() {
  64990. this._isEnabled = true;
  64991. this.leftColor = BABYLON.Color3.White();
  64992. this.rightColor = BABYLON.Color3.Black();
  64993. this.bias = 0;
  64994. this.power = 1;
  64995. }
  64996. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  64997. get: function () {
  64998. return this._isEnabled;
  64999. },
  65000. set: function (value) {
  65001. if (this._isEnabled === value) {
  65002. return;
  65003. }
  65004. this._isEnabled = value;
  65005. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  65006. },
  65007. enumerable: true,
  65008. configurable: true
  65009. });
  65010. FresnelParameters.prototype.clone = function () {
  65011. var newFresnelParameters = new FresnelParameters();
  65012. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  65013. return newFresnelParameters;
  65014. };
  65015. FresnelParameters.prototype.serialize = function () {
  65016. var serializationObject = {};
  65017. serializationObject.isEnabled = this.isEnabled;
  65018. serializationObject.leftColor = this.leftColor.asArray();
  65019. serializationObject.rightColor = this.rightColor.asArray();
  65020. serializationObject.bias = this.bias;
  65021. serializationObject.power = this.power;
  65022. return serializationObject;
  65023. };
  65024. FresnelParameters.Parse = function (parsedFresnelParameters) {
  65025. var fresnelParameters = new FresnelParameters();
  65026. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  65027. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  65028. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  65029. fresnelParameters.bias = parsedFresnelParameters.bias;
  65030. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  65031. return fresnelParameters;
  65032. };
  65033. return FresnelParameters;
  65034. }());
  65035. BABYLON.FresnelParameters = FresnelParameters;
  65036. })(BABYLON || (BABYLON = {}));
  65037. //# sourceMappingURL=babylon.fresnelParameters.js.map
  65038. "use strict";
  65039. var BABYLON;
  65040. (function (BABYLON) {
  65041. var MultiMaterial = /** @class */ (function (_super) {
  65042. __extends(MultiMaterial, _super);
  65043. function MultiMaterial(name, scene) {
  65044. var _this = _super.call(this, name, scene, true) || this;
  65045. scene.multiMaterials.push(_this);
  65046. _this.subMaterials = new Array();
  65047. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  65048. return _this;
  65049. }
  65050. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  65051. get: function () {
  65052. return this._subMaterials;
  65053. },
  65054. set: function (value) {
  65055. this._subMaterials = value;
  65056. this._hookArray(value);
  65057. },
  65058. enumerable: true,
  65059. configurable: true
  65060. });
  65061. MultiMaterial.prototype._hookArray = function (array) {
  65062. var _this = this;
  65063. var oldPush = array.push;
  65064. array.push = function () {
  65065. var items = [];
  65066. for (var _i = 0; _i < arguments.length; _i++) {
  65067. items[_i] = arguments[_i];
  65068. }
  65069. var result = oldPush.apply(array, items);
  65070. _this._markAllSubMeshesAsTexturesDirty();
  65071. return result;
  65072. };
  65073. var oldSplice = array.splice;
  65074. array.splice = function (index, deleteCount) {
  65075. var deleted = oldSplice.apply(array, [index, deleteCount]);
  65076. _this._markAllSubMeshesAsTexturesDirty();
  65077. return deleted;
  65078. };
  65079. };
  65080. // Properties
  65081. MultiMaterial.prototype.getSubMaterial = function (index) {
  65082. if (index < 0 || index >= this.subMaterials.length) {
  65083. return this.getScene().defaultMaterial;
  65084. }
  65085. return this.subMaterials[index];
  65086. };
  65087. MultiMaterial.prototype.getActiveTextures = function () {
  65088. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  65089. if (subMaterial) {
  65090. return subMaterial.getActiveTextures();
  65091. }
  65092. else {
  65093. return [];
  65094. }
  65095. }));
  65096. var _a;
  65097. };
  65098. // Methods
  65099. MultiMaterial.prototype.getClassName = function () {
  65100. return "MultiMaterial";
  65101. };
  65102. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  65103. for (var index = 0; index < this.subMaterials.length; index++) {
  65104. var subMaterial = this.subMaterials[index];
  65105. if (subMaterial) {
  65106. if (subMaterial.storeEffectOnSubMeshes) {
  65107. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  65108. return false;
  65109. }
  65110. continue;
  65111. }
  65112. if (!subMaterial.isReady(mesh)) {
  65113. return false;
  65114. }
  65115. }
  65116. }
  65117. return true;
  65118. };
  65119. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  65120. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  65121. for (var index = 0; index < this.subMaterials.length; index++) {
  65122. var subMaterial = null;
  65123. var current = this.subMaterials[index];
  65124. if (cloneChildren && current) {
  65125. subMaterial = current.clone(name + "-" + current.name);
  65126. }
  65127. else {
  65128. subMaterial = this.subMaterials[index];
  65129. }
  65130. newMultiMaterial.subMaterials.push(subMaterial);
  65131. }
  65132. return newMultiMaterial;
  65133. };
  65134. MultiMaterial.prototype.serialize = function () {
  65135. var serializationObject = {};
  65136. serializationObject.name = this.name;
  65137. serializationObject.id = this.id;
  65138. if (BABYLON.Tags) {
  65139. serializationObject.tags = BABYLON.Tags.GetTags(this);
  65140. }
  65141. serializationObject.materials = [];
  65142. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  65143. var subMat = this.subMaterials[matIndex];
  65144. if (subMat) {
  65145. serializationObject.materials.push(subMat.id);
  65146. }
  65147. else {
  65148. serializationObject.materials.push(null);
  65149. }
  65150. }
  65151. return serializationObject;
  65152. };
  65153. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  65154. var scene = this.getScene();
  65155. if (!scene) {
  65156. return;
  65157. }
  65158. var index = scene.multiMaterials.indexOf(this);
  65159. if (index >= 0) {
  65160. scene.multiMaterials.splice(index, 1);
  65161. }
  65162. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  65163. };
  65164. return MultiMaterial;
  65165. }(BABYLON.Material));
  65166. BABYLON.MultiMaterial = MultiMaterial;
  65167. })(BABYLON || (BABYLON = {}));
  65168. //# sourceMappingURL=babylon.multiMaterial.js.map
  65169. "use strict";
  65170. var BABYLON;
  65171. (function (BABYLON) {
  65172. var FreeCameraTouchInput = /** @class */ (function () {
  65173. function FreeCameraTouchInput() {
  65174. this._offsetX = null;
  65175. this._offsetY = null;
  65176. this._pointerPressed = new Array();
  65177. this.touchAngularSensibility = 200000.0;
  65178. this.touchMoveSensibility = 250.0;
  65179. }
  65180. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  65181. var _this = this;
  65182. var previousPosition = null;
  65183. if (this._pointerInput === undefined) {
  65184. this._onLostFocus = function (evt) {
  65185. _this._offsetX = null;
  65186. _this._offsetY = null;
  65187. };
  65188. this._pointerInput = function (p, s) {
  65189. var evt = p.event;
  65190. if (evt.pointerType === "mouse") {
  65191. return;
  65192. }
  65193. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  65194. if (!noPreventDefault) {
  65195. evt.preventDefault();
  65196. }
  65197. _this._pointerPressed.push(evt.pointerId);
  65198. if (_this._pointerPressed.length !== 1) {
  65199. return;
  65200. }
  65201. previousPosition = {
  65202. x: evt.clientX,
  65203. y: evt.clientY
  65204. };
  65205. }
  65206. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  65207. if (!noPreventDefault) {
  65208. evt.preventDefault();
  65209. }
  65210. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65211. if (index === -1) {
  65212. return;
  65213. }
  65214. _this._pointerPressed.splice(index, 1);
  65215. if (index != 0) {
  65216. return;
  65217. }
  65218. previousPosition = null;
  65219. _this._offsetX = null;
  65220. _this._offsetY = null;
  65221. }
  65222. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  65223. if (!noPreventDefault) {
  65224. evt.preventDefault();
  65225. }
  65226. if (!previousPosition) {
  65227. return;
  65228. }
  65229. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65230. if (index != 0) {
  65231. return;
  65232. }
  65233. _this._offsetX = evt.clientX - previousPosition.x;
  65234. _this._offsetY = -(evt.clientY - previousPosition.y);
  65235. }
  65236. };
  65237. }
  65238. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  65239. if (this._onLostFocus) {
  65240. element.addEventListener("blur", this._onLostFocus);
  65241. }
  65242. };
  65243. FreeCameraTouchInput.prototype.detachControl = function (element) {
  65244. if (this._pointerInput && element) {
  65245. if (this._observer) {
  65246. this.camera.getScene().onPointerObservable.remove(this._observer);
  65247. this._observer = null;
  65248. }
  65249. if (this._onLostFocus) {
  65250. element.removeEventListener("blur", this._onLostFocus);
  65251. this._onLostFocus = null;
  65252. }
  65253. this._pointerPressed = [];
  65254. this._offsetX = null;
  65255. this._offsetY = null;
  65256. }
  65257. };
  65258. FreeCameraTouchInput.prototype.checkInputs = function () {
  65259. if (this._offsetX && this._offsetY) {
  65260. var camera = this.camera;
  65261. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  65262. if (this._pointerPressed.length > 1) {
  65263. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  65264. }
  65265. else {
  65266. var speed = camera._computeLocalCameraSpeed();
  65267. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  65268. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  65269. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  65270. }
  65271. }
  65272. };
  65273. FreeCameraTouchInput.prototype.getClassName = function () {
  65274. return "FreeCameraTouchInput";
  65275. };
  65276. FreeCameraTouchInput.prototype.getSimpleName = function () {
  65277. return "touch";
  65278. };
  65279. __decorate([
  65280. BABYLON.serialize()
  65281. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  65282. __decorate([
  65283. BABYLON.serialize()
  65284. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  65285. return FreeCameraTouchInput;
  65286. }());
  65287. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  65288. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  65289. })(BABYLON || (BABYLON = {}));
  65290. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  65291. "use strict";
  65292. var BABYLON;
  65293. (function (BABYLON) {
  65294. // We're mainly based on the logic defined into the FreeCamera code
  65295. var TouchCamera = /** @class */ (function (_super) {
  65296. __extends(TouchCamera, _super);
  65297. //-- end properties for backward compatibility for inputs
  65298. function TouchCamera(name, position, scene) {
  65299. var _this = _super.call(this, name, position, scene) || this;
  65300. _this.inputs.addTouch();
  65301. _this._setupInputs();
  65302. return _this;
  65303. }
  65304. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  65305. //-- Begin properties for backward compatibility for inputs
  65306. get: function () {
  65307. var touch = this.inputs.attached["touch"];
  65308. if (touch)
  65309. return touch.touchAngularSensibility;
  65310. return 0;
  65311. },
  65312. set: function (value) {
  65313. var touch = this.inputs.attached["touch"];
  65314. if (touch)
  65315. touch.touchAngularSensibility = value;
  65316. },
  65317. enumerable: true,
  65318. configurable: true
  65319. });
  65320. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  65321. get: function () {
  65322. var touch = this.inputs.attached["touch"];
  65323. if (touch)
  65324. return touch.touchMoveSensibility;
  65325. return 0;
  65326. },
  65327. set: function (value) {
  65328. var touch = this.inputs.attached["touch"];
  65329. if (touch)
  65330. touch.touchMoveSensibility = value;
  65331. },
  65332. enumerable: true,
  65333. configurable: true
  65334. });
  65335. TouchCamera.prototype.getClassName = function () {
  65336. return "TouchCamera";
  65337. };
  65338. TouchCamera.prototype._setupInputs = function () {
  65339. var mouse = this.inputs.attached["mouse"];
  65340. if (mouse) {
  65341. mouse.touchEnabled = false;
  65342. }
  65343. };
  65344. return TouchCamera;
  65345. }(BABYLON.FreeCamera));
  65346. BABYLON.TouchCamera = TouchCamera;
  65347. })(BABYLON || (BABYLON = {}));
  65348. //# sourceMappingURL=babylon.touchCamera.js.map
  65349. "use strict";
  65350. var BABYLON;
  65351. (function (BABYLON) {
  65352. var ProceduralTexture = /** @class */ (function (_super) {
  65353. __extends(ProceduralTexture, _super);
  65354. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  65355. if (fallbackTexture === void 0) { fallbackTexture = null; }
  65356. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65357. if (isCube === void 0) { isCube = false; }
  65358. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65359. _this.isCube = isCube;
  65360. _this.isEnabled = true;
  65361. _this._currentRefreshId = -1;
  65362. _this._refreshRate = 1;
  65363. _this._vertexBuffers = {};
  65364. _this._uniforms = new Array();
  65365. _this._samplers = new Array();
  65366. _this._textures = {};
  65367. _this._floats = {};
  65368. _this._floatsArrays = {};
  65369. _this._colors3 = {};
  65370. _this._colors4 = {};
  65371. _this._vectors2 = {};
  65372. _this._vectors3 = {};
  65373. _this._matrices = {};
  65374. _this._fallbackTextureUsed = false;
  65375. scene._proceduralTextures.push(_this);
  65376. _this._engine = scene.getEngine();
  65377. _this.name = name;
  65378. _this.isRenderTarget = true;
  65379. _this._size = size;
  65380. _this._generateMipMaps = generateMipMaps;
  65381. _this.setFragment(fragment);
  65382. _this._fallbackTexture = fallbackTexture;
  65383. if (isCube) {
  65384. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  65385. _this.setFloat("face", 0);
  65386. }
  65387. else {
  65388. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  65389. }
  65390. // VBO
  65391. var vertices = [];
  65392. vertices.push(1, 1);
  65393. vertices.push(-1, 1);
  65394. vertices.push(-1, -1);
  65395. vertices.push(1, -1);
  65396. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65397. _this._createIndexBuffer();
  65398. return _this;
  65399. }
  65400. ProceduralTexture.prototype._createIndexBuffer = function () {
  65401. var engine = this._engine;
  65402. // Indices
  65403. var indices = [];
  65404. indices.push(0);
  65405. indices.push(1);
  65406. indices.push(2);
  65407. indices.push(0);
  65408. indices.push(2);
  65409. indices.push(3);
  65410. this._indexBuffer = engine.createIndexBuffer(indices);
  65411. };
  65412. ProceduralTexture.prototype._rebuild = function () {
  65413. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65414. if (vb) {
  65415. vb._rebuild();
  65416. }
  65417. this._createIndexBuffer();
  65418. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65419. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65420. }
  65421. };
  65422. ProceduralTexture.prototype.reset = function () {
  65423. if (this._effect === undefined) {
  65424. return;
  65425. }
  65426. var engine = this._engine;
  65427. engine._releaseEffect(this._effect);
  65428. };
  65429. ProceduralTexture.prototype.isReady = function () {
  65430. var _this = this;
  65431. var engine = this._engine;
  65432. var shaders;
  65433. if (!this._fragment) {
  65434. return false;
  65435. }
  65436. if (this._fallbackTextureUsed) {
  65437. return true;
  65438. }
  65439. if (this._fragment.fragmentElement !== undefined) {
  65440. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  65441. }
  65442. else {
  65443. shaders = { vertex: "procedural", fragment: this._fragment };
  65444. }
  65445. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  65446. _this.releaseInternalTexture();
  65447. if (_this._fallbackTexture) {
  65448. _this._texture = _this._fallbackTexture._texture;
  65449. if (_this._texture) {
  65450. _this._texture.incrementReferences();
  65451. }
  65452. }
  65453. _this._fallbackTextureUsed = true;
  65454. });
  65455. return this._effect.isReady();
  65456. };
  65457. ProceduralTexture.prototype.resetRefreshCounter = function () {
  65458. this._currentRefreshId = -1;
  65459. };
  65460. ProceduralTexture.prototype.setFragment = function (fragment) {
  65461. this._fragment = fragment;
  65462. };
  65463. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  65464. get: function () {
  65465. return this._refreshRate;
  65466. },
  65467. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65468. set: function (value) {
  65469. this._refreshRate = value;
  65470. this.resetRefreshCounter();
  65471. },
  65472. enumerable: true,
  65473. configurable: true
  65474. });
  65475. ProceduralTexture.prototype._shouldRender = function () {
  65476. if (!this.isEnabled || !this.isReady() || !this._texture) {
  65477. return false;
  65478. }
  65479. if (this._fallbackTextureUsed) {
  65480. return false;
  65481. }
  65482. if (this._currentRefreshId === -1) {
  65483. this._currentRefreshId = 1;
  65484. return true;
  65485. }
  65486. if (this.refreshRate === this._currentRefreshId) {
  65487. this._currentRefreshId = 1;
  65488. return true;
  65489. }
  65490. this._currentRefreshId++;
  65491. return false;
  65492. };
  65493. ProceduralTexture.prototype.getRenderSize = function () {
  65494. return this._size;
  65495. };
  65496. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  65497. if (this._fallbackTextureUsed) {
  65498. return;
  65499. }
  65500. this.releaseInternalTexture();
  65501. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  65502. };
  65503. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  65504. if (this._uniforms.indexOf(uniformName) === -1) {
  65505. this._uniforms.push(uniformName);
  65506. }
  65507. };
  65508. ProceduralTexture.prototype.setTexture = function (name, texture) {
  65509. if (this._samplers.indexOf(name) === -1) {
  65510. this._samplers.push(name);
  65511. }
  65512. this._textures[name] = texture;
  65513. return this;
  65514. };
  65515. ProceduralTexture.prototype.setFloat = function (name, value) {
  65516. this._checkUniform(name);
  65517. this._floats[name] = value;
  65518. return this;
  65519. };
  65520. ProceduralTexture.prototype.setFloats = function (name, value) {
  65521. this._checkUniform(name);
  65522. this._floatsArrays[name] = value;
  65523. return this;
  65524. };
  65525. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65526. this._checkUniform(name);
  65527. this._colors3[name] = value;
  65528. return this;
  65529. };
  65530. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65531. this._checkUniform(name);
  65532. this._colors4[name] = value;
  65533. return this;
  65534. };
  65535. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65536. this._checkUniform(name);
  65537. this._vectors2[name] = value;
  65538. return this;
  65539. };
  65540. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65541. this._checkUniform(name);
  65542. this._vectors3[name] = value;
  65543. return this;
  65544. };
  65545. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65546. this._checkUniform(name);
  65547. this._matrices[name] = value;
  65548. return this;
  65549. };
  65550. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65551. var scene = this.getScene();
  65552. if (!scene) {
  65553. return;
  65554. }
  65555. var engine = this._engine;
  65556. // Render
  65557. engine.enableEffect(this._effect);
  65558. engine.setState(false);
  65559. // Texture
  65560. for (var name in this._textures) {
  65561. this._effect.setTexture(name, this._textures[name]);
  65562. }
  65563. // Float
  65564. for (name in this._floats) {
  65565. this._effect.setFloat(name, this._floats[name]);
  65566. }
  65567. // Floats
  65568. for (name in this._floatsArrays) {
  65569. this._effect.setArray(name, this._floatsArrays[name]);
  65570. }
  65571. // Color3
  65572. for (name in this._colors3) {
  65573. this._effect.setColor3(name, this._colors3[name]);
  65574. }
  65575. // Color4
  65576. for (name in this._colors4) {
  65577. var color = this._colors4[name];
  65578. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65579. }
  65580. // Vector2
  65581. for (name in this._vectors2) {
  65582. this._effect.setVector2(name, this._vectors2[name]);
  65583. }
  65584. // Vector3
  65585. for (name in this._vectors3) {
  65586. this._effect.setVector3(name, this._vectors3[name]);
  65587. }
  65588. // Matrix
  65589. for (name in this._matrices) {
  65590. this._effect.setMatrix(name, this._matrices[name]);
  65591. }
  65592. if (!this._texture) {
  65593. return;
  65594. }
  65595. if (this.isCube) {
  65596. for (var face = 0; face < 6; face++) {
  65597. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65598. // VBOs
  65599. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65600. this._effect.setFloat("face", face);
  65601. // Clear
  65602. engine.clear(scene.clearColor, true, true, true);
  65603. // Draw order
  65604. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65605. // Mipmaps
  65606. if (face === 5) {
  65607. engine.generateMipMapsForCubemap(this._texture);
  65608. }
  65609. }
  65610. }
  65611. else {
  65612. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65613. // VBOs
  65614. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65615. // Clear
  65616. engine.clear(scene.clearColor, true, true, true);
  65617. // Draw order
  65618. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65619. }
  65620. // Unbind
  65621. engine.unBindFramebuffer(this._texture, this.isCube);
  65622. if (this.onGenerated) {
  65623. this.onGenerated();
  65624. }
  65625. };
  65626. ProceduralTexture.prototype.clone = function () {
  65627. var textureSize = this.getSize();
  65628. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65629. // Base texture
  65630. newTexture.hasAlpha = this.hasAlpha;
  65631. newTexture.level = this.level;
  65632. // RenderTarget Texture
  65633. newTexture.coordinatesMode = this.coordinatesMode;
  65634. return newTexture;
  65635. };
  65636. ProceduralTexture.prototype.dispose = function () {
  65637. var scene = this.getScene();
  65638. if (!scene) {
  65639. return;
  65640. }
  65641. var index = scene._proceduralTextures.indexOf(this);
  65642. if (index >= 0) {
  65643. scene._proceduralTextures.splice(index, 1);
  65644. }
  65645. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65646. if (vertexBuffer) {
  65647. vertexBuffer.dispose();
  65648. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65649. }
  65650. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65651. this._indexBuffer = null;
  65652. }
  65653. _super.prototype.dispose.call(this);
  65654. };
  65655. return ProceduralTexture;
  65656. }(BABYLON.Texture));
  65657. BABYLON.ProceduralTexture = ProceduralTexture;
  65658. })(BABYLON || (BABYLON = {}));
  65659. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65660. "use strict";
  65661. var BABYLON;
  65662. (function (BABYLON) {
  65663. var CustomProceduralTexture = /** @class */ (function (_super) {
  65664. __extends(CustomProceduralTexture, _super);
  65665. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65666. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65667. _this._animate = true;
  65668. _this._time = 0;
  65669. _this._texturePath = texturePath;
  65670. //Try to load json
  65671. _this.loadJson(texturePath);
  65672. _this.refreshRate = 1;
  65673. return _this;
  65674. }
  65675. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65676. var _this = this;
  65677. var noConfigFile = function () {
  65678. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65679. try {
  65680. _this.setFragment(_this._texturePath);
  65681. }
  65682. catch (ex) {
  65683. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65684. }
  65685. };
  65686. var configFileUrl = jsonUrl + "/config.json";
  65687. var xhr = new XMLHttpRequest();
  65688. xhr.open("GET", configFileUrl, true);
  65689. xhr.addEventListener("load", function () {
  65690. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65691. try {
  65692. _this._config = JSON.parse(xhr.response);
  65693. _this.updateShaderUniforms();
  65694. _this.updateTextures();
  65695. _this.setFragment(_this._texturePath + "/custom");
  65696. _this._animate = _this._config.animate;
  65697. _this.refreshRate = _this._config.refreshrate;
  65698. }
  65699. catch (ex) {
  65700. noConfigFile();
  65701. }
  65702. }
  65703. else {
  65704. noConfigFile();
  65705. }
  65706. }, false);
  65707. xhr.addEventListener("error", function () {
  65708. noConfigFile();
  65709. }, false);
  65710. try {
  65711. xhr.send();
  65712. }
  65713. catch (ex) {
  65714. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65715. }
  65716. };
  65717. CustomProceduralTexture.prototype.isReady = function () {
  65718. if (!_super.prototype.isReady.call(this)) {
  65719. return false;
  65720. }
  65721. for (var name in this._textures) {
  65722. var texture = this._textures[name];
  65723. if (!texture.isReady()) {
  65724. return false;
  65725. }
  65726. }
  65727. return true;
  65728. };
  65729. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65730. var scene = this.getScene();
  65731. if (this._animate && scene) {
  65732. this._time += scene.getAnimationRatio() * 0.03;
  65733. this.updateShaderUniforms();
  65734. }
  65735. _super.prototype.render.call(this, useCameraPostProcess);
  65736. };
  65737. CustomProceduralTexture.prototype.updateTextures = function () {
  65738. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65739. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65740. }
  65741. };
  65742. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65743. if (this._config) {
  65744. for (var j = 0; j < this._config.uniforms.length; j++) {
  65745. var uniform = this._config.uniforms[j];
  65746. switch (uniform.type) {
  65747. case "float":
  65748. this.setFloat(uniform.name, uniform.value);
  65749. break;
  65750. case "color3":
  65751. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65752. break;
  65753. case "color4":
  65754. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65755. break;
  65756. case "vector2":
  65757. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65758. break;
  65759. case "vector3":
  65760. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65761. break;
  65762. }
  65763. }
  65764. }
  65765. this.setFloat("time", this._time);
  65766. };
  65767. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65768. get: function () {
  65769. return this._animate;
  65770. },
  65771. set: function (value) {
  65772. this._animate = value;
  65773. },
  65774. enumerable: true,
  65775. configurable: true
  65776. });
  65777. return CustomProceduralTexture;
  65778. }(BABYLON.ProceduralTexture));
  65779. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65780. })(BABYLON || (BABYLON = {}));
  65781. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65782. "use strict";
  65783. var BABYLON;
  65784. (function (BABYLON) {
  65785. var FreeCameraGamepadInput = /** @class */ (function () {
  65786. function FreeCameraGamepadInput() {
  65787. this.gamepadAngularSensibility = 200;
  65788. this.gamepadMoveSensibility = 40;
  65789. // private members
  65790. this._cameraTransform = BABYLON.Matrix.Identity();
  65791. this._deltaTransform = BABYLON.Vector3.Zero();
  65792. this._vector3 = BABYLON.Vector3.Zero();
  65793. this._vector2 = BABYLON.Vector2.Zero();
  65794. }
  65795. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65796. var _this = this;
  65797. var manager = this.camera.getScene().gamepadManager;
  65798. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65799. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65800. // prioritize XBOX gamepads.
  65801. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65802. _this.gamepad = gamepad;
  65803. }
  65804. }
  65805. });
  65806. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65807. if (_this.gamepad === gamepad) {
  65808. _this.gamepad = null;
  65809. }
  65810. });
  65811. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65812. };
  65813. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65814. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65815. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65816. this.gamepad = null;
  65817. };
  65818. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65819. if (this.gamepad && this.gamepad.leftStick) {
  65820. var camera = this.camera;
  65821. var LSValues = this.gamepad.leftStick;
  65822. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65823. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65824. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65825. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65826. var RSValues = this.gamepad.rightStick;
  65827. if (RSValues) {
  65828. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65829. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65830. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65831. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65832. }
  65833. else {
  65834. RSValues = { x: 0, y: 0 };
  65835. }
  65836. if (!camera.rotationQuaternion) {
  65837. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65838. }
  65839. else {
  65840. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65841. }
  65842. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65843. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65844. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65845. camera.cameraDirection.addInPlace(this._deltaTransform);
  65846. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65847. camera.cameraRotation.addInPlace(this._vector2);
  65848. }
  65849. };
  65850. FreeCameraGamepadInput.prototype.getClassName = function () {
  65851. return "FreeCameraGamepadInput";
  65852. };
  65853. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65854. return "gamepad";
  65855. };
  65856. __decorate([
  65857. BABYLON.serialize()
  65858. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65859. __decorate([
  65860. BABYLON.serialize()
  65861. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65862. return FreeCameraGamepadInput;
  65863. }());
  65864. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65865. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65866. })(BABYLON || (BABYLON = {}));
  65867. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65868. "use strict";
  65869. var BABYLON;
  65870. (function (BABYLON) {
  65871. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65872. function ArcRotateCameraGamepadInput() {
  65873. this.gamepadRotationSensibility = 80;
  65874. this.gamepadMoveSensibility = 40;
  65875. }
  65876. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65877. var _this = this;
  65878. var manager = this.camera.getScene().gamepadManager;
  65879. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65880. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65881. // prioritize XBOX gamepads.
  65882. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65883. _this.gamepad = gamepad;
  65884. }
  65885. }
  65886. });
  65887. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65888. if (_this.gamepad === gamepad) {
  65889. _this.gamepad = null;
  65890. }
  65891. });
  65892. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65893. };
  65894. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65895. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65896. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65897. this.gamepad = null;
  65898. };
  65899. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65900. if (this.gamepad) {
  65901. var camera = this.camera;
  65902. var RSValues = this.gamepad.rightStick;
  65903. if (RSValues) {
  65904. if (RSValues.x != 0) {
  65905. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65906. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65907. camera.inertialAlphaOffset += normalizedRX;
  65908. }
  65909. }
  65910. if (RSValues.y != 0) {
  65911. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65912. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65913. camera.inertialBetaOffset += normalizedRY;
  65914. }
  65915. }
  65916. }
  65917. var LSValues = this.gamepad.leftStick;
  65918. if (LSValues && LSValues.y != 0) {
  65919. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65920. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65921. this.camera.inertialRadiusOffset -= normalizedLY;
  65922. }
  65923. }
  65924. }
  65925. };
  65926. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65927. return "ArcRotateCameraGamepadInput";
  65928. };
  65929. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65930. return "gamepad";
  65931. };
  65932. __decorate([
  65933. BABYLON.serialize()
  65934. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65935. __decorate([
  65936. BABYLON.serialize()
  65937. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65938. return ArcRotateCameraGamepadInput;
  65939. }());
  65940. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65941. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65942. })(BABYLON || (BABYLON = {}));
  65943. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65944. "use strict";
  65945. var BABYLON;
  65946. (function (BABYLON) {
  65947. var GamepadManager = /** @class */ (function () {
  65948. function GamepadManager(_scene) {
  65949. var _this = this;
  65950. this._scene = _scene;
  65951. this._babylonGamepads = [];
  65952. this._oneGamepadConnected = false;
  65953. this._isMonitoring = false;
  65954. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65955. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65956. this._gamepadEventSupported = false;
  65957. }
  65958. else {
  65959. this._gamepadEventSupported = 'GamepadEvent' in window;
  65960. this._gamepadSupport = (navigator.getGamepads ||
  65961. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65962. }
  65963. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65964. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65965. for (var i in _this._babylonGamepads) {
  65966. var gamepad = _this._babylonGamepads[i];
  65967. if (gamepad && gamepad._isConnected) {
  65968. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  65969. }
  65970. }
  65971. });
  65972. this._onGamepadConnectedEvent = function (evt) {
  65973. var gamepad = evt.gamepad;
  65974. if (gamepad.index in _this._babylonGamepads) {
  65975. if (_this._babylonGamepads[gamepad.index].isConnected) {
  65976. return;
  65977. }
  65978. }
  65979. var newGamepad;
  65980. if (_this._babylonGamepads[gamepad.index]) {
  65981. newGamepad = _this._babylonGamepads[gamepad.index];
  65982. newGamepad.browserGamepad = gamepad;
  65983. newGamepad._isConnected = true;
  65984. }
  65985. else {
  65986. newGamepad = _this._addNewGamepad(gamepad);
  65987. }
  65988. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65989. _this._startMonitoringGamepads();
  65990. };
  65991. this._onGamepadDisconnectedEvent = function (evt) {
  65992. var gamepad = evt.gamepad;
  65993. // Remove the gamepad from the list of gamepads to monitor.
  65994. for (var i in _this._babylonGamepads) {
  65995. if (_this._babylonGamepads[i].index === gamepad.index) {
  65996. var disconnectedGamepad = _this._babylonGamepads[i];
  65997. disconnectedGamepad._isConnected = false;
  65998. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  65999. break;
  66000. }
  66001. }
  66002. };
  66003. if (this._gamepadSupport) {
  66004. //first add already-connected gamepads
  66005. this._updateGamepadObjects();
  66006. if (this._babylonGamepads.length) {
  66007. this._startMonitoringGamepads();
  66008. }
  66009. // Checking if the gamepad connected event is supported (like in Firefox)
  66010. if (this._gamepadEventSupported) {
  66011. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  66012. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  66013. }
  66014. else {
  66015. this._startMonitoringGamepads();
  66016. }
  66017. }
  66018. }
  66019. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  66020. get: function () {
  66021. return this._babylonGamepads;
  66022. },
  66023. enumerable: true,
  66024. configurable: true
  66025. });
  66026. GamepadManager.prototype.getGamepadByType = function (type) {
  66027. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  66028. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  66029. var gamepad = _a[_i];
  66030. if (gamepad && gamepad.type === type) {
  66031. return gamepad;
  66032. }
  66033. }
  66034. return null;
  66035. };
  66036. GamepadManager.prototype.dispose = function () {
  66037. if (this._gamepadEventSupported) {
  66038. if (this._onGamepadConnectedEvent) {
  66039. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  66040. }
  66041. if (this._onGamepadDisconnectedEvent) {
  66042. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  66043. }
  66044. this._onGamepadConnectedEvent = null;
  66045. this._onGamepadDisconnectedEvent = null;
  66046. }
  66047. this._babylonGamepads.forEach(function (gamepad) {
  66048. gamepad.dispose();
  66049. });
  66050. this.onGamepadConnectedObservable.clear();
  66051. this.onGamepadDisconnectedObservable.clear();
  66052. this._oneGamepadConnected = false;
  66053. this._stopMonitoringGamepads();
  66054. this._babylonGamepads = [];
  66055. };
  66056. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  66057. if (!this._oneGamepadConnected) {
  66058. this._oneGamepadConnected = true;
  66059. }
  66060. var newGamepad;
  66061. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  66062. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  66063. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  66064. }
  66065. else if (gamepad.pose) {
  66066. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  66067. }
  66068. else {
  66069. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  66070. }
  66071. this._babylonGamepads[newGamepad.index] = newGamepad;
  66072. return newGamepad;
  66073. };
  66074. GamepadManager.prototype._startMonitoringGamepads = function () {
  66075. if (!this._isMonitoring) {
  66076. this._isMonitoring = true;
  66077. //back-comp
  66078. if (!this._scene) {
  66079. this._checkGamepadsStatus();
  66080. }
  66081. }
  66082. };
  66083. GamepadManager.prototype._stopMonitoringGamepads = function () {
  66084. this._isMonitoring = false;
  66085. };
  66086. GamepadManager.prototype._checkGamepadsStatus = function () {
  66087. var _this = this;
  66088. // Hack to be compatible Chrome
  66089. this._updateGamepadObjects();
  66090. for (var i in this._babylonGamepads) {
  66091. var gamepad = this._babylonGamepads[i];
  66092. if (!gamepad || !gamepad.isConnected) {
  66093. continue;
  66094. }
  66095. gamepad.update();
  66096. }
  66097. if (this._isMonitoring && !this._scene) {
  66098. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  66099. }
  66100. };
  66101. // This function is called only on Chrome, which does not properly support
  66102. // connection/disconnection events and forces you to recopy again the gamepad object
  66103. GamepadManager.prototype._updateGamepadObjects = function () {
  66104. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  66105. for (var i = 0; i < gamepads.length; i++) {
  66106. if (gamepads[i]) {
  66107. if (!this._babylonGamepads[gamepads[i].index]) {
  66108. var newGamepad = this._addNewGamepad(gamepads[i]);
  66109. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  66110. }
  66111. else {
  66112. // Forced to copy again this object for Chrome for unknown reason
  66113. this._babylonGamepads[i].browserGamepad = gamepads[i];
  66114. if (!this._babylonGamepads[i].isConnected) {
  66115. this._babylonGamepads[i]._isConnected = true;
  66116. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  66117. }
  66118. }
  66119. }
  66120. }
  66121. };
  66122. return GamepadManager;
  66123. }());
  66124. BABYLON.GamepadManager = GamepadManager;
  66125. })(BABYLON || (BABYLON = {}));
  66126. //# sourceMappingURL=babylon.gamepadManager.js.map
  66127. "use strict";
  66128. var BABYLON;
  66129. (function (BABYLON) {
  66130. var StickValues = /** @class */ (function () {
  66131. function StickValues(x, y) {
  66132. this.x = x;
  66133. this.y = y;
  66134. }
  66135. return StickValues;
  66136. }());
  66137. BABYLON.StickValues = StickValues;
  66138. var Gamepad = /** @class */ (function () {
  66139. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  66140. if (leftStickX === void 0) { leftStickX = 0; }
  66141. if (leftStickY === void 0) { leftStickY = 1; }
  66142. if (rightStickX === void 0) { rightStickX = 2; }
  66143. if (rightStickY === void 0) { rightStickY = 3; }
  66144. this.id = id;
  66145. this.index = index;
  66146. this.browserGamepad = browserGamepad;
  66147. this._isConnected = true;
  66148. this._invertLeftStickY = false;
  66149. this.type = Gamepad.GAMEPAD;
  66150. this._leftStickAxisX = leftStickX;
  66151. this._leftStickAxisY = leftStickY;
  66152. this._rightStickAxisX = rightStickX;
  66153. this._rightStickAxisY = rightStickY;
  66154. if (this.browserGamepad.axes.length >= 2) {
  66155. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66156. }
  66157. if (this.browserGamepad.axes.length >= 4) {
  66158. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66159. }
  66160. }
  66161. Object.defineProperty(Gamepad.prototype, "isConnected", {
  66162. get: function () {
  66163. return this._isConnected;
  66164. },
  66165. enumerable: true,
  66166. configurable: true
  66167. });
  66168. Gamepad.prototype.onleftstickchanged = function (callback) {
  66169. this._onleftstickchanged = callback;
  66170. };
  66171. Gamepad.prototype.onrightstickchanged = function (callback) {
  66172. this._onrightstickchanged = callback;
  66173. };
  66174. Object.defineProperty(Gamepad.prototype, "leftStick", {
  66175. get: function () {
  66176. return this._leftStick;
  66177. },
  66178. set: function (newValues) {
  66179. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  66180. this._onleftstickchanged(newValues);
  66181. }
  66182. this._leftStick = newValues;
  66183. },
  66184. enumerable: true,
  66185. configurable: true
  66186. });
  66187. Object.defineProperty(Gamepad.prototype, "rightStick", {
  66188. get: function () {
  66189. return this._rightStick;
  66190. },
  66191. set: function (newValues) {
  66192. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  66193. this._onrightstickchanged(newValues);
  66194. }
  66195. this._rightStick = newValues;
  66196. },
  66197. enumerable: true,
  66198. configurable: true
  66199. });
  66200. Gamepad.prototype.update = function () {
  66201. if (this._leftStick) {
  66202. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66203. if (this._invertLeftStickY) {
  66204. this.leftStick.y *= -1;
  66205. }
  66206. }
  66207. if (this._rightStick) {
  66208. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66209. }
  66210. };
  66211. Gamepad.prototype.dispose = function () {
  66212. };
  66213. Gamepad.GAMEPAD = 0;
  66214. Gamepad.GENERIC = 1;
  66215. Gamepad.XBOX = 2;
  66216. Gamepad.POSE_ENABLED = 3;
  66217. return Gamepad;
  66218. }());
  66219. BABYLON.Gamepad = Gamepad;
  66220. var GenericPad = /** @class */ (function (_super) {
  66221. __extends(GenericPad, _super);
  66222. function GenericPad(id, index, browserGamepad) {
  66223. var _this = _super.call(this, id, index, browserGamepad) || this;
  66224. _this.onButtonDownObservable = new BABYLON.Observable();
  66225. _this.onButtonUpObservable = new BABYLON.Observable();
  66226. _this.type = Gamepad.GENERIC;
  66227. _this._buttons = new Array(browserGamepad.buttons.length);
  66228. return _this;
  66229. }
  66230. GenericPad.prototype.onbuttondown = function (callback) {
  66231. this._onbuttondown = callback;
  66232. };
  66233. GenericPad.prototype.onbuttonup = function (callback) {
  66234. this._onbuttonup = callback;
  66235. };
  66236. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  66237. if (newValue !== currentValue) {
  66238. if (newValue === 1) {
  66239. if (this._onbuttondown) {
  66240. this._onbuttondown(buttonIndex);
  66241. }
  66242. this.onButtonDownObservable.notifyObservers(buttonIndex);
  66243. }
  66244. if (newValue === 0) {
  66245. if (this._onbuttonup) {
  66246. this._onbuttonup(buttonIndex);
  66247. }
  66248. this.onButtonUpObservable.notifyObservers(buttonIndex);
  66249. }
  66250. }
  66251. return newValue;
  66252. };
  66253. GenericPad.prototype.update = function () {
  66254. _super.prototype.update.call(this);
  66255. for (var index = 0; index < this._buttons.length; index++) {
  66256. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  66257. }
  66258. };
  66259. GenericPad.prototype.dispose = function () {
  66260. _super.prototype.dispose.call(this);
  66261. this.onButtonDownObservable.clear();
  66262. this.onButtonUpObservable.clear();
  66263. };
  66264. return GenericPad;
  66265. }(Gamepad));
  66266. BABYLON.GenericPad = GenericPad;
  66267. })(BABYLON || (BABYLON = {}));
  66268. //# sourceMappingURL=babylon.gamepad.js.map
  66269. "use strict";
  66270. var BABYLON;
  66271. (function (BABYLON) {
  66272. var Xbox360Button;
  66273. (function (Xbox360Button) {
  66274. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  66275. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  66276. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  66277. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  66278. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  66279. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  66280. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  66281. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  66282. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  66283. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  66284. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  66285. var Xbox360Dpad;
  66286. (function (Xbox360Dpad) {
  66287. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  66288. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  66289. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  66290. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  66291. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  66292. var Xbox360Pad = /** @class */ (function (_super) {
  66293. __extends(Xbox360Pad, _super);
  66294. function Xbox360Pad(id, index, gamepad, xboxOne) {
  66295. if (xboxOne === void 0) { xboxOne = false; }
  66296. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  66297. _this._leftTrigger = 0;
  66298. _this._rightTrigger = 0;
  66299. _this.onButtonDownObservable = new BABYLON.Observable();
  66300. _this.onButtonUpObservable = new BABYLON.Observable();
  66301. _this.onPadDownObservable = new BABYLON.Observable();
  66302. _this.onPadUpObservable = new BABYLON.Observable();
  66303. _this._buttonA = 0;
  66304. _this._buttonB = 0;
  66305. _this._buttonX = 0;
  66306. _this._buttonY = 0;
  66307. _this._buttonBack = 0;
  66308. _this._buttonStart = 0;
  66309. _this._buttonLB = 0;
  66310. _this._buttonRB = 0;
  66311. _this._buttonLeftStick = 0;
  66312. _this._buttonRightStick = 0;
  66313. _this._dPadUp = 0;
  66314. _this._dPadDown = 0;
  66315. _this._dPadLeft = 0;
  66316. _this._dPadRight = 0;
  66317. _this._isXboxOnePad = false;
  66318. _this.type = BABYLON.Gamepad.XBOX;
  66319. _this._isXboxOnePad = xboxOne;
  66320. return _this;
  66321. }
  66322. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  66323. this._onlefttriggerchanged = callback;
  66324. };
  66325. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  66326. this._onrighttriggerchanged = callback;
  66327. };
  66328. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  66329. get: function () {
  66330. return this._leftTrigger;
  66331. },
  66332. set: function (newValue) {
  66333. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  66334. this._onlefttriggerchanged(newValue);
  66335. }
  66336. this._leftTrigger = newValue;
  66337. },
  66338. enumerable: true,
  66339. configurable: true
  66340. });
  66341. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  66342. get: function () {
  66343. return this._rightTrigger;
  66344. },
  66345. set: function (newValue) {
  66346. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  66347. this._onrighttriggerchanged(newValue);
  66348. }
  66349. this._rightTrigger = newValue;
  66350. },
  66351. enumerable: true,
  66352. configurable: true
  66353. });
  66354. Xbox360Pad.prototype.onbuttondown = function (callback) {
  66355. this._onbuttondown = callback;
  66356. };
  66357. Xbox360Pad.prototype.onbuttonup = function (callback) {
  66358. this._onbuttonup = callback;
  66359. };
  66360. Xbox360Pad.prototype.ondpaddown = function (callback) {
  66361. this._ondpaddown = callback;
  66362. };
  66363. Xbox360Pad.prototype.ondpadup = function (callback) {
  66364. this._ondpadup = callback;
  66365. };
  66366. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  66367. if (newValue !== currentValue) {
  66368. if (newValue === 1) {
  66369. if (this._onbuttondown) {
  66370. this._onbuttondown(buttonType);
  66371. }
  66372. this.onButtonDownObservable.notifyObservers(buttonType);
  66373. }
  66374. if (newValue === 0) {
  66375. if (this._onbuttonup) {
  66376. this._onbuttonup(buttonType);
  66377. }
  66378. this.onButtonUpObservable.notifyObservers(buttonType);
  66379. }
  66380. }
  66381. return newValue;
  66382. };
  66383. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  66384. if (newValue !== currentValue) {
  66385. if (newValue === 1) {
  66386. if (this._ondpaddown) {
  66387. this._ondpaddown(buttonType);
  66388. }
  66389. this.onPadDownObservable.notifyObservers(buttonType);
  66390. }
  66391. if (newValue === 0) {
  66392. if (this._ondpadup) {
  66393. this._ondpadup(buttonType);
  66394. }
  66395. this.onPadUpObservable.notifyObservers(buttonType);
  66396. }
  66397. }
  66398. return newValue;
  66399. };
  66400. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  66401. get: function () {
  66402. return this._buttonA;
  66403. },
  66404. set: function (value) {
  66405. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  66406. },
  66407. enumerable: true,
  66408. configurable: true
  66409. });
  66410. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  66411. get: function () {
  66412. return this._buttonB;
  66413. },
  66414. set: function (value) {
  66415. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  66416. },
  66417. enumerable: true,
  66418. configurable: true
  66419. });
  66420. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  66421. get: function () {
  66422. return this._buttonX;
  66423. },
  66424. set: function (value) {
  66425. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  66426. },
  66427. enumerable: true,
  66428. configurable: true
  66429. });
  66430. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  66431. get: function () {
  66432. return this._buttonY;
  66433. },
  66434. set: function (value) {
  66435. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  66436. },
  66437. enumerable: true,
  66438. configurable: true
  66439. });
  66440. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  66441. get: function () {
  66442. return this._buttonStart;
  66443. },
  66444. set: function (value) {
  66445. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  66446. },
  66447. enumerable: true,
  66448. configurable: true
  66449. });
  66450. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  66451. get: function () {
  66452. return this._buttonBack;
  66453. },
  66454. set: function (value) {
  66455. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  66456. },
  66457. enumerable: true,
  66458. configurable: true
  66459. });
  66460. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  66461. get: function () {
  66462. return this._buttonLB;
  66463. },
  66464. set: function (value) {
  66465. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  66466. },
  66467. enumerable: true,
  66468. configurable: true
  66469. });
  66470. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  66471. get: function () {
  66472. return this._buttonRB;
  66473. },
  66474. set: function (value) {
  66475. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  66476. },
  66477. enumerable: true,
  66478. configurable: true
  66479. });
  66480. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  66481. get: function () {
  66482. return this._buttonLeftStick;
  66483. },
  66484. set: function (value) {
  66485. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  66486. },
  66487. enumerable: true,
  66488. configurable: true
  66489. });
  66490. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  66491. get: function () {
  66492. return this._buttonRightStick;
  66493. },
  66494. set: function (value) {
  66495. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  66496. },
  66497. enumerable: true,
  66498. configurable: true
  66499. });
  66500. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  66501. get: function () {
  66502. return this._dPadUp;
  66503. },
  66504. set: function (value) {
  66505. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  66506. },
  66507. enumerable: true,
  66508. configurable: true
  66509. });
  66510. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  66511. get: function () {
  66512. return this._dPadDown;
  66513. },
  66514. set: function (value) {
  66515. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  66516. },
  66517. enumerable: true,
  66518. configurable: true
  66519. });
  66520. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  66521. get: function () {
  66522. return this._dPadLeft;
  66523. },
  66524. set: function (value) {
  66525. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  66526. },
  66527. enumerable: true,
  66528. configurable: true
  66529. });
  66530. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66531. get: function () {
  66532. return this._dPadRight;
  66533. },
  66534. set: function (value) {
  66535. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66536. },
  66537. enumerable: true,
  66538. configurable: true
  66539. });
  66540. Xbox360Pad.prototype.update = function () {
  66541. _super.prototype.update.call(this);
  66542. if (this._isXboxOnePad) {
  66543. this.buttonA = this.browserGamepad.buttons[0].value;
  66544. this.buttonB = this.browserGamepad.buttons[1].value;
  66545. this.buttonX = this.browserGamepad.buttons[2].value;
  66546. this.buttonY = this.browserGamepad.buttons[3].value;
  66547. this.buttonLB = this.browserGamepad.buttons[4].value;
  66548. this.buttonRB = this.browserGamepad.buttons[5].value;
  66549. this.leftTrigger = this.browserGamepad.axes[2];
  66550. this.rightTrigger = this.browserGamepad.axes[5];
  66551. this.buttonBack = this.browserGamepad.buttons[9].value;
  66552. this.buttonStart = this.browserGamepad.buttons[8].value;
  66553. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66554. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66555. this.dPadUp = this.browserGamepad.buttons[11].value;
  66556. this.dPadDown = this.browserGamepad.buttons[12].value;
  66557. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66558. this.dPadRight = this.browserGamepad.buttons[14].value;
  66559. }
  66560. else {
  66561. this.buttonA = this.browserGamepad.buttons[0].value;
  66562. this.buttonB = this.browserGamepad.buttons[1].value;
  66563. this.buttonX = this.browserGamepad.buttons[2].value;
  66564. this.buttonY = this.browserGamepad.buttons[3].value;
  66565. this.buttonLB = this.browserGamepad.buttons[4].value;
  66566. this.buttonRB = this.browserGamepad.buttons[5].value;
  66567. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66568. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66569. this.buttonBack = this.browserGamepad.buttons[8].value;
  66570. this.buttonStart = this.browserGamepad.buttons[9].value;
  66571. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66572. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66573. this.dPadUp = this.browserGamepad.buttons[12].value;
  66574. this.dPadDown = this.browserGamepad.buttons[13].value;
  66575. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66576. this.dPadRight = this.browserGamepad.buttons[15].value;
  66577. }
  66578. };
  66579. Xbox360Pad.prototype.dispose = function () {
  66580. _super.prototype.dispose.call(this);
  66581. this.onButtonDownObservable.clear();
  66582. this.onButtonUpObservable.clear();
  66583. this.onPadDownObservable.clear();
  66584. this.onPadUpObservable.clear();
  66585. };
  66586. return Xbox360Pad;
  66587. }(BABYLON.Gamepad));
  66588. BABYLON.Xbox360Pad = Xbox360Pad;
  66589. })(BABYLON || (BABYLON = {}));
  66590. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66591. "use strict";
  66592. var BABYLON;
  66593. (function (BABYLON) {
  66594. var PoseEnabledControllerType;
  66595. (function (PoseEnabledControllerType) {
  66596. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66597. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66598. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66599. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66600. /**
  66601. * Google Daydream
  66602. */
  66603. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66604. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66605. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66606. var PoseEnabledControllerHelper = /** @class */ (function () {
  66607. function PoseEnabledControllerHelper() {
  66608. }
  66609. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66610. // Oculus Touch
  66611. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66612. return new BABYLON.OculusTouchController(vrGamepad);
  66613. }
  66614. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66615. return new BABYLON.WindowsMotionController(vrGamepad);
  66616. }
  66617. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66618. return new BABYLON.ViveController(vrGamepad);
  66619. }
  66620. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66621. return new BABYLON.GearVRController(vrGamepad);
  66622. }
  66623. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66624. return new BABYLON.DaydreamController(vrGamepad);
  66625. }
  66626. else {
  66627. return new BABYLON.GenericController(vrGamepad);
  66628. }
  66629. };
  66630. return PoseEnabledControllerHelper;
  66631. }());
  66632. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66633. var PoseEnabledController = /** @class */ (function (_super) {
  66634. __extends(PoseEnabledController, _super);
  66635. function PoseEnabledController(browserGamepad) {
  66636. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66637. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66638. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66639. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66640. // Represents device position and rotation in babylon space
  66641. _this.devicePosition = BABYLON.Vector3.Zero();
  66642. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66643. _this.deviceScaleFactor = 1;
  66644. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66645. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66646. /**
  66647. * Node to be used when casting a ray from the controller
  66648. */
  66649. _this._pointingPoseNode = null;
  66650. _this._workingMatrix = BABYLON.Matrix.Identity();
  66651. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66652. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66653. _this.position = BABYLON.Vector3.Zero();
  66654. _this.rotationQuaternion = new BABYLON.Quaternion();
  66655. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66656. _this._calculatedRotation = new BABYLON.Quaternion();
  66657. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66658. return _this;
  66659. }
  66660. PoseEnabledController.prototype.update = function () {
  66661. _super.prototype.update.call(this);
  66662. var pose = this.browserGamepad.pose;
  66663. this.updateFromDevice(pose);
  66664. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66665. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66666. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66667. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66668. if (this._mesh) {
  66669. this._mesh.position.copyFrom(this.devicePosition);
  66670. if (this._mesh.rotationQuaternion) {
  66671. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66672. }
  66673. }
  66674. };
  66675. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66676. if (poseData) {
  66677. this.rawPose = poseData;
  66678. if (poseData.position) {
  66679. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66680. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66681. this._deviceRoomPosition.z *= -1;
  66682. }
  66683. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66684. this._calculatedPosition.addInPlace(this.position);
  66685. }
  66686. var pose = this.rawPose;
  66687. if (poseData.orientation && pose.orientation) {
  66688. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66689. if (this._mesh) {
  66690. if (this._mesh.getScene().useRightHandedSystem) {
  66691. this._deviceRoomRotationQuaternion.z *= -1;
  66692. this._deviceRoomRotationQuaternion.w *= -1;
  66693. }
  66694. else {
  66695. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66696. }
  66697. }
  66698. // if the camera is set, rotate to the camera's rotation
  66699. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66700. }
  66701. }
  66702. };
  66703. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66704. if (this._mesh) {
  66705. this._mesh.parent = null;
  66706. }
  66707. this._mesh = mesh;
  66708. if (this._poseControlledCamera) {
  66709. this._mesh.parent = this._poseControlledCamera;
  66710. }
  66711. if (!this._mesh.rotationQuaternion) {
  66712. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66713. }
  66714. };
  66715. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66716. this._poseControlledCamera = camera;
  66717. if (this._mesh) {
  66718. this._mesh.parent = this._poseControlledCamera;
  66719. }
  66720. };
  66721. PoseEnabledController.prototype.dispose = function () {
  66722. if (this._mesh) {
  66723. this._mesh.dispose();
  66724. }
  66725. this._mesh = null;
  66726. _super.prototype.dispose.call(this);
  66727. };
  66728. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66729. get: function () {
  66730. return this._mesh;
  66731. },
  66732. enumerable: true,
  66733. configurable: true
  66734. });
  66735. PoseEnabledController.prototype.getForwardRay = function (length) {
  66736. if (length === void 0) { length = 100; }
  66737. if (!this.mesh) {
  66738. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66739. }
  66740. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66741. var origin = m.getTranslation();
  66742. var forward = new BABYLON.Vector3(0, 0, -1);
  66743. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66744. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66745. return new BABYLON.Ray(origin, direction, length);
  66746. };
  66747. /**
  66748. * Name of the child mesh that can be used to cast a ray from the controller
  66749. */
  66750. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66751. return PoseEnabledController;
  66752. }(BABYLON.Gamepad));
  66753. BABYLON.PoseEnabledController = PoseEnabledController;
  66754. })(BABYLON || (BABYLON = {}));
  66755. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66756. "use strict";
  66757. var BABYLON;
  66758. (function (BABYLON) {
  66759. var WebVRController = /** @class */ (function (_super) {
  66760. __extends(WebVRController, _super);
  66761. function WebVRController(vrGamepad) {
  66762. var _this = _super.call(this, vrGamepad) || this;
  66763. // Observables
  66764. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66765. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66766. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66767. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66768. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66769. _this.pad = { x: 0, y: 0 };
  66770. // avoid GC, store state in a tmp object
  66771. _this._changes = {
  66772. pressChanged: false,
  66773. touchChanged: false,
  66774. valueChanged: false,
  66775. changed: false
  66776. };
  66777. _this._buttons = new Array(vrGamepad.buttons.length);
  66778. _this.hand = vrGamepad.hand;
  66779. return _this;
  66780. }
  66781. WebVRController.prototype.onButtonStateChange = function (callback) {
  66782. this._onButtonStateChange = callback;
  66783. };
  66784. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66785. get: function () {
  66786. return this._defaultModel;
  66787. },
  66788. enumerable: true,
  66789. configurable: true
  66790. });
  66791. WebVRController.prototype.update = function () {
  66792. _super.prototype.update.call(this);
  66793. for (var index = 0; index < this._buttons.length; index++) {
  66794. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66795. }
  66796. ;
  66797. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66798. this.pad.x = this.leftStick.x;
  66799. this.pad.y = this.leftStick.y;
  66800. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66801. }
  66802. };
  66803. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66804. if (!newState) {
  66805. newState = {
  66806. pressed: false,
  66807. touched: false,
  66808. value: 0
  66809. };
  66810. }
  66811. if (!currentState) {
  66812. this._buttons[buttonIndex] = {
  66813. pressed: newState.pressed,
  66814. touched: newState.touched,
  66815. value: newState.value
  66816. };
  66817. return;
  66818. }
  66819. this._checkChanges(newState, currentState);
  66820. if (this._changes.changed) {
  66821. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66822. this._handleButtonChange(buttonIndex, newState, this._changes);
  66823. }
  66824. this._buttons[buttonIndex].pressed = newState.pressed;
  66825. this._buttons[buttonIndex].touched = newState.touched;
  66826. // oculus triggers are never 0, thou not touched.
  66827. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66828. };
  66829. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66830. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66831. this._changes.touchChanged = newState.touched !== currentState.touched;
  66832. this._changes.valueChanged = newState.value !== currentState.value;
  66833. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66834. return this._changes;
  66835. };
  66836. WebVRController.prototype.dispose = function () {
  66837. _super.prototype.dispose.call(this);
  66838. this.onTriggerStateChangedObservable.clear();
  66839. this.onMainButtonStateChangedObservable.clear();
  66840. this.onSecondaryButtonStateChangedObservable.clear();
  66841. this.onPadStateChangedObservable.clear();
  66842. this.onPadValuesChangedObservable.clear();
  66843. };
  66844. return WebVRController;
  66845. }(BABYLON.PoseEnabledController));
  66846. BABYLON.WebVRController = WebVRController;
  66847. })(BABYLON || (BABYLON = {}));
  66848. //# sourceMappingURL=babylon.webVRController.js.map
  66849. "use strict";
  66850. var BABYLON;
  66851. (function (BABYLON) {
  66852. var OculusTouchController = /** @class */ (function (_super) {
  66853. __extends(OculusTouchController, _super);
  66854. function OculusTouchController(vrGamepad) {
  66855. var _this = _super.call(this, vrGamepad) || this;
  66856. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66857. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66858. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66859. return _this;
  66860. }
  66861. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66862. var _this = this;
  66863. var meshName;
  66864. // Hand
  66865. if (this.hand === 'left') {
  66866. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66867. }
  66868. else {
  66869. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66870. }
  66871. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66872. /*
  66873. Parent Mesh name: oculus_touch_left
  66874. - body
  66875. - trigger
  66876. - thumbstick
  66877. - grip
  66878. - button_y
  66879. - button_x
  66880. - button_enter
  66881. */
  66882. _this._defaultModel = newMeshes[1];
  66883. _this.attachToMesh(_this._defaultModel);
  66884. if (meshLoaded) {
  66885. meshLoaded(_this._defaultModel);
  66886. }
  66887. });
  66888. };
  66889. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66890. // helper getters for left and right hand.
  66891. get: function () {
  66892. if (this.hand === 'right') {
  66893. return this.onMainButtonStateChangedObservable;
  66894. }
  66895. else {
  66896. throw new Error('No A button on left hand');
  66897. }
  66898. },
  66899. enumerable: true,
  66900. configurable: true
  66901. });
  66902. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66903. get: function () {
  66904. if (this.hand === 'right') {
  66905. return this.onSecondaryButtonStateChangedObservable;
  66906. }
  66907. else {
  66908. throw new Error('No B button on left hand');
  66909. }
  66910. },
  66911. enumerable: true,
  66912. configurable: true
  66913. });
  66914. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66915. get: function () {
  66916. if (this.hand === 'left') {
  66917. return this.onMainButtonStateChangedObservable;
  66918. }
  66919. else {
  66920. throw new Error('No X button on right hand');
  66921. }
  66922. },
  66923. enumerable: true,
  66924. configurable: true
  66925. });
  66926. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66927. get: function () {
  66928. if (this.hand === 'left') {
  66929. return this.onSecondaryButtonStateChangedObservable;
  66930. }
  66931. else {
  66932. throw new Error('No Y button on right hand');
  66933. }
  66934. },
  66935. enumerable: true,
  66936. configurable: true
  66937. });
  66938. /*
  66939. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66940. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66941. 2) secondary trigger (same)
  66942. 3) A (right) X (left), touch, pressed = value
  66943. 4) B / Y
  66944. 5) thumb rest
  66945. */
  66946. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66947. var notifyObject = state; //{ state: state, changes: changes };
  66948. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66949. switch (buttonIdx) {
  66950. case 0:
  66951. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66952. return;
  66953. case 1:// index trigger
  66954. if (this._defaultModel) {
  66955. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66956. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66957. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66958. }
  66959. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66960. return;
  66961. case 2:// secondary trigger
  66962. if (this._defaultModel) {
  66963. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66964. }
  66965. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66966. return;
  66967. case 3:
  66968. if (this._defaultModel) {
  66969. if (notifyObject.pressed) {
  66970. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  66971. }
  66972. else {
  66973. (this._defaultModel.getChildren()[1]).position.y = 0;
  66974. }
  66975. }
  66976. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66977. return;
  66978. case 4:
  66979. if (this._defaultModel) {
  66980. if (notifyObject.pressed) {
  66981. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66982. }
  66983. else {
  66984. (this._defaultModel.getChildren()[2]).position.y = 0;
  66985. }
  66986. }
  66987. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66988. return;
  66989. case 5:
  66990. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  66991. return;
  66992. }
  66993. };
  66994. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  66995. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  66996. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  66997. return OculusTouchController;
  66998. }(BABYLON.WebVRController));
  66999. BABYLON.OculusTouchController = OculusTouchController;
  67000. })(BABYLON || (BABYLON = {}));
  67001. //# sourceMappingURL=babylon.oculusTouchController.js.map
  67002. "use strict";
  67003. var BABYLON;
  67004. (function (BABYLON) {
  67005. var ViveController = /** @class */ (function (_super) {
  67006. __extends(ViveController, _super);
  67007. function ViveController(vrGamepad) {
  67008. var _this = _super.call(this, vrGamepad) || this;
  67009. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  67010. _this._invertLeftStickY = true;
  67011. return _this;
  67012. }
  67013. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67014. var _this = this;
  67015. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  67016. /*
  67017. Parent Mesh name: ViveWand
  67018. - body
  67019. - r_gripper
  67020. - l_gripper
  67021. - menu_button
  67022. - system_button
  67023. - trackpad
  67024. - trigger
  67025. - LED
  67026. */
  67027. _this._defaultModel = newMeshes[1];
  67028. _this.attachToMesh(_this._defaultModel);
  67029. if (meshLoaded) {
  67030. meshLoaded(_this._defaultModel);
  67031. }
  67032. });
  67033. };
  67034. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  67035. get: function () {
  67036. return this.onMainButtonStateChangedObservable;
  67037. },
  67038. enumerable: true,
  67039. configurable: true
  67040. });
  67041. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  67042. get: function () {
  67043. return this.onMainButtonStateChangedObservable;
  67044. },
  67045. enumerable: true,
  67046. configurable: true
  67047. });
  67048. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  67049. get: function () {
  67050. return this.onSecondaryButtonStateChangedObservable;
  67051. },
  67052. enumerable: true,
  67053. configurable: true
  67054. });
  67055. /**
  67056. * Vive mapping:
  67057. * 0: touchpad
  67058. * 1: trigger
  67059. * 2: left AND right buttons
  67060. * 3: menu button
  67061. */
  67062. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67063. var notifyObject = state; //{ state: state, changes: changes };
  67064. switch (buttonIdx) {
  67065. case 0:
  67066. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  67067. return;
  67068. case 1:// index trigger
  67069. if (this._defaultModel) {
  67070. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  67071. }
  67072. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  67073. return;
  67074. case 2:// left AND right button
  67075. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  67076. return;
  67077. case 3:
  67078. if (this._defaultModel) {
  67079. if (notifyObject.pressed) {
  67080. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  67081. }
  67082. else {
  67083. (this._defaultModel.getChildren()[2]).position.y = 0;
  67084. }
  67085. }
  67086. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  67087. return;
  67088. }
  67089. };
  67090. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  67091. ViveController.MODEL_FILENAME = 'wand.babylon';
  67092. return ViveController;
  67093. }(BABYLON.WebVRController));
  67094. BABYLON.ViveController = ViveController;
  67095. })(BABYLON || (BABYLON = {}));
  67096. //# sourceMappingURL=babylon.viveController.js.map
  67097. "use strict";
  67098. var BABYLON;
  67099. (function (BABYLON) {
  67100. var GenericController = /** @class */ (function (_super) {
  67101. __extends(GenericController, _super);
  67102. function GenericController(vrGamepad) {
  67103. return _super.call(this, vrGamepad) || this;
  67104. }
  67105. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67106. var _this = this;
  67107. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  67108. _this._defaultModel = newMeshes[1];
  67109. _this.attachToMesh(_this._defaultModel);
  67110. if (meshLoaded) {
  67111. meshLoaded(_this._defaultModel);
  67112. }
  67113. });
  67114. };
  67115. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67116. console.log("Button id: " + buttonIdx + "state: ");
  67117. console.dir(state);
  67118. };
  67119. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67120. GenericController.MODEL_FILENAME = 'generic.babylon';
  67121. return GenericController;
  67122. }(BABYLON.WebVRController));
  67123. BABYLON.GenericController = GenericController;
  67124. })(BABYLON || (BABYLON = {}));
  67125. //# sourceMappingURL=babylon.genericController.js.map
  67126. "use strict";
  67127. var BABYLON;
  67128. (function (BABYLON) {
  67129. var LoadedMeshInfo = /** @class */ (function () {
  67130. function LoadedMeshInfo() {
  67131. this.buttonMeshes = {};
  67132. this.axisMeshes = {};
  67133. }
  67134. return LoadedMeshInfo;
  67135. }());
  67136. var WindowsMotionController = /** @class */ (function (_super) {
  67137. __extends(WindowsMotionController, _super);
  67138. function WindowsMotionController(vrGamepad) {
  67139. var _this = _super.call(this, vrGamepad) || this;
  67140. _this._mapping = {
  67141. // Semantic button names
  67142. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  67143. // A mapping of the button name to glTF model node name
  67144. // that should be transformed by button value.
  67145. buttonMeshNames: {
  67146. 'trigger': 'SELECT',
  67147. 'menu': 'MENU',
  67148. 'grip': 'GRASP',
  67149. 'thumbstick': 'THUMBSTICK_PRESS',
  67150. 'trackpad': 'TOUCHPAD_PRESS'
  67151. },
  67152. // This mapping is used to translate from the Motion Controller to Babylon semantics
  67153. buttonObservableNames: {
  67154. 'trigger': 'onTriggerStateChangedObservable',
  67155. 'menu': 'onSecondaryButtonStateChangedObservable',
  67156. 'grip': 'onMainButtonStateChangedObservable',
  67157. 'thumbstick': 'onPadStateChangedObservable',
  67158. 'trackpad': 'onTrackpadChangedObservable'
  67159. },
  67160. // A mapping of the axis name to glTF model node name
  67161. // that should be transformed by axis value.
  67162. // This array mirrors the browserGamepad.axes array, such that
  67163. // the mesh corresponding to axis 0 is in this array index 0.
  67164. axisMeshNames: [
  67165. 'THUMBSTICK_X',
  67166. 'THUMBSTICK_Y',
  67167. 'TOUCHPAD_TOUCH_X',
  67168. 'TOUCHPAD_TOUCH_Y'
  67169. ],
  67170. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  67171. };
  67172. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  67173. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  67174. _this.trackpad = { x: 0, y: 0 };
  67175. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  67176. _this._loadedMeshInfo = null;
  67177. return _this;
  67178. }
  67179. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  67180. get: function () {
  67181. return this.onTriggerStateChangedObservable;
  67182. },
  67183. enumerable: true,
  67184. configurable: true
  67185. });
  67186. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  67187. get: function () {
  67188. return this.onSecondaryButtonStateChangedObservable;
  67189. },
  67190. enumerable: true,
  67191. configurable: true
  67192. });
  67193. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  67194. get: function () {
  67195. return this.onMainButtonStateChangedObservable;
  67196. },
  67197. enumerable: true,
  67198. configurable: true
  67199. });
  67200. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  67201. get: function () {
  67202. return this.onPadStateChangedObservable;
  67203. },
  67204. enumerable: true,
  67205. configurable: true
  67206. });
  67207. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  67208. get: function () {
  67209. return this.onTrackpadChangedObservable;
  67210. },
  67211. enumerable: true,
  67212. configurable: true
  67213. });
  67214. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  67215. get: function () {
  67216. return this.onTrackpadValuesChangedObservable;
  67217. },
  67218. enumerable: true,
  67219. configurable: true
  67220. });
  67221. /**
  67222. * Called once per frame by the engine.
  67223. */
  67224. WindowsMotionController.prototype.update = function () {
  67225. _super.prototype.update.call(this);
  67226. if (this.browserGamepad.axes) {
  67227. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  67228. this.trackpad.x = this.browserGamepad["axes"][2];
  67229. this.trackpad.y = this.browserGamepad["axes"][3];
  67230. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  67231. }
  67232. // Only need to animate axes if there is a loaded mesh
  67233. if (this._loadedMeshInfo) {
  67234. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  67235. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  67236. }
  67237. }
  67238. }
  67239. };
  67240. /**
  67241. * Called once for each button that changed state since the last frame
  67242. * @param buttonIdx Which button index changed
  67243. * @param state New state of the button
  67244. * @param changes Which properties on the state changed since last frame
  67245. */
  67246. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67247. var buttonName = this._mapping.buttons[buttonIdx];
  67248. if (!buttonName) {
  67249. return;
  67250. }
  67251. // Only emit events for buttons that we know how to map from index to name
  67252. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  67253. if (observable) {
  67254. observable.notifyObservers(state);
  67255. }
  67256. this.lerpButtonTransform(buttonName, state.value);
  67257. };
  67258. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  67259. // If there is no loaded mesh, there is nothing to transform.
  67260. if (!this._loadedMeshInfo) {
  67261. return;
  67262. }
  67263. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  67264. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67265. return;
  67266. }
  67267. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  67268. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  67269. };
  67270. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  67271. if (!this._loadedMeshInfo) {
  67272. return;
  67273. }
  67274. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  67275. if (!meshInfo) {
  67276. return;
  67277. }
  67278. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67279. return;
  67280. }
  67281. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  67282. var lerpValue = axisValue * 0.5 + 0.5;
  67283. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  67284. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  67285. };
  67286. /**
  67287. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  67288. * @param scene scene in which to add meshes
  67289. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  67290. */
  67291. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  67292. var _this = this;
  67293. if (forceDefault === void 0) { forceDefault = false; }
  67294. var path;
  67295. var filename;
  67296. // Checking if GLB loader is present
  67297. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  67298. // Determine the device specific folder based on the ID suffix
  67299. var device = 'default';
  67300. if (this.id && !forceDefault) {
  67301. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  67302. device = ((match && match[0]) || device);
  67303. }
  67304. // Hand
  67305. if (this.hand === 'left') {
  67306. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  67307. }
  67308. else {
  67309. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  67310. }
  67311. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  67312. }
  67313. else {
  67314. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  67315. path = BABYLON.GenericController.MODEL_BASE_URL;
  67316. filename = BABYLON.GenericController.MODEL_FILENAME;
  67317. }
  67318. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  67319. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  67320. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  67321. if (!_this._loadedMeshInfo) {
  67322. return;
  67323. }
  67324. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  67325. _this.attachToMesh(_this._defaultModel);
  67326. if (meshLoaded) {
  67327. meshLoaded(_this._defaultModel);
  67328. }
  67329. }, null, function (scene, message) {
  67330. BABYLON.Tools.Log(message);
  67331. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  67332. if (!forceDefault) {
  67333. _this.initControllerMesh(scene, meshLoaded, true);
  67334. }
  67335. });
  67336. };
  67337. /**
  67338. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  67339. * can be transformed by button presses and axes values, based on this._mapping.
  67340. *
  67341. * @param scene scene in which the meshes exist
  67342. * @param meshes list of meshes that make up the controller model to process
  67343. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  67344. */
  67345. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  67346. var loadedMeshInfo = null;
  67347. // Create a new mesh to contain the glTF hierarchy
  67348. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  67349. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  67350. var childMesh = null;
  67351. for (var i = 0; i < meshes.length; i++) {
  67352. var mesh = meshes[i];
  67353. if (!mesh.parent) {
  67354. // Exclude controller meshes from picking results
  67355. mesh.isPickable = false;
  67356. // Handle root node, attach to the new parentMesh
  67357. childMesh = mesh;
  67358. break;
  67359. }
  67360. }
  67361. if (childMesh) {
  67362. childMesh.setParent(parentMesh);
  67363. // Create our mesh info. Note that this method will always return non-null.
  67364. loadedMeshInfo = this.createMeshInfo(parentMesh);
  67365. }
  67366. else {
  67367. BABYLON.Tools.Warn('Could not find root node in model file.');
  67368. }
  67369. return loadedMeshInfo;
  67370. };
  67371. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  67372. var loadedMeshInfo = new LoadedMeshInfo();
  67373. var i;
  67374. loadedMeshInfo.rootNode = rootNode;
  67375. // Reset the caches
  67376. loadedMeshInfo.buttonMeshes = {};
  67377. loadedMeshInfo.axisMeshes = {};
  67378. // Button Meshes
  67379. for (i = 0; i < this._mapping.buttons.length; i++) {
  67380. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  67381. if (!buttonMeshName) {
  67382. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  67383. continue;
  67384. }
  67385. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  67386. if (!buttonMesh) {
  67387. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  67388. continue;
  67389. }
  67390. var buttonMeshInfo = {
  67391. index: i,
  67392. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  67393. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  67394. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  67395. };
  67396. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  67397. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  67398. }
  67399. else {
  67400. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  67401. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  67402. '(VALUE: ' + !!buttonMeshInfo.value +
  67403. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  67404. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  67405. ')');
  67406. }
  67407. }
  67408. // Axis Meshes
  67409. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  67410. var axisMeshName = this._mapping.axisMeshNames[i];
  67411. if (!axisMeshName) {
  67412. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  67413. continue;
  67414. }
  67415. var axisMesh = getChildByName(rootNode, axisMeshName);
  67416. if (!axisMesh) {
  67417. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  67418. continue;
  67419. }
  67420. var axisMeshInfo = {
  67421. index: i,
  67422. value: getImmediateChildByName(axisMesh, 'VALUE'),
  67423. min: getImmediateChildByName(axisMesh, 'MIN'),
  67424. max: getImmediateChildByName(axisMesh, 'MAX')
  67425. };
  67426. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  67427. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  67428. }
  67429. else {
  67430. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  67431. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  67432. '(VALUE: ' + !!axisMeshInfo.value +
  67433. ', MIN: ' + !!axisMeshInfo.min +
  67434. ', MAX:' + !!axisMeshInfo.max +
  67435. ')');
  67436. }
  67437. }
  67438. // Pointing Ray
  67439. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  67440. if (!loadedMeshInfo.pointingPoseNode) {
  67441. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  67442. }
  67443. return loadedMeshInfo;
  67444. // Look through all children recursively. This will return null if no mesh exists with the given name.
  67445. function getChildByName(node, name) {
  67446. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  67447. }
  67448. // Look through only immediate children. This will return null if no mesh exists with the given name.
  67449. function getImmediateChildByName(node, name) {
  67450. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  67451. }
  67452. };
  67453. WindowsMotionController.prototype.getForwardRay = function (length) {
  67454. if (length === void 0) { length = 100; }
  67455. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  67456. return _super.prototype.getForwardRay.call(this, length);
  67457. }
  67458. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  67459. var origin = m.getTranslation();
  67460. var forward = new BABYLON.Vector3(0, 0, -1);
  67461. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67462. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67463. return new BABYLON.Ray(origin, direction, length);
  67464. };
  67465. WindowsMotionController.prototype.dispose = function () {
  67466. _super.prototype.dispose.call(this);
  67467. this.onTrackpadChangedObservable.clear();
  67468. };
  67469. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  67470. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  67471. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  67472. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  67473. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  67474. return WindowsMotionController;
  67475. }(BABYLON.WebVRController));
  67476. BABYLON.WindowsMotionController = WindowsMotionController;
  67477. })(BABYLON || (BABYLON = {}));
  67478. //# sourceMappingURL=babylon.windowsMotionController.js.map
  67479. "use strict";
  67480. var BABYLON;
  67481. (function (BABYLON) {
  67482. var GearVRController = /** @class */ (function (_super) {
  67483. __extends(GearVRController, _super);
  67484. function GearVRController(vrGamepad) {
  67485. var _this = _super.call(this, vrGamepad) || this;
  67486. _this._buttonIndexToObservableNameMap = [
  67487. 'onTrackpadChangedObservable',
  67488. 'onTriggerStateChangedObservable' // Trigger
  67489. ];
  67490. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  67491. return _this;
  67492. }
  67493. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67494. var _this = this;
  67495. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  67496. _this._defaultModel = newMeshes[1];
  67497. _this.attachToMesh(_this._defaultModel);
  67498. if (meshLoaded) {
  67499. meshLoaded(_this._defaultModel);
  67500. }
  67501. });
  67502. };
  67503. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67504. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  67505. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  67506. // Only emit events for buttons that we know how to map from index to observable
  67507. var observable = this[observableName];
  67508. if (observable) {
  67509. observable.notifyObservers(state);
  67510. }
  67511. }
  67512. };
  67513. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67514. GearVRController.MODEL_FILENAME = 'generic.babylon';
  67515. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  67516. return GearVRController;
  67517. }(BABYLON.WebVRController));
  67518. BABYLON.GearVRController = GearVRController;
  67519. })(BABYLON || (BABYLON = {}));
  67520. //# sourceMappingURL=babylon.gearVRController.js.map
  67521. "use strict";
  67522. var BABYLON;
  67523. (function (BABYLON) {
  67524. /**
  67525. * Google Daydream controller
  67526. */
  67527. var DaydreamController = /** @class */ (function (_super) {
  67528. __extends(DaydreamController, _super);
  67529. function DaydreamController(vrGamepad) {
  67530. var _this = _super.call(this, vrGamepad) || this;
  67531. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  67532. return _this;
  67533. }
  67534. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67535. var _this = this;
  67536. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67537. _this._defaultModel = newMeshes[1];
  67538. _this.attachToMesh(_this._defaultModel);
  67539. if (meshLoaded) {
  67540. meshLoaded(_this._defaultModel);
  67541. }
  67542. });
  67543. };
  67544. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67545. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67546. if (buttonIdx === 0) {
  67547. var observable = this.onTriggerStateChangedObservable;
  67548. if (observable) {
  67549. observable.notifyObservers(state);
  67550. }
  67551. }
  67552. else {
  67553. // If the app or home buttons are ever made available
  67554. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67555. }
  67556. };
  67557. /**
  67558. * Base Url for the controller model.
  67559. */
  67560. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67561. /**
  67562. * File name for the controller model.
  67563. */
  67564. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67565. /**
  67566. * Gamepad Id prefix used to identify Daydream Controller.
  67567. */
  67568. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67569. return DaydreamController;
  67570. }(BABYLON.WebVRController));
  67571. BABYLON.DaydreamController = DaydreamController;
  67572. })(BABYLON || (BABYLON = {}));
  67573. //# sourceMappingURL=babylon.daydreamController.js.map
  67574. "use strict";
  67575. var BABYLON;
  67576. (function (BABYLON) {
  67577. var FollowCamera = /** @class */ (function (_super) {
  67578. __extends(FollowCamera, _super);
  67579. function FollowCamera(name, position, scene, lockedTarget) {
  67580. if (lockedTarget === void 0) { lockedTarget = null; }
  67581. var _this = _super.call(this, name, position, scene) || this;
  67582. _this.radius = 12;
  67583. _this.rotationOffset = 0;
  67584. _this.heightOffset = 4;
  67585. _this.cameraAcceleration = 0.05;
  67586. _this.maxCameraSpeed = 20;
  67587. _this.lockedTarget = lockedTarget;
  67588. return _this;
  67589. }
  67590. FollowCamera.prototype.getRadians = function (degrees) {
  67591. return degrees * Math.PI / 180;
  67592. };
  67593. FollowCamera.prototype.follow = function (cameraTarget) {
  67594. if (!cameraTarget)
  67595. return;
  67596. var yRotation;
  67597. if (cameraTarget.rotationQuaternion) {
  67598. var rotMatrix = new BABYLON.Matrix();
  67599. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67600. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67601. }
  67602. else {
  67603. yRotation = cameraTarget.rotation.y;
  67604. }
  67605. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67606. var targetPosition = cameraTarget.getAbsolutePosition();
  67607. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67608. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67609. var dx = targetX - this.position.x;
  67610. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67611. var dz = (targetZ) - this.position.z;
  67612. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67613. var vy = dy * this.cameraAcceleration;
  67614. var vz = dz * this.cameraAcceleration * 2;
  67615. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67616. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67617. }
  67618. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67619. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67620. }
  67621. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67622. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67623. }
  67624. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67625. this.setTarget(targetPosition);
  67626. };
  67627. FollowCamera.prototype._checkInputs = function () {
  67628. _super.prototype._checkInputs.call(this);
  67629. if (this.lockedTarget) {
  67630. this.follow(this.lockedTarget);
  67631. }
  67632. };
  67633. FollowCamera.prototype.getClassName = function () {
  67634. return "FollowCamera";
  67635. };
  67636. __decorate([
  67637. BABYLON.serialize()
  67638. ], FollowCamera.prototype, "radius", void 0);
  67639. __decorate([
  67640. BABYLON.serialize()
  67641. ], FollowCamera.prototype, "rotationOffset", void 0);
  67642. __decorate([
  67643. BABYLON.serialize()
  67644. ], FollowCamera.prototype, "heightOffset", void 0);
  67645. __decorate([
  67646. BABYLON.serialize()
  67647. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67648. __decorate([
  67649. BABYLON.serialize()
  67650. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67651. __decorate([
  67652. BABYLON.serializeAsMeshReference("lockedTargetId")
  67653. ], FollowCamera.prototype, "lockedTarget", void 0);
  67654. return FollowCamera;
  67655. }(BABYLON.TargetCamera));
  67656. BABYLON.FollowCamera = FollowCamera;
  67657. var ArcFollowCamera = /** @class */ (function (_super) {
  67658. __extends(ArcFollowCamera, _super);
  67659. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67660. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67661. _this.alpha = alpha;
  67662. _this.beta = beta;
  67663. _this.radius = radius;
  67664. _this.target = target;
  67665. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67666. _this.follow();
  67667. return _this;
  67668. }
  67669. ArcFollowCamera.prototype.follow = function () {
  67670. if (!this.target) {
  67671. return;
  67672. }
  67673. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67674. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67675. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67676. var targetPosition = this.target.getAbsolutePosition();
  67677. this.position = targetPosition.add(this._cartesianCoordinates);
  67678. this.setTarget(targetPosition);
  67679. };
  67680. ArcFollowCamera.prototype._checkInputs = function () {
  67681. _super.prototype._checkInputs.call(this);
  67682. this.follow();
  67683. };
  67684. ArcFollowCamera.prototype.getClassName = function () {
  67685. return "ArcFollowCamera";
  67686. };
  67687. return ArcFollowCamera;
  67688. }(BABYLON.TargetCamera));
  67689. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67690. })(BABYLON || (BABYLON = {}));
  67691. //# sourceMappingURL=babylon.followCamera.js.map
  67692. "use strict";
  67693. var BABYLON;
  67694. (function (BABYLON) {
  67695. // We're mainly based on the logic defined into the FreeCamera code
  67696. var UniversalCamera = /** @class */ (function (_super) {
  67697. __extends(UniversalCamera, _super);
  67698. //-- end properties for backward compatibility for inputs
  67699. function UniversalCamera(name, position, scene) {
  67700. var _this = _super.call(this, name, position, scene) || this;
  67701. _this.inputs.addGamepad();
  67702. return _this;
  67703. }
  67704. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67705. //-- Begin properties for backward compatibility for inputs
  67706. get: function () {
  67707. var gamepad = this.inputs.attached["gamepad"];
  67708. if (gamepad)
  67709. return gamepad.gamepadAngularSensibility;
  67710. return 0;
  67711. },
  67712. set: function (value) {
  67713. var gamepad = this.inputs.attached["gamepad"];
  67714. if (gamepad)
  67715. gamepad.gamepadAngularSensibility = value;
  67716. },
  67717. enumerable: true,
  67718. configurable: true
  67719. });
  67720. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67721. get: function () {
  67722. var gamepad = this.inputs.attached["gamepad"];
  67723. if (gamepad)
  67724. return gamepad.gamepadMoveSensibility;
  67725. return 0;
  67726. },
  67727. set: function (value) {
  67728. var gamepad = this.inputs.attached["gamepad"];
  67729. if (gamepad)
  67730. gamepad.gamepadMoveSensibility = value;
  67731. },
  67732. enumerable: true,
  67733. configurable: true
  67734. });
  67735. UniversalCamera.prototype.getClassName = function () {
  67736. return "UniversalCamera";
  67737. };
  67738. return UniversalCamera;
  67739. }(BABYLON.TouchCamera));
  67740. BABYLON.UniversalCamera = UniversalCamera;
  67741. })(BABYLON || (BABYLON = {}));
  67742. //# sourceMappingURL=babylon.universalCamera.js.map
  67743. "use strict";
  67744. var BABYLON;
  67745. (function (BABYLON) {
  67746. // We're mainly based on the logic defined into the FreeCamera code
  67747. var GamepadCamera = /** @class */ (function (_super) {
  67748. __extends(GamepadCamera, _super);
  67749. //-- end properties for backward compatibility for inputs
  67750. function GamepadCamera(name, position, scene) {
  67751. return _super.call(this, name, position, scene) || this;
  67752. }
  67753. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67754. //-- Begin properties for backward compatibility for inputs
  67755. get: function () {
  67756. var gamepad = this.inputs.attached["gamepad"];
  67757. if (gamepad)
  67758. return gamepad.gamepadAngularSensibility;
  67759. return 0;
  67760. },
  67761. set: function (value) {
  67762. var gamepad = this.inputs.attached["gamepad"];
  67763. if (gamepad)
  67764. gamepad.gamepadAngularSensibility = value;
  67765. },
  67766. enumerable: true,
  67767. configurable: true
  67768. });
  67769. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67770. get: function () {
  67771. var gamepad = this.inputs.attached["gamepad"];
  67772. if (gamepad)
  67773. return gamepad.gamepadMoveSensibility;
  67774. return 0;
  67775. },
  67776. set: function (value) {
  67777. var gamepad = this.inputs.attached["gamepad"];
  67778. if (gamepad)
  67779. gamepad.gamepadMoveSensibility = value;
  67780. },
  67781. enumerable: true,
  67782. configurable: true
  67783. });
  67784. GamepadCamera.prototype.getClassName = function () {
  67785. return "GamepadCamera";
  67786. };
  67787. return GamepadCamera;
  67788. }(BABYLON.UniversalCamera));
  67789. BABYLON.GamepadCamera = GamepadCamera;
  67790. })(BABYLON || (BABYLON = {}));
  67791. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67792. "use strict";
  67793. var BABYLON;
  67794. (function (BABYLON) {
  67795. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67796. function PostProcessRenderPipelineManager() {
  67797. this._renderPipelines = {};
  67798. }
  67799. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67800. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67801. };
  67802. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67803. if (unique === void 0) { unique = false; }
  67804. var renderPipeline = this._renderPipelines[renderPipelineName];
  67805. if (!renderPipeline) {
  67806. return;
  67807. }
  67808. renderPipeline._attachCameras(cameras, unique);
  67809. };
  67810. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67811. var renderPipeline = this._renderPipelines[renderPipelineName];
  67812. if (!renderPipeline) {
  67813. return;
  67814. }
  67815. renderPipeline._detachCameras(cameras);
  67816. };
  67817. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67818. var renderPipeline = this._renderPipelines[renderPipelineName];
  67819. if (!renderPipeline) {
  67820. return;
  67821. }
  67822. renderPipeline._enableEffect(renderEffectName, cameras);
  67823. };
  67824. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67825. var renderPipeline = this._renderPipelines[renderPipelineName];
  67826. if (!renderPipeline) {
  67827. return;
  67828. }
  67829. renderPipeline._disableEffect(renderEffectName, cameras);
  67830. };
  67831. PostProcessRenderPipelineManager.prototype.update = function () {
  67832. for (var renderPipelineName in this._renderPipelines) {
  67833. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67834. var pipeline = this._renderPipelines[renderPipelineName];
  67835. if (!pipeline.isSupported) {
  67836. pipeline.dispose();
  67837. delete this._renderPipelines[renderPipelineName];
  67838. }
  67839. else {
  67840. pipeline._update();
  67841. }
  67842. }
  67843. }
  67844. };
  67845. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67846. for (var renderPipelineName in this._renderPipelines) {
  67847. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67848. var pipeline = this._renderPipelines[renderPipelineName];
  67849. pipeline._rebuild();
  67850. }
  67851. }
  67852. };
  67853. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67854. for (var renderPipelineName in this._renderPipelines) {
  67855. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67856. var pipeline = this._renderPipelines[renderPipelineName];
  67857. pipeline.dispose();
  67858. }
  67859. }
  67860. };
  67861. return PostProcessRenderPipelineManager;
  67862. }());
  67863. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67864. })(BABYLON || (BABYLON = {}));
  67865. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67866. "use strict";
  67867. var BABYLON;
  67868. (function (BABYLON) {
  67869. /**
  67870. * This represents a set of one or more post processes in Babylon.
  67871. * A post process can be used to apply a shader to a texture after it is rendered.
  67872. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67873. */
  67874. var PostProcessRenderEffect = /** @class */ (function () {
  67875. /**
  67876. * Instantiates a post process render effect.
  67877. * A post process can be used to apply a shader to a texture after it is rendered.
  67878. * @param engine The engine the effect is tied to
  67879. * @param name The name of the effect
  67880. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67881. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67882. */
  67883. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67884. this._name = name;
  67885. this._singleInstance = singleInstance || true;
  67886. this._getPostProcesses = getPostProcesses;
  67887. this._cameras = {};
  67888. this._indicesForCamera = {};
  67889. this._postProcesses = {};
  67890. }
  67891. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67892. /**
  67893. * Checks if all the post processes in the effect are supported.
  67894. */
  67895. get: function () {
  67896. for (var index in this._postProcesses) {
  67897. for (var ppIndex in this._postProcesses[index]) {
  67898. if (!this._postProcesses[index][ppIndex].isSupported) {
  67899. return false;
  67900. }
  67901. }
  67902. }
  67903. return true;
  67904. },
  67905. enumerable: true,
  67906. configurable: true
  67907. });
  67908. /**
  67909. * Updates the current state of the effect
  67910. */
  67911. PostProcessRenderEffect.prototype._update = function () {
  67912. };
  67913. /**
  67914. * Attaches the effect on cameras
  67915. * @param cameras The camera to attach to.
  67916. */
  67917. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67918. var _this = this;
  67919. var cameraKey;
  67920. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67921. if (!cams) {
  67922. return;
  67923. }
  67924. for (var i = 0; i < cams.length; i++) {
  67925. var camera = cams[i];
  67926. var cameraName = camera.name;
  67927. if (this._singleInstance) {
  67928. cameraKey = 0;
  67929. }
  67930. else {
  67931. cameraKey = cameraName;
  67932. }
  67933. if (!this._postProcesses[cameraKey]) {
  67934. var postProcess = this._getPostProcesses();
  67935. if (postProcess) {
  67936. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67937. }
  67938. }
  67939. if (!this._indicesForCamera[cameraName]) {
  67940. this._indicesForCamera[cameraName] = [];
  67941. }
  67942. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67943. var index = camera.attachPostProcess(postProcess);
  67944. _this._indicesForCamera[cameraName].push(index);
  67945. });
  67946. if (!this._cameras[cameraName]) {
  67947. this._cameras[cameraName] = camera;
  67948. }
  67949. }
  67950. };
  67951. /**
  67952. * Detatches the effect on cameras
  67953. * @param cameras The camera to detatch from.
  67954. */
  67955. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67956. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67957. if (!cams) {
  67958. return;
  67959. }
  67960. for (var i = 0; i < cams.length; i++) {
  67961. var camera = cams[i];
  67962. var cameraName = camera.name;
  67963. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67964. camera.detachPostProcess(postProcess);
  67965. });
  67966. if (this._cameras[cameraName]) {
  67967. //this._indicesForCamera.splice(index, 1);
  67968. this._cameras[cameraName] = null;
  67969. }
  67970. }
  67971. };
  67972. /**
  67973. * Enables the effect on given cameras
  67974. * @param cameras The camera to enable.
  67975. */
  67976. PostProcessRenderEffect.prototype._enable = function (cameras) {
  67977. var _this = this;
  67978. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67979. if (!cams) {
  67980. return;
  67981. }
  67982. for (var i = 0; i < cams.length; i++) {
  67983. var camera = cams[i];
  67984. var cameraName = camera.name;
  67985. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  67986. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  67987. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67988. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  67989. });
  67990. }
  67991. }
  67992. }
  67993. };
  67994. /**
  67995. * Disables the effect on the given cameras
  67996. * @param cameras The camera to disable.
  67997. */
  67998. PostProcessRenderEffect.prototype._disable = function (cameras) {
  67999. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68000. if (!cams) {
  68001. return;
  68002. }
  68003. for (var i = 0; i < cams.length; i++) {
  68004. var camera = cams[i];
  68005. var cameraName = camera.name;
  68006. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68007. camera.detachPostProcess(postProcess);
  68008. });
  68009. }
  68010. };
  68011. /**
  68012. * Gets a list of the post processes contained in the effect.
  68013. * @param camera The camera to get the post processes on.
  68014. * @returns The list of the post processes in the effect.
  68015. */
  68016. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  68017. if (this._singleInstance) {
  68018. return this._postProcesses[0];
  68019. }
  68020. else {
  68021. if (!camera) {
  68022. return null;
  68023. }
  68024. return this._postProcesses[camera.name];
  68025. }
  68026. };
  68027. return PostProcessRenderEffect;
  68028. }());
  68029. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  68030. })(BABYLON || (BABYLON = {}));
  68031. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  68032. "use strict";
  68033. var BABYLON;
  68034. (function (BABYLON) {
  68035. var PostProcessRenderPipeline = /** @class */ (function () {
  68036. function PostProcessRenderPipeline(engine, name) {
  68037. this.engine = engine;
  68038. this._name = name;
  68039. this._renderEffects = {};
  68040. this._renderEffectsForIsolatedPass = new Array();
  68041. this._cameras = [];
  68042. }
  68043. PostProcessRenderPipeline.prototype.getClassName = function () {
  68044. return "PostProcessRenderPipeline";
  68045. };
  68046. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  68047. get: function () {
  68048. for (var renderEffectName in this._renderEffects) {
  68049. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68050. if (!this._renderEffects[renderEffectName].isSupported) {
  68051. return false;
  68052. }
  68053. }
  68054. }
  68055. return true;
  68056. },
  68057. enumerable: true,
  68058. configurable: true
  68059. });
  68060. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  68061. this._renderEffects[renderEffect._name] = renderEffect;
  68062. };
  68063. // private
  68064. PostProcessRenderPipeline.prototype._rebuild = function () {
  68065. };
  68066. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  68067. var renderEffects = this._renderEffects[renderEffectName];
  68068. if (!renderEffects) {
  68069. return;
  68070. }
  68071. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68072. };
  68073. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  68074. var renderEffects = this._renderEffects[renderEffectName];
  68075. if (!renderEffects) {
  68076. return;
  68077. }
  68078. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68079. };
  68080. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  68081. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68082. if (!cams) {
  68083. return;
  68084. }
  68085. var indicesToDelete = [];
  68086. var i;
  68087. for (i = 0; i < cams.length; i++) {
  68088. var camera = cams[i];
  68089. var cameraName = camera.name;
  68090. if (this._cameras.indexOf(camera) === -1) {
  68091. this._cameras[cameraName] = camera;
  68092. }
  68093. else if (unique) {
  68094. indicesToDelete.push(i);
  68095. }
  68096. }
  68097. for (i = 0; i < indicesToDelete.length; i++) {
  68098. cameras.splice(indicesToDelete[i], 1);
  68099. }
  68100. for (var renderEffectName in this._renderEffects) {
  68101. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68102. this._renderEffects[renderEffectName]._attachCameras(cams);
  68103. }
  68104. }
  68105. };
  68106. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  68107. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68108. if (!cams) {
  68109. return;
  68110. }
  68111. for (var renderEffectName in this._renderEffects) {
  68112. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68113. this._renderEffects[renderEffectName]._detachCameras(cams);
  68114. }
  68115. }
  68116. for (var i = 0; i < cams.length; i++) {
  68117. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  68118. }
  68119. };
  68120. PostProcessRenderPipeline.prototype._update = function () {
  68121. for (var renderEffectName in this._renderEffects) {
  68122. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68123. this._renderEffects[renderEffectName]._update();
  68124. }
  68125. }
  68126. for (var i = 0; i < this._cameras.length; i++) {
  68127. var cameraName = this._cameras[i].name;
  68128. if (this._renderEffectsForIsolatedPass[cameraName]) {
  68129. this._renderEffectsForIsolatedPass[cameraName]._update();
  68130. }
  68131. }
  68132. };
  68133. PostProcessRenderPipeline.prototype._reset = function () {
  68134. this._renderEffects = {};
  68135. this._renderEffectsForIsolatedPass = new Array();
  68136. };
  68137. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  68138. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  68139. var effectKeys = Object.keys(this._renderEffects);
  68140. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  68141. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  68142. if (postProcesses) {
  68143. postProcesses[0].samples = 4;
  68144. return true;
  68145. }
  68146. }
  68147. return false;
  68148. };
  68149. PostProcessRenderPipeline.prototype.dispose = function () {
  68150. // Must be implemented by children
  68151. };
  68152. __decorate([
  68153. BABYLON.serialize()
  68154. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  68155. return PostProcessRenderPipeline;
  68156. }());
  68157. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  68158. })(BABYLON || (BABYLON = {}));
  68159. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  68160. "use strict";
  68161. var BABYLON;
  68162. (function (BABYLON) {
  68163. /**
  68164. * This represents a depth renderer in Babylon.
  68165. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  68166. */
  68167. var DepthRenderer = /** @class */ (function () {
  68168. /**
  68169. * Instantiates a depth renderer
  68170. * @param scene The scene the renderer belongs to
  68171. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  68172. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  68173. */
  68174. function DepthRenderer(scene, type, camera) {
  68175. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68176. if (camera === void 0) { camera = null; }
  68177. var _this = this;
  68178. this._scene = scene;
  68179. this._camera = camera;
  68180. var engine = scene.getEngine();
  68181. // Render target
  68182. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  68183. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68184. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68185. this._depthMap.refreshRate = 1;
  68186. this._depthMap.renderParticles = false;
  68187. this._depthMap.renderList = null;
  68188. // Camera to get depth map from to support multiple concurrent cameras
  68189. this._depthMap.activeCamera = this._camera;
  68190. this._depthMap.ignoreCameraViewport = true;
  68191. this._depthMap.useCameraPostProcesses = false;
  68192. // set default depth value to 1.0 (far away)
  68193. this._depthMap.onClearObservable.add(function (engine) {
  68194. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  68195. });
  68196. // Custom render function
  68197. var renderSubMesh = function (subMesh) {
  68198. var mesh = subMesh.getRenderingMesh();
  68199. var scene = _this._scene;
  68200. var engine = scene.getEngine();
  68201. var material = subMesh.getMaterial();
  68202. if (!material) {
  68203. return;
  68204. }
  68205. // Culling and reverse (right handed system)
  68206. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68207. // Managing instances
  68208. var batch = mesh._getInstancesRenderList(subMesh._id);
  68209. if (batch.mustReturn) {
  68210. return;
  68211. }
  68212. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68213. var camera = _this._camera || scene.activeCamera;
  68214. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  68215. engine.enableEffect(_this._effect);
  68216. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68217. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68218. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  68219. // Alpha test
  68220. if (material && material.needAlphaTesting()) {
  68221. var alphaTexture = material.getAlphaTestTexture();
  68222. if (alphaTexture) {
  68223. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68224. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68225. }
  68226. }
  68227. // Bones
  68228. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68229. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68230. }
  68231. // Draw
  68232. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68233. }
  68234. };
  68235. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68236. var index;
  68237. if (depthOnlySubMeshes.length) {
  68238. engine.setColorWrite(false);
  68239. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68240. renderSubMesh(depthOnlySubMeshes.data[index]);
  68241. }
  68242. engine.setColorWrite(true);
  68243. }
  68244. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68245. renderSubMesh(opaqueSubMeshes.data[index]);
  68246. }
  68247. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68248. renderSubMesh(alphaTestSubMeshes.data[index]);
  68249. }
  68250. };
  68251. }
  68252. /**
  68253. * Creates the depth rendering effect and checks if the effect is ready.
  68254. * @param subMesh The submesh to be used to render the depth map of
  68255. * @param useInstances If multiple world instances should be used
  68256. * @returns if the depth renderer is ready to render the depth map
  68257. */
  68258. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  68259. var material = subMesh.getMaterial();
  68260. if (material.disableDepthWrite) {
  68261. return false;
  68262. }
  68263. var defines = [];
  68264. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68265. var mesh = subMesh.getMesh();
  68266. // Alpha test
  68267. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  68268. defines.push("#define ALPHATEST");
  68269. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68270. attribs.push(BABYLON.VertexBuffer.UVKind);
  68271. defines.push("#define UV1");
  68272. }
  68273. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68274. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68275. defines.push("#define UV2");
  68276. }
  68277. }
  68278. // Bones
  68279. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68280. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68281. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68282. if (mesh.numBoneInfluencers > 4) {
  68283. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68284. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68285. }
  68286. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68287. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68288. }
  68289. else {
  68290. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68291. }
  68292. // Instances
  68293. if (useInstances) {
  68294. defines.push("#define INSTANCES");
  68295. attribs.push("world0");
  68296. attribs.push("world1");
  68297. attribs.push("world2");
  68298. attribs.push("world3");
  68299. }
  68300. // Get correct effect
  68301. var join = defines.join("\n");
  68302. if (this._cachedDefines !== join) {
  68303. this._cachedDefines = join;
  68304. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  68305. }
  68306. return this._effect.isReady();
  68307. };
  68308. /**
  68309. * Gets the texture which the depth map will be written to.
  68310. * @returns The depth map texture
  68311. */
  68312. DepthRenderer.prototype.getDepthMap = function () {
  68313. return this._depthMap;
  68314. };
  68315. /**
  68316. * Disposes of the depth renderer.
  68317. */
  68318. DepthRenderer.prototype.dispose = function () {
  68319. this._depthMap.dispose();
  68320. };
  68321. return DepthRenderer;
  68322. }());
  68323. BABYLON.DepthRenderer = DepthRenderer;
  68324. })(BABYLON || (BABYLON = {}));
  68325. //# sourceMappingURL=babylon.depthRenderer.js.map
  68326. "use strict";
  68327. var BABYLON;
  68328. (function (BABYLON) {
  68329. var SSAORenderingPipeline = /** @class */ (function (_super) {
  68330. __extends(SSAORenderingPipeline, _super);
  68331. /**
  68332. * @constructor
  68333. * @param {string} name - The rendering pipeline name
  68334. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68335. * @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 }
  68336. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68337. */
  68338. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  68339. var _this = _super.call(this, scene.getEngine(), name) || this;
  68340. // Members
  68341. /**
  68342. * The PassPostProcess id in the pipeline that contains the original scene color
  68343. * @type {string}
  68344. */
  68345. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68346. /**
  68347. * The SSAO PostProcess id in the pipeline
  68348. * @type {string}
  68349. */
  68350. _this.SSAORenderEffect = "SSAORenderEffect";
  68351. /**
  68352. * The horizontal blur PostProcess id in the pipeline
  68353. * @type {string}
  68354. */
  68355. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68356. /**
  68357. * The vertical blur PostProcess id in the pipeline
  68358. * @type {string}
  68359. */
  68360. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68361. /**
  68362. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68363. * @type {string}
  68364. */
  68365. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68366. /**
  68367. * The output strength of the SSAO post-process. Default value is 1.0.
  68368. * @type {number}
  68369. */
  68370. _this.totalStrength = 1.0;
  68371. /**
  68372. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  68373. * @type {number}
  68374. */
  68375. _this.radius = 0.0001;
  68376. /**
  68377. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  68378. * Must not be equal to fallOff and superior to fallOff.
  68379. * Default value is 0.975
  68380. * @type {number}
  68381. */
  68382. _this.area = 0.0075;
  68383. /**
  68384. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  68385. * Must not be equal to area and inferior to area.
  68386. * Default value is 0.0
  68387. * @type {number}
  68388. */
  68389. _this.fallOff = 0.000001;
  68390. /**
  68391. * The base color of the SSAO post-process
  68392. * The final result is "base + ssao" between [0, 1]
  68393. * @type {number}
  68394. */
  68395. _this.base = 0.5;
  68396. _this._firstUpdate = true;
  68397. _this._scene = scene;
  68398. // Set up assets
  68399. _this._createRandomTexture();
  68400. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68401. var ssaoRatio = ratio.ssaoRatio || ratio;
  68402. var combineRatio = ratio.combineRatio || ratio;
  68403. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68404. _this._createSSAOPostProcess(ssaoRatio);
  68405. _this._createBlurPostProcess(ssaoRatio);
  68406. _this._createSSAOCombinePostProcess(combineRatio);
  68407. // Set up pipeline
  68408. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68409. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68410. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68411. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68412. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68413. // Finish
  68414. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68415. if (cameras)
  68416. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68417. return _this;
  68418. }
  68419. // Public Methods
  68420. /**
  68421. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68422. */
  68423. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68424. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68425. for (var i = 0; i < this._scene.cameras.length; i++) {
  68426. var camera = this._scene.cameras[i];
  68427. this._originalColorPostProcess.dispose(camera);
  68428. this._ssaoPostProcess.dispose(camera);
  68429. this._blurHPostProcess.dispose(camera);
  68430. this._blurVPostProcess.dispose(camera);
  68431. this._ssaoCombinePostProcess.dispose(camera);
  68432. }
  68433. this._randomTexture.dispose();
  68434. if (disableDepthRender)
  68435. this._scene.disableDepthRenderer();
  68436. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68437. _super.prototype.dispose.call(this);
  68438. };
  68439. // Private Methods
  68440. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  68441. var _this = this;
  68442. var size = 16;
  68443. 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);
  68444. 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);
  68445. this._blurHPostProcess.onActivateObservable.add(function () {
  68446. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  68447. _this._blurHPostProcess.kernel = size * dw;
  68448. });
  68449. this._blurVPostProcess.onActivateObservable.add(function () {
  68450. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  68451. _this._blurVPostProcess.kernel = size * dw;
  68452. });
  68453. };
  68454. SSAORenderingPipeline.prototype._rebuild = function () {
  68455. this._firstUpdate = true;
  68456. _super.prototype._rebuild.call(this);
  68457. };
  68458. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68459. var _this = this;
  68460. var numSamples = 16;
  68461. var sampleSphere = [
  68462. 0.5381, 0.1856, -0.4319,
  68463. 0.1379, 0.2486, 0.4430,
  68464. 0.3371, 0.5679, -0.0057,
  68465. -0.6999, -0.0451, -0.0019,
  68466. 0.0689, -0.1598, -0.8547,
  68467. 0.0560, 0.0069, -0.1843,
  68468. -0.0146, 0.1402, 0.0762,
  68469. 0.0100, -0.1924, -0.0344,
  68470. -0.3577, -0.5301, -0.4358,
  68471. -0.3169, 0.1063, 0.0158,
  68472. 0.0103, -0.5869, 0.0046,
  68473. -0.0897, -0.4940, 0.3287,
  68474. 0.7119, -0.0154, -0.0918,
  68475. -0.0533, 0.0596, -0.5411,
  68476. 0.0352, -0.0631, 0.5460,
  68477. -0.4776, 0.2847, -0.0271
  68478. ];
  68479. var samplesFactor = 1.0 / numSamples;
  68480. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  68481. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68482. "area", "fallOff", "base", "range", "viewport"
  68483. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68484. this._ssaoPostProcess.onApply = function (effect) {
  68485. if (_this._firstUpdate) {
  68486. effect.setArray3("sampleSphere", sampleSphere);
  68487. effect.setFloat("samplesFactor", samplesFactor);
  68488. effect.setFloat("randTextureTiles", 4.0);
  68489. }
  68490. effect.setFloat("totalStrength", _this.totalStrength);
  68491. effect.setFloat("radius", _this.radius);
  68492. effect.setFloat("area", _this.area);
  68493. effect.setFloat("fallOff", _this.fallOff);
  68494. effect.setFloat("base", _this.base);
  68495. effect.setTexture("textureSampler", _this._depthTexture);
  68496. effect.setTexture("randomSampler", _this._randomTexture);
  68497. };
  68498. };
  68499. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68500. var _this = this;
  68501. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68502. this._ssaoCombinePostProcess.onApply = function (effect) {
  68503. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68504. };
  68505. };
  68506. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  68507. var size = 512;
  68508. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68509. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68510. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68511. var context = this._randomTexture.getContext();
  68512. var rand = function (min, max) {
  68513. return Math.random() * (max - min) + min;
  68514. };
  68515. var randVector = BABYLON.Vector3.Zero();
  68516. for (var x = 0; x < size; x++) {
  68517. for (var y = 0; y < size; y++) {
  68518. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  68519. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  68520. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  68521. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68522. context.fillRect(x, y, 1, 1);
  68523. }
  68524. }
  68525. this._randomTexture.update(false);
  68526. };
  68527. __decorate([
  68528. BABYLON.serialize()
  68529. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  68530. __decorate([
  68531. BABYLON.serialize()
  68532. ], SSAORenderingPipeline.prototype, "radius", void 0);
  68533. __decorate([
  68534. BABYLON.serialize()
  68535. ], SSAORenderingPipeline.prototype, "area", void 0);
  68536. __decorate([
  68537. BABYLON.serialize()
  68538. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  68539. __decorate([
  68540. BABYLON.serialize()
  68541. ], SSAORenderingPipeline.prototype, "base", void 0);
  68542. return SSAORenderingPipeline;
  68543. }(BABYLON.PostProcessRenderPipeline));
  68544. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68545. })(BABYLON || (BABYLON = {}));
  68546. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68547. "use strict";
  68548. var BABYLON;
  68549. (function (BABYLON) {
  68550. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68551. __extends(SSAO2RenderingPipeline, _super);
  68552. /**
  68553. * @constructor
  68554. * @param {string} name - The rendering pipeline name
  68555. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68556. * @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 }
  68557. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68558. */
  68559. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68560. var _this = _super.call(this, scene.getEngine(), name) || this;
  68561. // Members
  68562. /**
  68563. * The PassPostProcess id in the pipeline that contains the original scene color
  68564. * @type {string}
  68565. */
  68566. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68567. /**
  68568. * The SSAO PostProcess id in the pipeline
  68569. * @type {string}
  68570. */
  68571. _this.SSAORenderEffect = "SSAORenderEffect";
  68572. /**
  68573. * The horizontal blur PostProcess id in the pipeline
  68574. * @type {string}
  68575. */
  68576. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68577. /**
  68578. * The vertical blur PostProcess id in the pipeline
  68579. * @type {string}
  68580. */
  68581. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68582. /**
  68583. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68584. * @type {string}
  68585. */
  68586. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68587. /**
  68588. * The output strength of the SSAO post-process. Default value is 1.0.
  68589. * @type {number}
  68590. */
  68591. _this.totalStrength = 1.0;
  68592. /**
  68593. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68594. * @type {number}
  68595. */
  68596. _this.maxZ = 100.0;
  68597. /**
  68598. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68599. * @type {number}
  68600. */
  68601. _this.minZAspect = 0.2;
  68602. /**
  68603. * Number of samples used for the SSAO calculations. Default value is 8
  68604. * @type {number}
  68605. */
  68606. _this._samples = 8;
  68607. /**
  68608. * Are we using bilateral blur ?
  68609. * @type {boolean}
  68610. */
  68611. _this._expensiveBlur = true;
  68612. /**
  68613. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68614. * @type {number}
  68615. */
  68616. _this.radius = 2.0;
  68617. /**
  68618. * The base color of the SSAO post-process
  68619. * The final result is "base + ssao" between [0, 1]
  68620. * @type {number}
  68621. */
  68622. _this.base = 0.1;
  68623. _this._firstUpdate = true;
  68624. _this._scene = scene;
  68625. if (!_this.isSupported) {
  68626. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68627. return _this;
  68628. }
  68629. var ssaoRatio = ratio.ssaoRatio || ratio;
  68630. var blurRatio = ratio.blurRatio || ratio;
  68631. // Set up assets
  68632. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68633. _this._createRandomTexture();
  68634. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68635. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68636. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68637. _this._createSSAOPostProcess(1.0);
  68638. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68639. _this._createSSAOCombinePostProcess(blurRatio);
  68640. // Set up pipeline
  68641. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68642. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68643. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68644. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68645. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68646. // Finish
  68647. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68648. if (cameras)
  68649. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68650. return _this;
  68651. }
  68652. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68653. get: function () {
  68654. return this._samples;
  68655. },
  68656. set: function (n) {
  68657. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68658. this._samples = n;
  68659. this._sampleSphere = this._generateHemisphere();
  68660. this._firstUpdate = true;
  68661. },
  68662. enumerable: true,
  68663. configurable: true
  68664. });
  68665. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68666. get: function () {
  68667. return this._expensiveBlur;
  68668. },
  68669. set: function (b) {
  68670. 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"]);
  68671. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68672. this._expensiveBlur = b;
  68673. this._firstUpdate = true;
  68674. },
  68675. enumerable: true,
  68676. configurable: true
  68677. });
  68678. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68679. /**
  68680. * Support test.
  68681. * @type {boolean}
  68682. */
  68683. get: function () {
  68684. var engine = BABYLON.Engine.LastCreatedEngine;
  68685. if (!engine) {
  68686. return false;
  68687. }
  68688. return engine.getCaps().drawBuffersExtension;
  68689. },
  68690. enumerable: true,
  68691. configurable: true
  68692. });
  68693. // Public Methods
  68694. /**
  68695. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68696. */
  68697. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68698. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68699. for (var i = 0; i < this._scene.cameras.length; i++) {
  68700. var camera = this._scene.cameras[i];
  68701. this._originalColorPostProcess.dispose(camera);
  68702. this._ssaoPostProcess.dispose(camera);
  68703. this._blurHPostProcess.dispose(camera);
  68704. this._blurVPostProcess.dispose(camera);
  68705. this._ssaoCombinePostProcess.dispose(camera);
  68706. }
  68707. this._randomTexture.dispose();
  68708. if (disableGeometryBufferRenderer)
  68709. this._scene.disableGeometryBufferRenderer();
  68710. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68711. _super.prototype.dispose.call(this);
  68712. };
  68713. // Private Methods
  68714. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68715. var _this = this;
  68716. this._samplerOffsets = [];
  68717. var expensive = this.expensiveBlur;
  68718. for (var i = -8; i < 8; i++) {
  68719. this._samplerOffsets.push(i * 2 + 0.5);
  68720. }
  68721. 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");
  68722. this._blurHPostProcess.onApply = function (effect) {
  68723. if (!_this._scene.activeCamera) {
  68724. return;
  68725. }
  68726. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68727. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68728. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68729. effect.setFloat("radius", _this.radius);
  68730. effect.setTexture("depthSampler", _this._depthTexture);
  68731. if (_this._firstUpdate) {
  68732. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68733. }
  68734. };
  68735. 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");
  68736. this._blurVPostProcess.onApply = function (effect) {
  68737. if (!_this._scene.activeCamera) {
  68738. return;
  68739. }
  68740. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68741. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68742. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68743. effect.setFloat("radius", _this.radius);
  68744. effect.setTexture("depthSampler", _this._depthTexture);
  68745. if (_this._firstUpdate) {
  68746. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68747. _this._firstUpdate = false;
  68748. }
  68749. };
  68750. };
  68751. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68752. this._firstUpdate = true;
  68753. _super.prototype._rebuild.call(this);
  68754. };
  68755. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68756. var numSamples = this.samples;
  68757. var result = [];
  68758. var vector, scale;
  68759. var rand = function (min, max) {
  68760. return Math.random() * (max - min) + min;
  68761. };
  68762. var i = 0;
  68763. while (i < numSamples) {
  68764. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68765. vector.normalize();
  68766. scale = i / numSamples;
  68767. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68768. vector.scaleInPlace(scale);
  68769. result.push(vector.x, vector.y, vector.z);
  68770. i++;
  68771. }
  68772. return result;
  68773. };
  68774. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68775. var _this = this;
  68776. var numSamples = this.samples;
  68777. this._sampleSphere = this._generateHemisphere();
  68778. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68779. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68780. "base", "range", "projection", "near", "far", "texelSize",
  68781. "xViewport", "yViewport", "maxZ", "minZAspect"
  68782. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68783. this._ssaoPostProcess.onApply = function (effect) {
  68784. if (_this._firstUpdate) {
  68785. effect.setArray3("sampleSphere", _this._sampleSphere);
  68786. effect.setFloat("randTextureTiles", 4.0);
  68787. }
  68788. if (!_this._scene.activeCamera) {
  68789. return;
  68790. }
  68791. effect.setFloat("samplesFactor", 1 / _this.samples);
  68792. effect.setFloat("totalStrength", _this.totalStrength);
  68793. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68794. effect.setFloat("radius", _this.radius);
  68795. effect.setFloat("maxZ", _this.maxZ);
  68796. effect.setFloat("minZAspect", _this.minZAspect);
  68797. effect.setFloat("base", _this.base);
  68798. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68799. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68800. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68801. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68802. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68803. effect.setTexture("textureSampler", _this._depthTexture);
  68804. effect.setTexture("normalSampler", _this._normalTexture);
  68805. effect.setTexture("randomSampler", _this._randomTexture);
  68806. };
  68807. };
  68808. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68809. var _this = this;
  68810. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68811. this._ssaoCombinePostProcess.onApply = function (effect) {
  68812. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68813. };
  68814. };
  68815. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68816. var size = 512;
  68817. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68818. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68819. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68820. var context = this._randomTexture.getContext();
  68821. var rand = function (min, max) {
  68822. return Math.random() * (max - min) + min;
  68823. };
  68824. var randVector = BABYLON.Vector3.Zero();
  68825. for (var x = 0; x < size; x++) {
  68826. for (var y = 0; y < size; y++) {
  68827. randVector.x = rand(0.0, 1.0);
  68828. randVector.y = rand(0.0, 1.0);
  68829. randVector.z = 0.0;
  68830. randVector.normalize();
  68831. randVector.scaleInPlace(255);
  68832. randVector.x = Math.floor(randVector.x);
  68833. randVector.y = Math.floor(randVector.y);
  68834. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68835. context.fillRect(x, y, 1, 1);
  68836. }
  68837. }
  68838. this._randomTexture.update(false);
  68839. };
  68840. __decorate([
  68841. BABYLON.serialize()
  68842. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68843. __decorate([
  68844. BABYLON.serialize()
  68845. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68846. __decorate([
  68847. BABYLON.serialize()
  68848. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68849. __decorate([
  68850. BABYLON.serialize("samples")
  68851. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68852. __decorate([
  68853. BABYLON.serialize("expensiveBlur")
  68854. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68855. __decorate([
  68856. BABYLON.serialize()
  68857. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68858. __decorate([
  68859. BABYLON.serialize()
  68860. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68861. return SSAO2RenderingPipeline;
  68862. }(BABYLON.PostProcessRenderPipeline));
  68863. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68864. })(BABYLON || (BABYLON = {}));
  68865. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68866. "use strict";
  68867. // BABYLON.JS Chromatic Aberration GLSL Shader
  68868. // Author: Olivier Guyot
  68869. // Separates very slightly R, G and B colors on the edges of the screen
  68870. // Inspired by Francois Tarlier & Martins Upitis
  68871. var BABYLON;
  68872. (function (BABYLON) {
  68873. var LensRenderingPipeline = /** @class */ (function (_super) {
  68874. __extends(LensRenderingPipeline, _super);
  68875. /**
  68876. * @constructor
  68877. *
  68878. * Effect parameters are as follow:
  68879. * {
  68880. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68881. * edge_blur: number; // from 0 to x (1 for realism)
  68882. * distortion: number; // from 0 to x (1 for realism)
  68883. * grain_amount: number; // from 0 to 1
  68884. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68885. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68886. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68887. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68888. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68889. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68890. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68891. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68892. * }
  68893. * Note: if an effect parameter is unset, effect is disabled
  68894. *
  68895. * @param {string} name - The rendering pipeline name
  68896. * @param {object} parameters - An object containing all parameters (see above)
  68897. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68898. * @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)
  68899. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68900. */
  68901. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68902. if (ratio === void 0) { ratio = 1.0; }
  68903. var _this = _super.call(this, scene.getEngine(), name) || this;
  68904. // Lens effects can be of the following:
  68905. // - chromatic aberration (slight shift of RGB colors)
  68906. // - blur on the edge of the lens
  68907. // - lens distortion
  68908. // - depth-of-field blur & highlights enhancing
  68909. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68910. // - grain effect (noise or custom texture)
  68911. // Two additional texture samplers are needed:
  68912. // - depth map (for depth-of-field)
  68913. // - grain texture
  68914. /**
  68915. * The chromatic aberration PostProcess id in the pipeline
  68916. * @type {string}
  68917. */
  68918. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68919. /**
  68920. * The highlights enhancing PostProcess id in the pipeline
  68921. * @type {string}
  68922. */
  68923. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68924. /**
  68925. * The depth-of-field PostProcess id in the pipeline
  68926. * @type {string}
  68927. */
  68928. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68929. _this._scene = scene;
  68930. // Fetch texture samplers
  68931. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68932. if (parameters.grain_texture) {
  68933. _this._grainTexture = parameters.grain_texture;
  68934. }
  68935. else {
  68936. _this._createGrainTexture();
  68937. }
  68938. // save parameters
  68939. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68940. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68941. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68942. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68943. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68944. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68945. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68946. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68947. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68948. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68949. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68950. // Create effects
  68951. _this._createChromaticAberrationPostProcess(ratio);
  68952. _this._createHighlightsPostProcess(ratio);
  68953. _this._createDepthOfFieldPostProcess(ratio / 4);
  68954. // Set up pipeline
  68955. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68956. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68957. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68958. if (_this._highlightsGain === -1) {
  68959. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68960. }
  68961. // Finish
  68962. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68963. if (cameras) {
  68964. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68965. }
  68966. return _this;
  68967. }
  68968. // public methods (self explanatory)
  68969. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  68970. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  68971. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  68972. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  68973. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  68974. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  68975. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  68976. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  68977. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  68978. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  68979. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  68980. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  68981. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  68982. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  68983. };
  68984. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  68985. this._highlightsPostProcess.updateEffect();
  68986. };
  68987. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  68988. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  68989. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  68990. this._highlightsGain = amount;
  68991. };
  68992. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  68993. if (this._highlightsGain === -1) {
  68994. this._highlightsGain = 1.0;
  68995. }
  68996. this._highlightsThreshold = amount;
  68997. };
  68998. LensRenderingPipeline.prototype.disableHighlights = function () {
  68999. this._highlightsGain = -1;
  69000. };
  69001. /**
  69002. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  69003. */
  69004. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  69005. if (disableDepthRender === void 0) { disableDepthRender = false; }
  69006. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  69007. this._chromaticAberrationPostProcess = null;
  69008. this._highlightsPostProcess = null;
  69009. this._depthOfFieldPostProcess = null;
  69010. this._grainTexture.dispose();
  69011. if (disableDepthRender)
  69012. this._scene.disableDepthRenderer();
  69013. };
  69014. // colors shifting and distortion
  69015. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  69016. var _this = this;
  69017. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  69018. [], // samplers
  69019. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69020. this._chromaticAberrationPostProcess.onApply = function (effect) {
  69021. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  69022. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69023. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69024. effect.setFloat('radialIntensity', 1);
  69025. effect.setFloat2('direction', 17, 17);
  69026. effect.setFloat2('centerPosition', 0.5, 0.5);
  69027. };
  69028. };
  69029. // highlights enhancing
  69030. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  69031. var _this = this;
  69032. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  69033. [], // samplers
  69034. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  69035. this._highlightsPostProcess.onApply = function (effect) {
  69036. effect.setFloat('gain', _this._highlightsGain);
  69037. effect.setFloat('threshold', _this._highlightsThreshold);
  69038. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  69039. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69040. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69041. };
  69042. };
  69043. // colors shifting and distortion
  69044. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  69045. var _this = this;
  69046. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  69047. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  69048. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  69049. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69050. this._depthOfFieldPostProcess.onApply = function (effect) {
  69051. effect.setTexture("depthSampler", _this._depthTexture);
  69052. effect.setTexture("grainSampler", _this._grainTexture);
  69053. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  69054. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  69055. effect.setFloat('grain_amount', _this._grainAmount);
  69056. effect.setBool('blur_noise', _this._blurNoise);
  69057. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69058. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69059. effect.setFloat('distortion', _this._distortion);
  69060. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  69061. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  69062. effect.setFloat('aperture', _this._dofAperture);
  69063. effect.setFloat('darken', _this._dofDarken);
  69064. effect.setFloat('edge_blur', _this._edgeBlur);
  69065. effect.setBool('highlights', (_this._highlightsGain !== -1));
  69066. if (_this._scene.activeCamera) {
  69067. effect.setFloat('near', _this._scene.activeCamera.minZ);
  69068. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  69069. }
  69070. };
  69071. };
  69072. // creates a black and white random noise texture, 512x512
  69073. LensRenderingPipeline.prototype._createGrainTexture = function () {
  69074. var size = 512;
  69075. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69076. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  69077. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  69078. var context = this._grainTexture.getContext();
  69079. var rand = function (min, max) {
  69080. return Math.random() * (max - min) + min;
  69081. };
  69082. var value;
  69083. for (var x = 0; x < size; x++) {
  69084. for (var y = 0; y < size; y++) {
  69085. value = Math.floor(rand(0.42, 0.58) * 255);
  69086. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  69087. context.fillRect(x, y, 1, 1);
  69088. }
  69089. }
  69090. this._grainTexture.update(false);
  69091. };
  69092. return LensRenderingPipeline;
  69093. }(BABYLON.PostProcessRenderPipeline));
  69094. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  69095. })(BABYLON || (BABYLON = {}));
  69096. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  69097. "use strict";
  69098. var BABYLON;
  69099. (function (BABYLON) {
  69100. var StandardRenderingPipeline = /** @class */ (function (_super) {
  69101. __extends(StandardRenderingPipeline, _super);
  69102. /**
  69103. * @constructor
  69104. * @param {string} name - The rendering pipeline name
  69105. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69106. * @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)
  69107. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  69108. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69109. */
  69110. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  69111. if (originalPostProcess === void 0) { originalPostProcess = null; }
  69112. var _this = _super.call(this, scene.getEngine(), name) || this;
  69113. _this.downSampleX4PostProcess = null;
  69114. _this.brightPassPostProcess = null;
  69115. _this.blurHPostProcesses = [];
  69116. _this.blurVPostProcesses = [];
  69117. _this.textureAdderPostProcess = null;
  69118. _this.volumetricLightPostProcess = null;
  69119. _this.volumetricLightSmoothXPostProcess = null;
  69120. _this.volumetricLightSmoothYPostProcess = null;
  69121. _this.volumetricLightMergePostProces = null;
  69122. _this.volumetricLightFinalPostProcess = null;
  69123. _this.luminancePostProcess = null;
  69124. _this.luminanceDownSamplePostProcesses = [];
  69125. _this.hdrPostProcess = null;
  69126. _this.textureAdderFinalPostProcess = null;
  69127. _this.lensFlareFinalPostProcess = null;
  69128. _this.hdrFinalPostProcess = null;
  69129. _this.lensFlarePostProcess = null;
  69130. _this.lensFlareComposePostProcess = null;
  69131. _this.motionBlurPostProcess = null;
  69132. _this.depthOfFieldPostProcess = null;
  69133. // Values
  69134. _this.brightThreshold = 1.0;
  69135. _this.blurWidth = 512.0;
  69136. _this.horizontalBlur = false;
  69137. _this.exposure = 1.0;
  69138. _this.lensTexture = null;
  69139. _this.volumetricLightCoefficient = 0.2;
  69140. _this.volumetricLightPower = 4.0;
  69141. _this.volumetricLightBlurScale = 64.0;
  69142. _this.sourceLight = null;
  69143. _this.hdrMinimumLuminance = 1.0;
  69144. _this.hdrDecreaseRate = 0.5;
  69145. _this.hdrIncreaseRate = 0.5;
  69146. _this.lensColorTexture = null;
  69147. _this.lensFlareStrength = 20.0;
  69148. _this.lensFlareGhostDispersal = 1.4;
  69149. _this.lensFlareHaloWidth = 0.7;
  69150. _this.lensFlareDistortionStrength = 16.0;
  69151. _this.lensStarTexture = null;
  69152. _this.lensFlareDirtTexture = null;
  69153. _this.depthOfFieldDistance = 10.0;
  69154. _this.depthOfFieldBlurWidth = 64.0;
  69155. _this.motionStrength = 1.0;
  69156. // IAnimatable
  69157. _this.animations = [];
  69158. _this._currentDepthOfFieldSource = null;
  69159. _this._hdrCurrentLuminance = 1.0;
  69160. // Getters and setters
  69161. _this._bloomEnabled = true;
  69162. _this._depthOfFieldEnabled = false;
  69163. _this._vlsEnabled = false;
  69164. _this._lensFlareEnabled = false;
  69165. _this._hdrEnabled = false;
  69166. _this._motionBlurEnabled = false;
  69167. _this._motionBlurSamples = 64.0;
  69168. _this._volumetricLightStepsCount = 50.0;
  69169. _this._cameras = cameras || [];
  69170. // Initialize
  69171. _this._scene = scene;
  69172. _this._basePostProcess = originalPostProcess;
  69173. _this._ratio = ratio;
  69174. // Misc
  69175. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69176. // Finish
  69177. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69178. _this._buildPipeline();
  69179. return _this;
  69180. }
  69181. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  69182. get: function () {
  69183. return this._bloomEnabled;
  69184. },
  69185. set: function (enabled) {
  69186. if (this._bloomEnabled === enabled) {
  69187. return;
  69188. }
  69189. this._bloomEnabled = enabled;
  69190. this._buildPipeline();
  69191. },
  69192. enumerable: true,
  69193. configurable: true
  69194. });
  69195. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  69196. get: function () {
  69197. return this._depthOfFieldEnabled;
  69198. },
  69199. set: function (enabled) {
  69200. if (this._depthOfFieldEnabled === enabled) {
  69201. return;
  69202. }
  69203. this._depthOfFieldEnabled = enabled;
  69204. this._buildPipeline();
  69205. },
  69206. enumerable: true,
  69207. configurable: true
  69208. });
  69209. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  69210. get: function () {
  69211. return this._lensFlareEnabled;
  69212. },
  69213. set: function (enabled) {
  69214. if (this._lensFlareEnabled === enabled) {
  69215. return;
  69216. }
  69217. this._lensFlareEnabled = enabled;
  69218. this._buildPipeline();
  69219. },
  69220. enumerable: true,
  69221. configurable: true
  69222. });
  69223. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  69224. get: function () {
  69225. return this._hdrEnabled;
  69226. },
  69227. set: function (enabled) {
  69228. if (this._hdrEnabled === enabled) {
  69229. return;
  69230. }
  69231. this._hdrEnabled = enabled;
  69232. this._buildPipeline();
  69233. },
  69234. enumerable: true,
  69235. configurable: true
  69236. });
  69237. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  69238. get: function () {
  69239. return this._vlsEnabled;
  69240. },
  69241. set: function (enabled) {
  69242. if (this._vlsEnabled === enabled) {
  69243. return;
  69244. }
  69245. if (enabled) {
  69246. var geometry = this._scene.enableGeometryBufferRenderer();
  69247. if (!geometry) {
  69248. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  69249. return;
  69250. }
  69251. }
  69252. this._vlsEnabled = enabled;
  69253. this._buildPipeline();
  69254. },
  69255. enumerable: true,
  69256. configurable: true
  69257. });
  69258. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  69259. get: function () {
  69260. return this._motionBlurEnabled;
  69261. },
  69262. set: function (enabled) {
  69263. if (this._motionBlurEnabled === enabled) {
  69264. return;
  69265. }
  69266. this._motionBlurEnabled = enabled;
  69267. this._buildPipeline();
  69268. },
  69269. enumerable: true,
  69270. configurable: true
  69271. });
  69272. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  69273. get: function () {
  69274. return this._volumetricLightStepsCount;
  69275. },
  69276. set: function (count) {
  69277. if (this.volumetricLightPostProcess) {
  69278. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  69279. }
  69280. this._volumetricLightStepsCount = count;
  69281. },
  69282. enumerable: true,
  69283. configurable: true
  69284. });
  69285. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  69286. get: function () {
  69287. return this._motionBlurSamples;
  69288. },
  69289. set: function (samples) {
  69290. if (this.motionBlurPostProcess) {
  69291. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  69292. }
  69293. this._motionBlurSamples = samples;
  69294. },
  69295. enumerable: true,
  69296. configurable: true
  69297. });
  69298. StandardRenderingPipeline.prototype._buildPipeline = function () {
  69299. var _this = this;
  69300. var ratio = this._ratio;
  69301. var scene = this._scene;
  69302. this._disposePostProcesses();
  69303. this._reset();
  69304. // Create pass post-process
  69305. if (!this._basePostProcess) {
  69306. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  69307. this.originalPostProcess.onApply = function (effect) {
  69308. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  69309. };
  69310. }
  69311. else {
  69312. this.originalPostProcess = this._basePostProcess;
  69313. }
  69314. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  69315. this._currentDepthOfFieldSource = this.originalPostProcess;
  69316. if (this._vlsEnabled) {
  69317. // Create volumetric light
  69318. this._createVolumetricLightPostProcess(scene, ratio);
  69319. // Create volumetric light final post-process
  69320. 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);
  69321. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  69322. }
  69323. if (this._bloomEnabled) {
  69324. // Create down sample X4 post-process
  69325. this._createDownSampleX4PostProcess(scene, ratio / 2);
  69326. // Create bright pass post-process
  69327. this._createBrightPassPostProcess(scene, ratio / 2);
  69328. // Create gaussian blur post-processes (down sampling blurs)
  69329. this._createBlurPostProcesses(scene, ratio / 4, 1);
  69330. // Create texture adder post-process
  69331. this._createTextureAdderPostProcess(scene, ratio);
  69332. // Create depth-of-field source post-process
  69333. 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);
  69334. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  69335. }
  69336. if (this._lensFlareEnabled) {
  69337. // Create lens flare post-process
  69338. this._createLensFlarePostProcess(scene, ratio);
  69339. // Create depth-of-field source post-process post lens-flare and disable it now
  69340. 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);
  69341. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  69342. }
  69343. if (this._hdrEnabled) {
  69344. // Create luminance
  69345. this._createLuminancePostProcesses(scene, this._floatTextureType);
  69346. // Create HDR
  69347. this._createHdrPostProcess(scene, ratio);
  69348. // Create depth-of-field source post-process post hdr and disable it now
  69349. 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);
  69350. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  69351. }
  69352. if (this._depthOfFieldEnabled) {
  69353. // Create gaussian blur used by depth-of-field
  69354. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  69355. // Create depth-of-field post-process
  69356. this._createDepthOfFieldPostProcess(scene, ratio);
  69357. }
  69358. if (this._motionBlurEnabled) {
  69359. // Create motion blur post-process
  69360. this._createMotionBlurPostProcess(scene, ratio);
  69361. }
  69362. if (this._cameras !== null) {
  69363. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69364. }
  69365. };
  69366. // Down Sample X4 Post-Processs
  69367. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  69368. var _this = this;
  69369. var downSampleX4Offsets = new Array(32);
  69370. 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);
  69371. this.downSampleX4PostProcess.onApply = function (effect) {
  69372. var id = 0;
  69373. var width = _this.downSampleX4PostProcess.width;
  69374. var height = _this.downSampleX4PostProcess.height;
  69375. for (var i = -2; i < 2; i++) {
  69376. for (var j = -2; j < 2; j++) {
  69377. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  69378. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  69379. id += 2;
  69380. }
  69381. }
  69382. effect.setArray2("dsOffsets", downSampleX4Offsets);
  69383. };
  69384. // Add to pipeline
  69385. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  69386. };
  69387. // Brightpass Post-Process
  69388. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  69389. var _this = this;
  69390. var brightOffsets = new Array(8);
  69391. 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);
  69392. this.brightPassPostProcess.onApply = function (effect) {
  69393. var sU = (1.0 / _this.brightPassPostProcess.width);
  69394. var sV = (1.0 / _this.brightPassPostProcess.height);
  69395. brightOffsets[0] = -0.5 * sU;
  69396. brightOffsets[1] = 0.5 * sV;
  69397. brightOffsets[2] = 0.5 * sU;
  69398. brightOffsets[3] = 0.5 * sV;
  69399. brightOffsets[4] = -0.5 * sU;
  69400. brightOffsets[5] = -0.5 * sV;
  69401. brightOffsets[6] = 0.5 * sU;
  69402. brightOffsets[7] = -0.5 * sV;
  69403. effect.setArray2("dsOffsets", brightOffsets);
  69404. effect.setFloat("brightThreshold", _this.brightThreshold);
  69405. };
  69406. // Add to pipeline
  69407. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  69408. };
  69409. // Create blur H&V post-processes
  69410. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  69411. var _this = this;
  69412. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  69413. var engine = scene.getEngine();
  69414. 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);
  69415. 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);
  69416. blurX.onActivateObservable.add(function () {
  69417. var dw = blurX.width / engine.getRenderWidth();
  69418. blurX.kernel = _this[blurWidthKey] * dw;
  69419. });
  69420. blurY.onActivateObservable.add(function () {
  69421. var dw = blurY.height / engine.getRenderHeight();
  69422. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  69423. });
  69424. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  69425. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  69426. this.blurHPostProcesses.push(blurX);
  69427. this.blurVPostProcesses.push(blurY);
  69428. };
  69429. // Create texture adder post-process
  69430. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  69431. var _this = this;
  69432. 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);
  69433. this.textureAdderPostProcess.onApply = function (effect) {
  69434. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  69435. effect.setTexture("lensSampler", _this.lensTexture);
  69436. effect.setFloat("exposure", _this.exposure);
  69437. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  69438. };
  69439. // Add to pipeline
  69440. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  69441. };
  69442. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  69443. var _this = this;
  69444. var geometryRenderer = scene.enableGeometryBufferRenderer();
  69445. geometryRenderer.enablePosition = true;
  69446. var geometry = geometryRenderer.getGBuffer();
  69447. // Base post-process
  69448. 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));
  69449. var depthValues = BABYLON.Vector2.Zero();
  69450. this.volumetricLightPostProcess.onApply = function (effect) {
  69451. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  69452. var generator = _this.sourceLight.getShadowGenerator();
  69453. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  69454. effect.setTexture("positionSampler", geometry.textures[2]);
  69455. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  69456. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  69457. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  69458. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  69459. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  69460. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  69461. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  69462. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  69463. effect.setVector2("depthValues", depthValues);
  69464. }
  69465. };
  69466. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  69467. // Smooth
  69468. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  69469. // Merge
  69470. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  69471. this.volumetricLightMergePostProces.onApply = function (effect) {
  69472. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  69473. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  69474. };
  69475. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  69476. };
  69477. // Create luminance
  69478. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  69479. var _this = this;
  69480. // Create luminance
  69481. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  69482. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  69483. var offsets = [];
  69484. this.luminancePostProcess.onApply = function (effect) {
  69485. var sU = (1.0 / _this.luminancePostProcess.width);
  69486. var sV = (1.0 / _this.luminancePostProcess.height);
  69487. offsets[0] = -0.5 * sU;
  69488. offsets[1] = 0.5 * sV;
  69489. offsets[2] = 0.5 * sU;
  69490. offsets[3] = 0.5 * sV;
  69491. offsets[4] = -0.5 * sU;
  69492. offsets[5] = -0.5 * sV;
  69493. offsets[6] = 0.5 * sU;
  69494. offsets[7] = -0.5 * sV;
  69495. effect.setArray2("lumOffsets", offsets);
  69496. };
  69497. // Add to pipeline
  69498. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  69499. // Create down sample luminance
  69500. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  69501. var size = Math.pow(3, i);
  69502. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  69503. if (i === 0) {
  69504. defines += "#define FINAL_DOWN_SAMPLER";
  69505. }
  69506. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  69507. this.luminanceDownSamplePostProcesses.push(postProcess);
  69508. }
  69509. // Create callbacks and add effects
  69510. var lastLuminance = this.luminancePostProcess;
  69511. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  69512. var downSampleOffsets = new Array(18);
  69513. pp.onApply = function (effect) {
  69514. if (!lastLuminance) {
  69515. return;
  69516. }
  69517. var id = 0;
  69518. for (var x = -1; x < 2; x++) {
  69519. for (var y = -1; y < 2; y++) {
  69520. downSampleOffsets[id] = x / lastLuminance.width;
  69521. downSampleOffsets[id + 1] = y / lastLuminance.height;
  69522. id += 2;
  69523. }
  69524. }
  69525. effect.setArray2("dsOffsets", downSampleOffsets);
  69526. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  69527. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69528. lastLuminance = _this.luminancePostProcess;
  69529. }
  69530. else {
  69531. lastLuminance = pp;
  69532. }
  69533. };
  69534. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69535. pp.onAfterRender = function (effect) {
  69536. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  69537. 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);
  69538. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  69539. };
  69540. }
  69541. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  69542. });
  69543. };
  69544. // Create HDR post-process
  69545. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  69546. var _this = this;
  69547. 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);
  69548. var outputLiminance = 1;
  69549. var time = 0;
  69550. var lastTime = 0;
  69551. this.hdrPostProcess.onApply = function (effect) {
  69552. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69553. time += scene.getEngine().getDeltaTime();
  69554. if (outputLiminance < 0) {
  69555. outputLiminance = _this._hdrCurrentLuminance;
  69556. }
  69557. else {
  69558. var dt = (lastTime - time) / 1000.0;
  69559. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69560. outputLiminance += _this.hdrDecreaseRate * dt;
  69561. }
  69562. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69563. outputLiminance -= _this.hdrIncreaseRate * dt;
  69564. }
  69565. else {
  69566. outputLiminance = _this._hdrCurrentLuminance;
  69567. }
  69568. }
  69569. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69570. effect.setFloat("averageLuminance", outputLiminance);
  69571. lastTime = time;
  69572. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69573. };
  69574. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69575. };
  69576. // Create lens flare post-process
  69577. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69578. var _this = this;
  69579. 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);
  69580. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69581. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69582. 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);
  69583. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69584. var resolution = new BABYLON.Vector2(0, 0);
  69585. // Lens flare
  69586. this.lensFlarePostProcess.onApply = function (effect) {
  69587. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69588. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69589. effect.setFloat("strength", _this.lensFlareStrength);
  69590. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69591. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69592. // Shift
  69593. resolution.x = _this.lensFlarePostProcess.width;
  69594. resolution.y = _this.lensFlarePostProcess.height;
  69595. effect.setVector2("resolution", resolution);
  69596. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69597. };
  69598. // Compose
  69599. 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);
  69600. 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);
  69601. this.lensFlareComposePostProcess.onApply = function (effect) {
  69602. if (!_this._scene.activeCamera) {
  69603. return;
  69604. }
  69605. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69606. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69607. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69608. // Lens start rotation matrix
  69609. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69610. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69611. 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));
  69612. camRot *= 4.0;
  69613. 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);
  69614. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69615. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69616. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69617. };
  69618. };
  69619. // Create depth-of-field post-process
  69620. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69621. var _this = this;
  69622. 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);
  69623. this.depthOfFieldPostProcess.onApply = function (effect) {
  69624. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69625. effect.setTexture("depthSampler", _this._getDepthTexture());
  69626. effect.setFloat("distance", _this.depthOfFieldDistance);
  69627. };
  69628. // Add to pipeline
  69629. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69630. };
  69631. // Create motion blur post-process
  69632. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69633. var _this = this;
  69634. 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);
  69635. var motionScale = 0;
  69636. var prevViewProjection = BABYLON.Matrix.Identity();
  69637. var invViewProjection = BABYLON.Matrix.Identity();
  69638. var viewProjection = BABYLON.Matrix.Identity();
  69639. var screenSize = BABYLON.Vector2.Zero();
  69640. this.motionBlurPostProcess.onApply = function (effect) {
  69641. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69642. viewProjection.invertToRef(invViewProjection);
  69643. effect.setMatrix("inverseViewProjection", invViewProjection);
  69644. effect.setMatrix("prevViewProjection", prevViewProjection);
  69645. prevViewProjection = viewProjection;
  69646. screenSize.x = _this.motionBlurPostProcess.width;
  69647. screenSize.y = _this.motionBlurPostProcess.height;
  69648. effect.setVector2("screenSize", screenSize);
  69649. motionScale = scene.getEngine().getFps() / 60.0;
  69650. effect.setFloat("motionScale", motionScale);
  69651. effect.setFloat("motionStrength", _this.motionStrength);
  69652. effect.setTexture("depthSampler", _this._getDepthTexture());
  69653. };
  69654. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69655. };
  69656. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69657. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69658. var renderer = this._scene.enableGeometryBufferRenderer();
  69659. return renderer.getGBuffer().textures[0];
  69660. }
  69661. return this._scene.enableDepthRenderer().getDepthMap();
  69662. };
  69663. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69664. for (var i = 0; i < this._cameras.length; i++) {
  69665. var camera = this._cameras[i];
  69666. if (this.originalPostProcess) {
  69667. this.originalPostProcess.dispose(camera);
  69668. }
  69669. if (this.downSampleX4PostProcess) {
  69670. this.downSampleX4PostProcess.dispose(camera);
  69671. }
  69672. if (this.brightPassPostProcess) {
  69673. this.brightPassPostProcess.dispose(camera);
  69674. }
  69675. if (this.textureAdderPostProcess) {
  69676. this.textureAdderPostProcess.dispose(camera);
  69677. }
  69678. if (this.textureAdderFinalPostProcess) {
  69679. this.textureAdderFinalPostProcess.dispose(camera);
  69680. }
  69681. if (this.volumetricLightPostProcess) {
  69682. this.volumetricLightPostProcess.dispose(camera);
  69683. }
  69684. if (this.volumetricLightSmoothXPostProcess) {
  69685. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69686. }
  69687. if (this.volumetricLightSmoothYPostProcess) {
  69688. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69689. }
  69690. if (this.volumetricLightMergePostProces) {
  69691. this.volumetricLightMergePostProces.dispose(camera);
  69692. }
  69693. if (this.volumetricLightFinalPostProcess) {
  69694. this.volumetricLightFinalPostProcess.dispose(camera);
  69695. }
  69696. if (this.lensFlarePostProcess) {
  69697. this.lensFlarePostProcess.dispose(camera);
  69698. }
  69699. if (this.lensFlareComposePostProcess) {
  69700. this.lensFlareComposePostProcess.dispose(camera);
  69701. }
  69702. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69703. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69704. }
  69705. if (this.luminancePostProcess) {
  69706. this.luminancePostProcess.dispose(camera);
  69707. }
  69708. if (this.hdrPostProcess) {
  69709. this.hdrPostProcess.dispose(camera);
  69710. }
  69711. if (this.hdrFinalPostProcess) {
  69712. this.hdrFinalPostProcess.dispose(camera);
  69713. }
  69714. if (this.depthOfFieldPostProcess) {
  69715. this.depthOfFieldPostProcess.dispose(camera);
  69716. }
  69717. if (this.motionBlurPostProcess) {
  69718. this.motionBlurPostProcess.dispose(camera);
  69719. }
  69720. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69721. this.blurHPostProcesses[j].dispose(camera);
  69722. }
  69723. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69724. this.blurVPostProcesses[j].dispose(camera);
  69725. }
  69726. }
  69727. this.originalPostProcess = null;
  69728. this.downSampleX4PostProcess = null;
  69729. this.brightPassPostProcess = null;
  69730. this.textureAdderPostProcess = null;
  69731. this.textureAdderFinalPostProcess = null;
  69732. this.volumetricLightPostProcess = null;
  69733. this.volumetricLightSmoothXPostProcess = null;
  69734. this.volumetricLightSmoothYPostProcess = null;
  69735. this.volumetricLightMergePostProces = null;
  69736. this.volumetricLightFinalPostProcess = null;
  69737. this.lensFlarePostProcess = null;
  69738. this.lensFlareComposePostProcess = null;
  69739. this.luminancePostProcess = null;
  69740. this.hdrPostProcess = null;
  69741. this.hdrFinalPostProcess = null;
  69742. this.depthOfFieldPostProcess = null;
  69743. this.motionBlurPostProcess = null;
  69744. this.luminanceDownSamplePostProcesses = [];
  69745. this.blurHPostProcesses = [];
  69746. this.blurVPostProcesses = [];
  69747. };
  69748. // Dispose
  69749. StandardRenderingPipeline.prototype.dispose = function () {
  69750. this._disposePostProcesses();
  69751. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69752. _super.prototype.dispose.call(this);
  69753. };
  69754. // Serialize rendering pipeline
  69755. StandardRenderingPipeline.prototype.serialize = function () {
  69756. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69757. serializationObject.customType = "StandardRenderingPipeline";
  69758. return serializationObject;
  69759. };
  69760. /**
  69761. * Static members
  69762. */
  69763. // Parse serialized pipeline
  69764. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69765. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69766. };
  69767. // Luminance steps
  69768. StandardRenderingPipeline.LuminanceSteps = 6;
  69769. __decorate([
  69770. BABYLON.serialize()
  69771. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69772. __decorate([
  69773. BABYLON.serialize()
  69774. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69775. __decorate([
  69776. BABYLON.serialize()
  69777. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69778. __decorate([
  69779. BABYLON.serialize()
  69780. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69781. __decorate([
  69782. BABYLON.serializeAsTexture("lensTexture")
  69783. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69784. __decorate([
  69785. BABYLON.serialize()
  69786. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69787. __decorate([
  69788. BABYLON.serialize()
  69789. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69790. __decorate([
  69791. BABYLON.serialize()
  69792. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69793. __decorate([
  69794. BABYLON.serialize()
  69795. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69796. __decorate([
  69797. BABYLON.serialize()
  69798. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69799. __decorate([
  69800. BABYLON.serialize()
  69801. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69802. __decorate([
  69803. BABYLON.serializeAsTexture("lensColorTexture")
  69804. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69805. __decorate([
  69806. BABYLON.serialize()
  69807. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69808. __decorate([
  69809. BABYLON.serialize()
  69810. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69811. __decorate([
  69812. BABYLON.serialize()
  69813. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69814. __decorate([
  69815. BABYLON.serialize()
  69816. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69817. __decorate([
  69818. BABYLON.serializeAsTexture("lensStarTexture")
  69819. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69820. __decorate([
  69821. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69822. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69823. __decorate([
  69824. BABYLON.serialize()
  69825. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69826. __decorate([
  69827. BABYLON.serialize()
  69828. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69829. __decorate([
  69830. BABYLON.serialize()
  69831. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69832. __decorate([
  69833. BABYLON.serialize()
  69834. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69835. __decorate([
  69836. BABYLON.serialize()
  69837. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69838. __decorate([
  69839. BABYLON.serialize()
  69840. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69841. __decorate([
  69842. BABYLON.serialize()
  69843. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69844. __decorate([
  69845. BABYLON.serialize()
  69846. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69847. __decorate([
  69848. BABYLON.serialize()
  69849. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69850. __decorate([
  69851. BABYLON.serialize()
  69852. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69853. __decorate([
  69854. BABYLON.serialize()
  69855. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69856. __decorate([
  69857. BABYLON.serialize()
  69858. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69859. return StandardRenderingPipeline;
  69860. }(BABYLON.PostProcessRenderPipeline));
  69861. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69862. })(BABYLON || (BABYLON = {}));
  69863. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69864. "use strict";
  69865. var BABYLON;
  69866. (function (BABYLON) {
  69867. var FxaaPostProcess = /** @class */ (function (_super) {
  69868. __extends(FxaaPostProcess, _super);
  69869. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69870. if (camera === void 0) { camera = null; }
  69871. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69872. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69873. _this.onApplyObservable.add(function (effect) {
  69874. var texelSize = _this.texelSize;
  69875. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69876. });
  69877. return _this;
  69878. }
  69879. return FxaaPostProcess;
  69880. }(BABYLON.PostProcess));
  69881. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69882. })(BABYLON || (BABYLON = {}));
  69883. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69884. "use strict";
  69885. var BABYLON;
  69886. (function (BABYLON) {
  69887. /**
  69888. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69889. */
  69890. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69891. __extends(ChromaticAberrationPostProcess, _super);
  69892. /**
  69893. * Creates a new instance of @see ChromaticAberrationPostProcess
  69894. * @param name The name of the effect.
  69895. * @param screenWidth The width of the screen to apply the effect on.
  69896. * @param screenHeight The height of the screen to apply the effect on.
  69897. * @param options The required width/height ratio to downsize to before computing the render pass.
  69898. * @param camera The camera to apply the render pass to.
  69899. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69900. * @param engine The engine which the post process will be applied. (default: current engine)
  69901. * @param reusable If the post process can be reused on the same frame. (default: false)
  69902. * @param textureType Type of textures used when performing the post process. (default: 0)
  69903. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69904. */
  69905. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69906. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69907. if (blockCompilation === void 0) { blockCompilation = false; }
  69908. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69909. /**
  69910. * The amount of seperation of rgb channels (default: 30)
  69911. */
  69912. _this.aberrationAmount = 30;
  69913. /**
  69914. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69915. */
  69916. _this.radialIntensity = 0;
  69917. /**
  69918. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  69919. */
  69920. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69921. /**
  69922. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  69923. */
  69924. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69925. _this.onApplyObservable.add(function (effect) {
  69926. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69927. effect.setFloat('screen_width', screenWidth);
  69928. effect.setFloat('screen_height', screenHeight);
  69929. effect.setFloat('radialIntensity', _this.radialIntensity);
  69930. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69931. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69932. });
  69933. return _this;
  69934. }
  69935. return ChromaticAberrationPostProcess;
  69936. }(BABYLON.PostProcess));
  69937. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69938. })(BABYLON || (BABYLON = {}));
  69939. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69940. "use strict";
  69941. var BABYLON;
  69942. (function (BABYLON) {
  69943. /**
  69944. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69945. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69946. */
  69947. var SharpenPostProcess = /** @class */ (function (_super) {
  69948. __extends(SharpenPostProcess, _super);
  69949. /**
  69950. * Creates a new instance of @see ConvolutionPostProcess
  69951. * @param name The name of the effect.
  69952. * @param options The required width/height ratio to downsize to before computing the render pass.
  69953. * @param camera The camera to apply the render pass to.
  69954. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69955. * @param engine The engine which the post process will be applied. (default: current engine)
  69956. * @param reusable If the post process can be reused on the same frame. (default: false)
  69957. * @param textureType Type of textures used when performing the post process. (default: 0)
  69958. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69959. */
  69960. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69961. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69962. if (blockCompilation === void 0) { blockCompilation = false; }
  69963. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69964. /**
  69965. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69966. */
  69967. _this.colorAmount = 1.0;
  69968. /**
  69969. * How much sharpness should be applied (default: 0.3)
  69970. */
  69971. _this.edgeAmount = 0.3;
  69972. _this.onApply = function (effect) {
  69973. effect.setFloat2("screenSize", _this.width, _this.height);
  69974. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69975. };
  69976. return _this;
  69977. }
  69978. return SharpenPostProcess;
  69979. }(BABYLON.PostProcess));
  69980. BABYLON.SharpenPostProcess = SharpenPostProcess;
  69981. })(BABYLON || (BABYLON = {}));
  69982. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  69983. "use strict";
  69984. var BABYLON;
  69985. (function (BABYLON) {
  69986. /**
  69987. * The Blur Post Process which blurs an image based on a kernel and direction.
  69988. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69989. */
  69990. var BlurPostProcess = /** @class */ (function (_super) {
  69991. __extends(BlurPostProcess, _super);
  69992. /**
  69993. * Creates a new instance of @see BlurPostProcess
  69994. * @param name The name of the effect.
  69995. * @param direction The direction in which to blur the image.
  69996. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  69997. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69998. * @param camera The camera to apply the render pass to.
  69999. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70000. * @param engine The engine which the post process will be applied. (default: current engine)
  70001. * @param reusable If the post process can be reused on the same frame. (default: false)
  70002. * @param textureType Type of textures used when performing the post process. (default: 0)
  70003. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70004. */
  70005. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  70006. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70007. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70008. if (defines === void 0) { defines = ""; }
  70009. if (blockCompilation === void 0) { blockCompilation = false; }
  70010. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  70011. _this.direction = direction;
  70012. _this.blockCompilation = blockCompilation;
  70013. _this._packedFloat = false;
  70014. _this._staticDefines = "";
  70015. _this._staticDefines = defines;
  70016. _this.onApplyObservable.add(function (effect) {
  70017. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  70018. });
  70019. _this.kernel = kernel;
  70020. return _this;
  70021. }
  70022. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  70023. /**
  70024. * Gets the length in pixels of the blur sample region
  70025. */
  70026. get: function () {
  70027. return this._idealKernel;
  70028. },
  70029. /**
  70030. * Sets the length in pixels of the blur sample region
  70031. */
  70032. set: function (v) {
  70033. if (this._idealKernel === v) {
  70034. return;
  70035. }
  70036. v = Math.max(v, 1);
  70037. this._idealKernel = v;
  70038. this._kernel = this._nearestBestKernel(v);
  70039. if (!this.blockCompilation) {
  70040. this._updateParameters();
  70041. }
  70042. },
  70043. enumerable: true,
  70044. configurable: true
  70045. });
  70046. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  70047. /**
  70048. * Gets wether or not the blur is unpacking/repacking floats
  70049. */
  70050. get: function () {
  70051. return this._packedFloat;
  70052. },
  70053. /**
  70054. * Sets wether or not the blur needs to unpack/repack floats
  70055. */
  70056. set: function (v) {
  70057. if (this._packedFloat === v) {
  70058. return;
  70059. }
  70060. this._packedFloat = v;
  70061. if (!this.blockCompilation) {
  70062. this._updateParameters();
  70063. }
  70064. },
  70065. enumerable: true,
  70066. configurable: true
  70067. });
  70068. /**
  70069. * Updates the effect with the current post process compile time values and recompiles the shader.
  70070. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70071. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70072. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70073. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  70074. * @param onCompiled Called when the shader has been compiled.
  70075. * @param onError Called if there is an error when compiling a shader.
  70076. */
  70077. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70078. if (defines === void 0) { defines = null; }
  70079. if (uniforms === void 0) { uniforms = null; }
  70080. if (samplers === void 0) { samplers = null; }
  70081. this._updateParameters(onCompiled, onError);
  70082. };
  70083. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  70084. // Generate sampling offsets and weights
  70085. var N = this._kernel;
  70086. var centerIndex = (N - 1) / 2;
  70087. // Generate Gaussian sampling weights over kernel
  70088. var offsets = [];
  70089. var weights = [];
  70090. var totalWeight = 0;
  70091. for (var i = 0; i < N; i++) {
  70092. var u = i / (N - 1);
  70093. var w = this._gaussianWeight(u * 2.0 - 1);
  70094. offsets[i] = (i - centerIndex);
  70095. weights[i] = w;
  70096. totalWeight += w;
  70097. }
  70098. // Normalize weights
  70099. for (var i = 0; i < weights.length; i++) {
  70100. weights[i] /= totalWeight;
  70101. }
  70102. // Optimize: combine samples to take advantage of hardware linear sampling
  70103. // Walk from left to center, combining pairs (symmetrically)
  70104. var linearSamplingWeights = [];
  70105. var linearSamplingOffsets = [];
  70106. var linearSamplingMap = [];
  70107. for (var i = 0; i <= centerIndex; i += 2) {
  70108. var j = Math.min(i + 1, Math.floor(centerIndex));
  70109. var singleCenterSample = i === j;
  70110. if (singleCenterSample) {
  70111. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70112. }
  70113. else {
  70114. var sharedCell = j === centerIndex;
  70115. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  70116. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  70117. if (offsetLinear === 0) {
  70118. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70119. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  70120. }
  70121. else {
  70122. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  70123. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  70124. }
  70125. }
  70126. }
  70127. for (var i = 0; i < linearSamplingMap.length; i++) {
  70128. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  70129. linearSamplingWeights[i] = linearSamplingMap[i].w;
  70130. }
  70131. // Replace with optimized
  70132. offsets = linearSamplingOffsets;
  70133. weights = linearSamplingWeights;
  70134. // Generate shaders
  70135. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  70136. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  70137. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  70138. var defines = "";
  70139. defines += this._staticDefines;
  70140. for (var i = 0; i < varyingCount; i++) {
  70141. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  70142. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  70143. }
  70144. var depCount = 0;
  70145. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  70146. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  70147. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  70148. depCount++;
  70149. }
  70150. if (this.packedFloat) {
  70151. defines += "#define PACKEDFLOAT 1";
  70152. }
  70153. _super.prototype.updateEffect.call(this, defines, null, null, {
  70154. varyingCount: varyingCount,
  70155. depCount: depCount
  70156. }, onCompiled, onError);
  70157. };
  70158. /**
  70159. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70160. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70161. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70162. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70163. * The gaps between physical kernels are compensated for in the weighting of the samples
  70164. * @param idealKernel Ideal blur kernel.
  70165. * @return Nearest best kernel.
  70166. */
  70167. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70168. var v = Math.round(idealKernel);
  70169. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70170. var k = _a[_i];
  70171. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70172. return Math.max(k, 3);
  70173. }
  70174. }
  70175. return Math.max(v, 3);
  70176. };
  70177. /**
  70178. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70179. * @param x The point on the Gaussian distribution to sample.
  70180. * @return the value of the Gaussian function at x.
  70181. */
  70182. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70183. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70184. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70185. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70186. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70187. // truncated at around 1.3% of peak strength.
  70188. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70189. var sigma = (1 / 3);
  70190. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70191. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70192. var weight = (1.0 / denominator) * Math.exp(exponent);
  70193. return weight;
  70194. };
  70195. /**
  70196. * Generates a string that can be used as a floating point number in GLSL.
  70197. * @param x Value to print.
  70198. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70199. * @return GLSL float string.
  70200. */
  70201. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70202. if (decimalFigures === void 0) { decimalFigures = 8; }
  70203. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70204. };
  70205. return BlurPostProcess;
  70206. }(BABYLON.PostProcess));
  70207. BABYLON.BlurPostProcess = BlurPostProcess;
  70208. })(BABYLON || (BABYLON = {}));
  70209. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70210. "use strict";
  70211. var BABYLON;
  70212. (function (BABYLON) {
  70213. /**
  70214. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  70215. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  70216. * based on samples that have a large difference in distance than the center pixel.
  70217. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70218. */
  70219. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  70220. __extends(DepthOfFieldBlurPostProcess, _super);
  70221. /**
  70222. * Creates a new instance of @see CircleOfConfusionPostProcess
  70223. * @param name The name of the effect.
  70224. * @param scene The scene the effect belongs to.
  70225. * @param direction The direction the blur should be applied.
  70226. * @param kernel The size of the kernel used to blur.
  70227. * @param options The required width/height ratio to downsize to before computing the render pass.
  70228. * @param camera The camera to apply the render pass to.
  70229. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  70230. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  70231. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70232. * @param engine The engine which the post process will be applied. (default: current engine)
  70233. * @param reusable If the post process can be reused on the same frame. (default: false)
  70234. * @param textureType Type of textures used when performing the post process. (default: 0)
  70235. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70236. */
  70237. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  70238. if (imageToBlur === void 0) { imageToBlur = null; }
  70239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70240. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70241. if (blockCompilation === void 0) { blockCompilation = false; }
  70242. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  70243. _this.direction = direction;
  70244. _this.onApplyObservable.add(function (effect) {
  70245. if (imageToBlur != null) {
  70246. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  70247. }
  70248. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70249. if (scene.activeCamera) {
  70250. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70251. }
  70252. });
  70253. return _this;
  70254. }
  70255. return DepthOfFieldBlurPostProcess;
  70256. }(BABYLON.BlurPostProcess));
  70257. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  70258. })(BABYLON || (BABYLON = {}));
  70259. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  70260. "use strict";
  70261. var BABYLON;
  70262. (function (BABYLON) {
  70263. /**
  70264. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  70265. */
  70266. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  70267. __extends(DepthOfFieldMergePostProcess, _super);
  70268. /**
  70269. * Creates a new instance of @see CircleOfConfusionPostProcess
  70270. * @param name The name of the effect.
  70271. * @param original The non-blurred image to be modified
  70272. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  70273. * @param blurSteps Incrimental bluring post processes.
  70274. * @param options The required width/height ratio to downsize to before computing the render pass.
  70275. * @param camera The camera to apply the render pass to.
  70276. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70277. * @param engine The engine which the post process will be applied. (default: current engine)
  70278. * @param reusable If the post process can be reused on the same frame. (default: false)
  70279. * @param textureType Type of textures used when performing the post process. (default: 0)
  70280. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70281. */
  70282. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70283. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70284. if (blockCompilation === void 0) { blockCompilation = false; }
  70285. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70286. _this.blurSteps = blurSteps;
  70287. _this.onApplyObservable.add(function (effect) {
  70288. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70289. effect.setTextureFromPostProcess("textureSampler", original);
  70290. blurSteps.forEach(function (step, index) {
  70291. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  70292. });
  70293. });
  70294. if (!blockCompilation) {
  70295. _this.updateEffect();
  70296. }
  70297. return _this;
  70298. }
  70299. /**
  70300. * Updates the effect with the current post process compile time values and recompiles the shader.
  70301. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70302. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70303. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70304. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  70305. * @param onCompiled Called when the shader has been compiled.
  70306. * @param onError Called if there is an error when compiling a shader.
  70307. */
  70308. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70309. if (defines === void 0) { defines = null; }
  70310. if (uniforms === void 0) { uniforms = null; }
  70311. if (samplers === void 0) { samplers = null; }
  70312. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  70313. };
  70314. return DepthOfFieldMergePostProcess;
  70315. }(BABYLON.PostProcess));
  70316. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  70317. })(BABYLON || (BABYLON = {}));
  70318. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  70319. "use strict";
  70320. var BABYLON;
  70321. (function (BABYLON) {
  70322. /**
  70323. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  70324. */
  70325. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  70326. __extends(CircleOfConfusionPostProcess, _super);
  70327. /**
  70328. * Creates a new instance of @see CircleOfConfusionPostProcess
  70329. * @param name The name of the effect.
  70330. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  70331. * @param options The required width/height ratio to downsize to before computing the render pass.
  70332. * @param camera The camera to apply the render pass to.
  70333. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70334. * @param engine The engine which the post process will be applied. (default: current engine)
  70335. * @param reusable If the post process can be reused on the same frame. (default: false)
  70336. * @param textureType Type of textures used when performing the post process. (default: 0)
  70337. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70338. */
  70339. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70340. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70341. if (blockCompilation === void 0) { blockCompilation = false; }
  70342. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70343. /**
  70344. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  70345. */
  70346. _this.lensSize = 50;
  70347. /**
  70348. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70349. */
  70350. _this.fStop = 1.4;
  70351. /**
  70352. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70353. */
  70354. _this.focusDistance = 2000;
  70355. /**
  70356. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  70357. */
  70358. _this.focalLength = 50;
  70359. _this._depthTexture = null;
  70360. _this._depthTexture = depthTexture;
  70361. _this.onApplyObservable.add(function (effect) {
  70362. if (!_this._depthTexture) {
  70363. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  70364. return;
  70365. }
  70366. effect.setTexture("depthSampler", _this._depthTexture);
  70367. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  70368. var aperture = _this.lensSize / _this.fStop;
  70369. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  70370. effect.setFloat('focusDistance', _this.focusDistance);
  70371. effect.setFloat('cocPrecalculation', cocPrecalculation);
  70372. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  70373. });
  70374. return _this;
  70375. }
  70376. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  70377. /**
  70378. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  70379. */
  70380. set: function (value) {
  70381. this._depthTexture = value;
  70382. },
  70383. enumerable: true,
  70384. configurable: true
  70385. });
  70386. return CircleOfConfusionPostProcess;
  70387. }(BABYLON.PostProcess));
  70388. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  70389. })(BABYLON || (BABYLON = {}));
  70390. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  70391. "use strict";
  70392. var BABYLON;
  70393. (function (BABYLON) {
  70394. /**
  70395. * Specifies the level of max blur that should be applied when using the depth of field effect
  70396. */
  70397. var DepthOfFieldEffectBlurLevel;
  70398. (function (DepthOfFieldEffectBlurLevel) {
  70399. /**
  70400. * Subtle blur
  70401. */
  70402. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  70403. /**
  70404. * Medium blur
  70405. */
  70406. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  70407. /**
  70408. * Large blur
  70409. */
  70410. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  70411. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  70412. ;
  70413. /**
  70414. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  70415. */
  70416. var DepthOfFieldEffect = /** @class */ (function (_super) {
  70417. __extends(DepthOfFieldEffect, _super);
  70418. /**
  70419. * Creates a new instance of @see DepthOfFieldEffect
  70420. * @param scene The scene the effect belongs to.
  70421. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  70422. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70423. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  70424. */
  70425. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  70426. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  70427. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70428. if (blockCompilation === void 0) { blockCompilation = false; }
  70429. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  70430. return _this._effects;
  70431. }, true) || this;
  70432. _this._effects = [];
  70433. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  70434. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70435. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  70436. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  70437. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70438. _this._depthOfFieldBlurY = [];
  70439. _this._depthOfFieldBlurX = [];
  70440. var blurCount = 1;
  70441. var kernelSize = 15;
  70442. switch (blurLevel) {
  70443. case DepthOfFieldEffectBlurLevel.High: {
  70444. blurCount = 3;
  70445. kernelSize = 51;
  70446. break;
  70447. }
  70448. case DepthOfFieldEffectBlurLevel.Medium: {
  70449. blurCount = 2;
  70450. kernelSize = 31;
  70451. break;
  70452. }
  70453. default: {
  70454. kernelSize = 15;
  70455. blurCount = 1;
  70456. break;
  70457. }
  70458. }
  70459. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  70460. for (var i = 0; i < blurCount; i++) {
  70461. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70462. blurY.autoClear = false;
  70463. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70464. blurX.autoClear = false;
  70465. _this._depthOfFieldBlurY.push(blurY);
  70466. _this._depthOfFieldBlurX.push(blurX);
  70467. }
  70468. // Merge blurred images with original image based on circleOfConfusion
  70469. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70470. _this._depthOfFieldMerge.autoClear = false;
  70471. // Set all post processes on the effect.
  70472. _this._effects = [_this._circleOfConfusion];
  70473. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  70474. _this._effects.push(_this._depthOfFieldBlurY[i]);
  70475. _this._effects.push(_this._depthOfFieldBlurX[i]);
  70476. }
  70477. _this._effects.push(_this._depthOfFieldMerge);
  70478. return _this;
  70479. }
  70480. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  70481. get: function () {
  70482. return this._circleOfConfusion.focalLength;
  70483. },
  70484. /**
  70485. * The focal the length of the camera used in the effect
  70486. */
  70487. set: function (value) {
  70488. this._circleOfConfusion.focalLength = value;
  70489. },
  70490. enumerable: true,
  70491. configurable: true
  70492. });
  70493. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  70494. get: function () {
  70495. return this._circleOfConfusion.fStop;
  70496. },
  70497. /**
  70498. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70499. */
  70500. set: function (value) {
  70501. this._circleOfConfusion.fStop = value;
  70502. },
  70503. enumerable: true,
  70504. configurable: true
  70505. });
  70506. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  70507. get: function () {
  70508. return this._circleOfConfusion.focusDistance;
  70509. },
  70510. /**
  70511. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70512. */
  70513. set: function (value) {
  70514. this._circleOfConfusion.focusDistance = value;
  70515. },
  70516. enumerable: true,
  70517. configurable: true
  70518. });
  70519. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  70520. get: function () {
  70521. return this._circleOfConfusion.lensSize;
  70522. },
  70523. /**
  70524. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  70525. */
  70526. set: function (value) {
  70527. this._circleOfConfusion.lensSize = value;
  70528. },
  70529. enumerable: true,
  70530. configurable: true
  70531. });
  70532. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  70533. /**
  70534. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  70535. */
  70536. set: function (value) {
  70537. this._circleOfConfusion.depthTexture = value;
  70538. },
  70539. enumerable: true,
  70540. configurable: true
  70541. });
  70542. /**
  70543. * Disposes each of the internal effects for a given camera.
  70544. * @param camera The camera to dispose the effect on.
  70545. */
  70546. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  70547. this._circleOfConfusion.dispose(camera);
  70548. this._depthOfFieldBlurX.forEach(function (element) {
  70549. element.dispose(camera);
  70550. });
  70551. this._depthOfFieldBlurY.forEach(function (element) {
  70552. element.dispose(camera);
  70553. });
  70554. this._depthOfFieldMerge.dispose(camera);
  70555. };
  70556. /**
  70557. * Internal
  70558. */
  70559. DepthOfFieldEffect.prototype._updateEffects = function () {
  70560. for (var effect in this._effects) {
  70561. this._effects[effect].updateEffect();
  70562. }
  70563. };
  70564. /**
  70565. * Internal
  70566. * @returns if all the contained post processes are ready.
  70567. */
  70568. DepthOfFieldEffect.prototype._isReady = function () {
  70569. for (var effect in this._effects) {
  70570. if (!this._effects[effect].isReady()) {
  70571. return false;
  70572. }
  70573. }
  70574. return true;
  70575. };
  70576. return DepthOfFieldEffect;
  70577. }(BABYLON.PostProcessRenderEffect));
  70578. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70579. })(BABYLON || (BABYLON = {}));
  70580. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70581. "use strict";
  70582. var BABYLON;
  70583. (function (BABYLON) {
  70584. /**
  70585. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70586. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70587. */
  70588. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70589. __extends(DefaultRenderingPipeline, _super);
  70590. /**
  70591. * @constructor
  70592. * @param {string} name - The rendering pipeline name
  70593. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70594. * @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)
  70595. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70596. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70597. */
  70598. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70599. if (automaticBuild === void 0) { automaticBuild = true; }
  70600. var _this = _super.call(this, scene.getEngine(), name) || this;
  70601. _this._originalCameras = [];
  70602. /**
  70603. * ID of the sharpen post process,
  70604. */
  70605. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70606. /**
  70607. * ID of the pass post process used for bloom,
  70608. */
  70609. _this.PassPostProcessId = "PassPostProcessEffect";
  70610. /**
  70611. * ID of the highlight post process used for bloom,
  70612. */
  70613. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  70614. /**
  70615. * ID of the blurX post process used for bloom,
  70616. */
  70617. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  70618. /**
  70619. * ID of the blurY post process used for bloom,
  70620. */
  70621. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  70622. /**
  70623. * ID of the copy back post process used for bloom,
  70624. */
  70625. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  70626. /**
  70627. * ID of the image processing post process;
  70628. */
  70629. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70630. /**
  70631. * ID of the Fast Approximate Anti-Aliasing post process;
  70632. */
  70633. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70634. /**
  70635. * ID of the final merge post process;
  70636. */
  70637. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  70638. /**
  70639. * ID of the chromatic aberration post process,
  70640. */
  70641. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70642. /**
  70643. * Animations which can be used to tweak settings over a period of time
  70644. */
  70645. _this.animations = [];
  70646. // Values
  70647. _this._sharpenEnabled = false;
  70648. _this._bloomEnabled = false;
  70649. _this._depthOfFieldEnabled = false;
  70650. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70651. _this._fxaaEnabled = false;
  70652. _this._msaaEnabled = false;
  70653. _this._imageProcessingEnabled = true;
  70654. _this._bloomScale = 0.6;
  70655. _this._chromaticAberrationEnabled = false;
  70656. _this._buildAllowed = true;
  70657. /**
  70658. * Specifies the size of the bloom blur kernel, relative to the final output size
  70659. */
  70660. _this.bloomKernel = 64;
  70661. /**
  70662. * Specifies the weight of the bloom in the final rendering
  70663. */
  70664. _this._bloomWeight = 0.15;
  70665. _this._prevPostProcess = null;
  70666. _this._prevPrevPostProcess = null;
  70667. _this._cameras = cameras || [];
  70668. _this._originalCameras = _this._cameras.slice();
  70669. _this._buildAllowed = automaticBuild;
  70670. // Initialize
  70671. _this._scene = scene;
  70672. var caps = _this._scene.getEngine().getCaps();
  70673. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70674. // Misc
  70675. if (_this._hdr) {
  70676. if (caps.textureHalfFloatRender) {
  70677. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70678. }
  70679. else if (caps.textureFloatRender) {
  70680. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70681. }
  70682. }
  70683. else {
  70684. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70685. }
  70686. // Attach
  70687. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70688. var engine = _this._scene.getEngine();
  70689. // Create post processes before hand so they can be modified before enabled.
  70690. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70691. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70692. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70693. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70694. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70695. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70696. _this._buildPipeline();
  70697. return _this;
  70698. }
  70699. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70700. get: function () {
  70701. return this._sharpenEnabled;
  70702. },
  70703. /**
  70704. * Enable or disable the sharpen process from the pipeline
  70705. */
  70706. set: function (enabled) {
  70707. if (this._sharpenEnabled === enabled) {
  70708. return;
  70709. }
  70710. this._sharpenEnabled = enabled;
  70711. this._buildPipeline();
  70712. },
  70713. enumerable: true,
  70714. configurable: true
  70715. });
  70716. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  70717. get: function () {
  70718. return this._bloomWeight;
  70719. },
  70720. /**
  70721. * The strength of the bloom.
  70722. */
  70723. set: function (value) {
  70724. if (this._bloomWeight === value) {
  70725. return;
  70726. }
  70727. this._bloomWeight = value;
  70728. if (this._hdr && this.copyBack) {
  70729. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  70730. }
  70731. },
  70732. enumerable: true,
  70733. configurable: true
  70734. });
  70735. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  70736. get: function () {
  70737. return this._bloomScale;
  70738. },
  70739. /**
  70740. * The scale of the bloom, lower value will provide better performance.
  70741. */
  70742. set: function (value) {
  70743. if (this._bloomScale === value) {
  70744. return;
  70745. }
  70746. this._bloomScale = value;
  70747. this._buildPipeline();
  70748. },
  70749. enumerable: true,
  70750. configurable: true
  70751. });
  70752. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  70753. get: function () {
  70754. return this._bloomEnabled;
  70755. },
  70756. /**
  70757. * Enable or disable the bloom from the pipeline
  70758. */
  70759. set: function (enabled) {
  70760. if (this._bloomEnabled === enabled) {
  70761. return;
  70762. }
  70763. this._bloomEnabled = enabled;
  70764. this._buildPipeline();
  70765. },
  70766. enumerable: true,
  70767. configurable: true
  70768. });
  70769. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  70770. /**
  70771. * If the depth of field is enabled.
  70772. */
  70773. get: function () {
  70774. return this._depthOfFieldEnabled;
  70775. },
  70776. set: function (enabled) {
  70777. if (this._depthOfFieldEnabled === enabled) {
  70778. return;
  70779. }
  70780. this._depthOfFieldEnabled = enabled;
  70781. this._buildPipeline();
  70782. },
  70783. enumerable: true,
  70784. configurable: true
  70785. });
  70786. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  70787. /**
  70788. * Blur level of the depth of field effect. (Higher blur will effect performance)
  70789. */
  70790. get: function () {
  70791. return this._depthOfFieldBlurLevel;
  70792. },
  70793. set: function (value) {
  70794. if (this._depthOfFieldBlurLevel === value) {
  70795. return;
  70796. }
  70797. this._depthOfFieldBlurLevel = value;
  70798. // recreate dof and dispose old as this setting is not dynamic
  70799. var oldDof = this.depthOfField;
  70800. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  70801. this.depthOfField.focalLength = oldDof.focalLength;
  70802. this.depthOfField.focusDistance = oldDof.focusDistance;
  70803. this.depthOfField.fStop = oldDof.fStop;
  70804. this.depthOfField.lensSize = oldDof.lensSize;
  70805. for (var i = 0; i < this._cameras.length; i++) {
  70806. oldDof.disposeEffects(this._cameras[i]);
  70807. }
  70808. this._buildPipeline();
  70809. },
  70810. enumerable: true,
  70811. configurable: true
  70812. });
  70813. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  70814. get: function () {
  70815. return this._fxaaEnabled;
  70816. },
  70817. /**
  70818. * If the anti aliasing is enabled.
  70819. */
  70820. set: function (enabled) {
  70821. if (this._fxaaEnabled === enabled) {
  70822. return;
  70823. }
  70824. this._fxaaEnabled = enabled;
  70825. this._buildPipeline();
  70826. },
  70827. enumerable: true,
  70828. configurable: true
  70829. });
  70830. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  70831. get: function () {
  70832. return this._msaaEnabled;
  70833. },
  70834. /**
  70835. * If the multisample anti-aliasing is enabled.
  70836. */
  70837. set: function (enabled) {
  70838. if (this._msaaEnabled === enabled) {
  70839. return;
  70840. }
  70841. this._msaaEnabled = enabled;
  70842. this._buildPipeline();
  70843. },
  70844. enumerable: true,
  70845. configurable: true
  70846. });
  70847. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  70848. get: function () {
  70849. return this._imageProcessingEnabled;
  70850. },
  70851. /**
  70852. * If image processing is enabled.
  70853. */
  70854. set: function (enabled) {
  70855. if (this._imageProcessingEnabled === enabled) {
  70856. return;
  70857. }
  70858. this._imageProcessingEnabled = enabled;
  70859. this._buildPipeline();
  70860. },
  70861. enumerable: true,
  70862. configurable: true
  70863. });
  70864. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  70865. get: function () {
  70866. return this._chromaticAberrationEnabled;
  70867. },
  70868. /**
  70869. * Enable or disable the chromaticAberration process from the pipeline
  70870. */
  70871. set: function (enabled) {
  70872. if (this._chromaticAberrationEnabled === enabled) {
  70873. return;
  70874. }
  70875. this._chromaticAberrationEnabled = enabled;
  70876. this._buildPipeline();
  70877. },
  70878. enumerable: true,
  70879. configurable: true
  70880. });
  70881. /**
  70882. * Force the compilation of the entire pipeline.
  70883. */
  70884. DefaultRenderingPipeline.prototype.prepare = function () {
  70885. var previousState = this._buildAllowed;
  70886. this._buildAllowed = true;
  70887. this._buildPipeline();
  70888. this._buildAllowed = previousState;
  70889. };
  70890. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  70891. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  70892. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  70893. postProcess.autoClear = false;
  70894. }
  70895. else {
  70896. postProcess.autoClear = true;
  70897. }
  70898. if (!skipTextureSharing) {
  70899. if (this._prevPrevPostProcess) {
  70900. postProcess.shareOutputWith(this._prevPrevPostProcess);
  70901. }
  70902. else {
  70903. postProcess.useOwnOutput();
  70904. }
  70905. if (this._prevPostProcess) {
  70906. this._prevPrevPostProcess = this._prevPostProcess;
  70907. }
  70908. this._prevPostProcess = postProcess;
  70909. }
  70910. };
  70911. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  70912. var _this = this;
  70913. if (!this._buildAllowed) {
  70914. return;
  70915. }
  70916. var engine = this._scene.getEngine();
  70917. this._disposePostProcesses();
  70918. if (this._cameras !== null) {
  70919. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70920. // get back cameras to be used to reattach pipeline
  70921. this._cameras = this._originalCameras.slice();
  70922. }
  70923. this._reset();
  70924. this._prevPostProcess = null;
  70925. this._prevPrevPostProcess = null;
  70926. if (this.sharpenEnabled) {
  70927. if (!this.sharpen.isReady()) {
  70928. this.sharpen.updateEffect();
  70929. }
  70930. this.addEffect(this._sharpenEffect);
  70931. this._setAutoClearAndTextureSharing(this.sharpen);
  70932. }
  70933. if (this.depthOfFieldEnabled) {
  70934. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  70935. this.depthOfField.depthTexture = depthTexture;
  70936. if (!this.depthOfField._isReady()) {
  70937. this.depthOfField._updateEffects();
  70938. }
  70939. this.addEffect(this.depthOfField);
  70940. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  70941. }
  70942. if (this.bloomEnabled) {
  70943. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70944. this._setAutoClearAndTextureSharing(this.pass, true);
  70945. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  70946. if (!this._hdr) {
  70947. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70948. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  70949. this.highlights.autoClear = false;
  70950. this.highlights.alwaysForcePOT = true;
  70951. }
  70952. 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);
  70953. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  70954. this.blurX.alwaysForcePOT = true;
  70955. this.blurX.autoClear = false;
  70956. this.blurX.onActivateObservable.add(function () {
  70957. var dw = _this.blurX.width / engine.getRenderWidth(true);
  70958. _this.blurX.kernel = _this.bloomKernel * dw;
  70959. });
  70960. 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);
  70961. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  70962. this.blurY.alwaysForcePOT = true;
  70963. this.blurY.autoClear = false;
  70964. this.blurY.onActivateObservable.add(function () {
  70965. var dh = _this.blurY.height / engine.getRenderHeight(true);
  70966. _this.blurY.kernel = _this.bloomKernel * dh;
  70967. });
  70968. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70969. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  70970. this.copyBack.alwaysForcePOT = true;
  70971. if (this._hdr) {
  70972. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  70973. var w = this.bloomWeight;
  70974. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  70975. }
  70976. else {
  70977. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  70978. }
  70979. this.copyBack.autoClear = false;
  70980. }
  70981. if (this._imageProcessingEnabled) {
  70982. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70983. if (this._hdr) {
  70984. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  70985. }
  70986. else {
  70987. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  70988. }
  70989. }
  70990. if (this._hdr && this.imageProcessing) {
  70991. this.finalMerge = this.imageProcessing;
  70992. }
  70993. else {
  70994. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70995. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  70996. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  70997. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  70998. }
  70999. if (this.bloomEnabled) {
  71000. if (this._hdr) {
  71001. this.copyBack.shareOutputWith(this.blurX);
  71002. if (this.imageProcessing) {
  71003. this.imageProcessing.shareOutputWith(this.pass);
  71004. this.imageProcessing.autoClear = false;
  71005. }
  71006. else {
  71007. this.finalMerge.shareOutputWith(this.pass);
  71008. }
  71009. }
  71010. else {
  71011. this.finalMerge.shareOutputWith(this.pass);
  71012. }
  71013. }
  71014. if (this.fxaaEnabled) {
  71015. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71016. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  71017. this._setAutoClearAndTextureSharing(this.fxaa);
  71018. }
  71019. if (this.chromaticAberrationEnabled) {
  71020. if (!this.chromaticAberration.isReady()) {
  71021. this.chromaticAberration.updateEffect();
  71022. }
  71023. this.addEffect(this._chromaticAberrationEffect);
  71024. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  71025. }
  71026. if (this._cameras !== null) {
  71027. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  71028. }
  71029. if (this.msaaEnabled) {
  71030. if (!this._enableMSAAOnFirstPostProcess()) {
  71031. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  71032. }
  71033. }
  71034. };
  71035. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  71036. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  71037. for (var i = 0; i < this._cameras.length; i++) {
  71038. var camera = this._cameras[i];
  71039. if (this.pass) {
  71040. this.pass.dispose(camera);
  71041. }
  71042. if (this.highlights) {
  71043. this.highlights.dispose(camera);
  71044. }
  71045. if (this.blurX) {
  71046. this.blurX.dispose(camera);
  71047. }
  71048. if (this.blurY) {
  71049. this.blurY.dispose(camera);
  71050. }
  71051. if (this.copyBack) {
  71052. this.copyBack.dispose(camera);
  71053. }
  71054. if (this.imageProcessing) {
  71055. this.imageProcessing.dispose(camera);
  71056. }
  71057. if (this.fxaa) {
  71058. this.fxaa.dispose(camera);
  71059. }
  71060. if (this.finalMerge) {
  71061. this.finalMerge.dispose(camera);
  71062. }
  71063. // These are created in the constructor and should not be disposed on every pipeline change
  71064. if (disposeNonRecreated) {
  71065. if (this.sharpen) {
  71066. this.sharpen.dispose(camera);
  71067. }
  71068. if (this.depthOfField) {
  71069. this.depthOfField.disposeEffects(camera);
  71070. }
  71071. if (this.chromaticAberration) {
  71072. this.chromaticAberration.dispose(camera);
  71073. }
  71074. }
  71075. }
  71076. this.pass = null;
  71077. this.highlights = null;
  71078. this.blurX = null;
  71079. this.blurY = null;
  71080. this.copyBack = null;
  71081. this.imageProcessing = null;
  71082. this.fxaa = null;
  71083. this.finalMerge = null;
  71084. if (disposeNonRecreated) {
  71085. this.sharpen = null;
  71086. this.depthOfField = null;
  71087. this.chromaticAberration = null;
  71088. }
  71089. };
  71090. /**
  71091. * Dispose of the pipeline and stop all post processes
  71092. */
  71093. DefaultRenderingPipeline.prototype.dispose = function () {
  71094. this._disposePostProcesses(true);
  71095. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  71096. _super.prototype.dispose.call(this);
  71097. };
  71098. /**
  71099. * Serialize the rendering pipeline (Used when exporting)
  71100. * @returns the serialized object
  71101. */
  71102. DefaultRenderingPipeline.prototype.serialize = function () {
  71103. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  71104. serializationObject.customType = "DefaultRenderingPipeline";
  71105. return serializationObject;
  71106. };
  71107. /**
  71108. * Parse the serialized pipeline
  71109. * @param source Source pipeline.
  71110. * @param scene The scene to load the pipeline to.
  71111. * @param rootUrl The URL of the serialized pipeline.
  71112. * @returns An instantiated pipeline from the serialized object.
  71113. */
  71114. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  71115. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  71116. };
  71117. __decorate([
  71118. BABYLON.serialize()
  71119. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  71120. __decorate([
  71121. BABYLON.serialize()
  71122. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  71123. __decorate([
  71124. BABYLON.serialize()
  71125. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  71126. __decorate([
  71127. BABYLON.serialize()
  71128. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  71129. __decorate([
  71130. BABYLON.serialize()
  71131. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  71132. __decorate([
  71133. BABYLON.serialize()
  71134. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  71135. __decorate([
  71136. BABYLON.serialize()
  71137. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  71138. __decorate([
  71139. BABYLON.serialize()
  71140. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  71141. __decorate([
  71142. BABYLON.serialize()
  71143. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  71144. __decorate([
  71145. BABYLON.serialize()
  71146. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  71147. __decorate([
  71148. BABYLON.serialize()
  71149. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  71150. __decorate([
  71151. BABYLON.serialize()
  71152. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  71153. __decorate([
  71154. BABYLON.serialize()
  71155. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  71156. return DefaultRenderingPipeline;
  71157. }(BABYLON.PostProcessRenderPipeline));
  71158. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  71159. })(BABYLON || (BABYLON = {}));
  71160. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  71161. "use strict";
  71162. var BABYLON;
  71163. (function (BABYLON) {
  71164. /**
  71165. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  71166. */
  71167. var GeometryBufferRenderer = /** @class */ (function () {
  71168. /**
  71169. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  71170. * @param scene The scene the buffer belongs to
  71171. * @param ratio How big is the buffer related to the main canvas.
  71172. */
  71173. function GeometryBufferRenderer(scene, ratio) {
  71174. if (ratio === void 0) { ratio = 1; }
  71175. this._enablePosition = false;
  71176. this._scene = scene;
  71177. this._ratio = ratio;
  71178. // Render target
  71179. this._createRenderTargets();
  71180. }
  71181. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  71182. /**
  71183. * Set the render list (meshes to be rendered) used in the G buffer.
  71184. */
  71185. set: function (meshes) {
  71186. this._multiRenderTarget.renderList = meshes;
  71187. },
  71188. enumerable: true,
  71189. configurable: true
  71190. });
  71191. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  71192. /**
  71193. * Gets wether or not G buffer are supported by the running hardware.
  71194. * This requires draw buffer supports
  71195. */
  71196. get: function () {
  71197. return this._multiRenderTarget.isSupported;
  71198. },
  71199. enumerable: true,
  71200. configurable: true
  71201. });
  71202. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  71203. /**
  71204. * Gets wether or not position are enabled for the G buffer.
  71205. */
  71206. get: function () {
  71207. return this._enablePosition;
  71208. },
  71209. /**
  71210. * Sets wether or not position are enabled for the G buffer.
  71211. */
  71212. set: function (enable) {
  71213. this._enablePosition = enable;
  71214. this.dispose();
  71215. this._createRenderTargets();
  71216. },
  71217. enumerable: true,
  71218. configurable: true
  71219. });
  71220. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  71221. /**
  71222. * Gets the scene associated with the buffer.
  71223. */
  71224. get: function () {
  71225. return this._scene;
  71226. },
  71227. enumerable: true,
  71228. configurable: true
  71229. });
  71230. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  71231. /**
  71232. * Gets the ratio used by the buffer during its creation.
  71233. * How big is the buffer related to the main canvas.
  71234. */
  71235. get: function () {
  71236. return this._ratio;
  71237. },
  71238. enumerable: true,
  71239. configurable: true
  71240. });
  71241. /**
  71242. * Checks wether everything is ready to render a submesh to the G buffer.
  71243. * @param subMesh the submesh to check readiness for
  71244. * @param useInstances is the mesh drawn using instance or not
  71245. * @returns true if ready otherwise false
  71246. */
  71247. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  71248. var material = subMesh.getMaterial();
  71249. if (material && material.disableDepthWrite) {
  71250. return false;
  71251. }
  71252. var defines = [];
  71253. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71254. var mesh = subMesh.getMesh();
  71255. // Alpha test
  71256. if (material && material.needAlphaTesting()) {
  71257. defines.push("#define ALPHATEST");
  71258. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71259. attribs.push(BABYLON.VertexBuffer.UVKind);
  71260. defines.push("#define UV1");
  71261. }
  71262. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71263. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71264. defines.push("#define UV2");
  71265. }
  71266. }
  71267. // Buffers
  71268. if (this._enablePosition) {
  71269. defines.push("#define POSITION");
  71270. }
  71271. // Bones
  71272. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71273. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71274. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71275. if (mesh.numBoneInfluencers > 4) {
  71276. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71277. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71278. }
  71279. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71280. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71281. }
  71282. else {
  71283. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71284. }
  71285. // Instances
  71286. if (useInstances) {
  71287. defines.push("#define INSTANCES");
  71288. attribs.push("world0");
  71289. attribs.push("world1");
  71290. attribs.push("world2");
  71291. attribs.push("world3");
  71292. }
  71293. // Get correct effect
  71294. var join = defines.join("\n");
  71295. if (this._cachedDefines !== join) {
  71296. this._cachedDefines = join;
  71297. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  71298. }
  71299. return this._effect.isReady();
  71300. };
  71301. /**
  71302. * Gets the current underlying G Buffer.
  71303. * @returns the buffer
  71304. */
  71305. GeometryBufferRenderer.prototype.getGBuffer = function () {
  71306. return this._multiRenderTarget;
  71307. };
  71308. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  71309. /**
  71310. * Gets the number of samples used to render the buffer (anti aliasing).
  71311. */
  71312. get: function () {
  71313. return this._multiRenderTarget.samples;
  71314. },
  71315. /**
  71316. * Sets the number of samples used to render the buffer (anti aliasing).
  71317. */
  71318. set: function (value) {
  71319. this._multiRenderTarget.samples = value;
  71320. },
  71321. enumerable: true,
  71322. configurable: true
  71323. });
  71324. /**
  71325. * Disposes the renderer and frees up associated resources.
  71326. */
  71327. GeometryBufferRenderer.prototype.dispose = function () {
  71328. this.getGBuffer().dispose();
  71329. };
  71330. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  71331. var _this = this;
  71332. var engine = this._scene.getEngine();
  71333. var count = this._enablePosition ? 3 : 2;
  71334. 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 });
  71335. if (!this.isSupported) {
  71336. return;
  71337. }
  71338. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71339. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71340. this._multiRenderTarget.refreshRate = 1;
  71341. this._multiRenderTarget.renderParticles = false;
  71342. this._multiRenderTarget.renderList = null;
  71343. // set default depth value to 1.0 (far away)
  71344. this._multiRenderTarget.onClearObservable.add(function (engine) {
  71345. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  71346. });
  71347. // Custom render function
  71348. var renderSubMesh = function (subMesh) {
  71349. var mesh = subMesh.getRenderingMesh();
  71350. var scene = _this._scene;
  71351. var engine = scene.getEngine();
  71352. var material = subMesh.getMaterial();
  71353. if (!material) {
  71354. return;
  71355. }
  71356. // Culling
  71357. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71358. // Managing instances
  71359. var batch = mesh._getInstancesRenderList(subMesh._id);
  71360. if (batch.mustReturn) {
  71361. return;
  71362. }
  71363. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71364. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  71365. engine.enableEffect(_this._effect);
  71366. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71367. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71368. _this._effect.setMatrix("view", scene.getViewMatrix());
  71369. // Alpha test
  71370. if (material && material.needAlphaTesting()) {
  71371. var alphaTexture = material.getAlphaTestTexture();
  71372. if (alphaTexture) {
  71373. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71374. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71375. }
  71376. }
  71377. // Bones
  71378. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71379. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71380. }
  71381. // Draw
  71382. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71383. }
  71384. };
  71385. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71386. var index;
  71387. if (depthOnlySubMeshes.length) {
  71388. engine.setColorWrite(false);
  71389. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71390. renderSubMesh(depthOnlySubMeshes.data[index]);
  71391. }
  71392. engine.setColorWrite(true);
  71393. }
  71394. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71395. renderSubMesh(opaqueSubMeshes.data[index]);
  71396. }
  71397. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71398. renderSubMesh(alphaTestSubMeshes.data[index]);
  71399. }
  71400. };
  71401. };
  71402. return GeometryBufferRenderer;
  71403. }());
  71404. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  71405. })(BABYLON || (BABYLON = {}));
  71406. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  71407. "use strict";
  71408. var BABYLON;
  71409. (function (BABYLON) {
  71410. var RefractionPostProcess = /** @class */ (function (_super) {
  71411. __extends(RefractionPostProcess, _super);
  71412. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  71413. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  71414. _this.color = color;
  71415. _this.depth = depth;
  71416. _this.colorLevel = colorLevel;
  71417. _this._ownRefractionTexture = true;
  71418. _this.onActivateObservable.add(function (cam) {
  71419. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  71420. });
  71421. _this.onApplyObservable.add(function (effect) {
  71422. effect.setColor3("baseColor", _this.color);
  71423. effect.setFloat("depth", _this.depth);
  71424. effect.setFloat("colorLevel", _this.colorLevel);
  71425. effect.setTexture("refractionSampler", _this._refTexture);
  71426. });
  71427. return _this;
  71428. }
  71429. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  71430. /**
  71431. * Gets or sets the refraction texture
  71432. * Please note that you are responsible for disposing the texture if you set it manually
  71433. */
  71434. get: function () {
  71435. return this._refTexture;
  71436. },
  71437. set: function (value) {
  71438. if (this._refTexture && this._ownRefractionTexture) {
  71439. this._refTexture.dispose();
  71440. }
  71441. this._refTexture = value;
  71442. this._ownRefractionTexture = false;
  71443. },
  71444. enumerable: true,
  71445. configurable: true
  71446. });
  71447. // Methods
  71448. RefractionPostProcess.prototype.dispose = function (camera) {
  71449. if (this._refTexture && this._ownRefractionTexture) {
  71450. this._refTexture.dispose();
  71451. this._refTexture = null;
  71452. }
  71453. _super.prototype.dispose.call(this, camera);
  71454. };
  71455. return RefractionPostProcess;
  71456. }(BABYLON.PostProcess));
  71457. BABYLON.RefractionPostProcess = RefractionPostProcess;
  71458. })(BABYLON || (BABYLON = {}));
  71459. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  71460. "use strict";
  71461. var BABYLON;
  71462. (function (BABYLON) {
  71463. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  71464. __extends(BlackAndWhitePostProcess, _super);
  71465. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  71466. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  71467. _this.degree = 1;
  71468. _this.onApplyObservable.add(function (effect) {
  71469. effect.setFloat("degree", _this.degree);
  71470. });
  71471. return _this;
  71472. }
  71473. return BlackAndWhitePostProcess;
  71474. }(BABYLON.PostProcess));
  71475. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  71476. })(BABYLON || (BABYLON = {}));
  71477. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  71478. "use strict";
  71479. var BABYLON;
  71480. (function (BABYLON) {
  71481. /**
  71482. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  71483. * input texture to perform effects such as edge detection or sharpening
  71484. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  71485. */
  71486. var ConvolutionPostProcess = /** @class */ (function (_super) {
  71487. __extends(ConvolutionPostProcess, _super);
  71488. /**
  71489. * Creates a new instance of @see ConvolutionPostProcess
  71490. * @param name The name of the effect.
  71491. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  71492. * @param options The required width/height ratio to downsize to before computing the render pass.
  71493. * @param camera The camera to apply the render pass to.
  71494. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71495. * @param engine The engine which the post process will be applied. (default: current engine)
  71496. * @param reusable If the post process can be reused on the same frame. (default: false)
  71497. * @param textureType Type of textures used when performing the post process. (default: 0)
  71498. */
  71499. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  71500. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71501. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71502. _this.kernel = kernel;
  71503. _this.onApply = function (effect) {
  71504. effect.setFloat2("screenSize", _this.width, _this.height);
  71505. effect.setArray("kernel", _this.kernel);
  71506. };
  71507. return _this;
  71508. }
  71509. // Statics
  71510. /**
  71511. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71512. */
  71513. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  71514. /**
  71515. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71516. */
  71517. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  71518. /**
  71519. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71520. */
  71521. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  71522. /**
  71523. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71524. */
  71525. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  71526. /**
  71527. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71528. */
  71529. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  71530. /**
  71531. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71532. */
  71533. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  71534. return ConvolutionPostProcess;
  71535. }(BABYLON.PostProcess));
  71536. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  71537. })(BABYLON || (BABYLON = {}));
  71538. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  71539. "use strict";
  71540. var BABYLON;
  71541. (function (BABYLON) {
  71542. var FilterPostProcess = /** @class */ (function (_super) {
  71543. __extends(FilterPostProcess, _super);
  71544. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  71545. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  71546. _this.kernelMatrix = kernelMatrix;
  71547. _this.onApply = function (effect) {
  71548. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  71549. };
  71550. return _this;
  71551. }
  71552. return FilterPostProcess;
  71553. }(BABYLON.PostProcess));
  71554. BABYLON.FilterPostProcess = FilterPostProcess;
  71555. })(BABYLON || (BABYLON = {}));
  71556. //# sourceMappingURL=babylon.filterPostProcess.js.map
  71557. "use strict";
  71558. var BABYLON;
  71559. (function (BABYLON) {
  71560. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71561. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71562. __extends(VolumetricLightScatteringPostProcess, _super);
  71563. /**
  71564. * @constructor
  71565. * @param {string} name - The post-process name
  71566. * @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)
  71567. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71568. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71569. * @param {number} samples - The post-process quality, default 100
  71570. * @param {number} samplingMode - The post-process filtering mode
  71571. * @param {BABYLON.Engine} engine - The babylon engine
  71572. * @param {boolean} reusable - If the post-process is reusable
  71573. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71574. */
  71575. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71576. if (samples === void 0) { samples = 100; }
  71577. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71578. 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;
  71579. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71580. /**
  71581. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71582. * @type {Vector3}
  71583. */
  71584. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71585. /**
  71586. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71587. * @type {boolean}
  71588. */
  71589. _this.useCustomMeshPosition = false;
  71590. /**
  71591. * If the post-process should inverse the light scattering direction
  71592. * @type {boolean}
  71593. */
  71594. _this.invert = true;
  71595. /**
  71596. * Array containing the excluded meshes not rendered in the internal pass
  71597. */
  71598. _this.excludedMeshes = new Array();
  71599. /**
  71600. * Controls the overall intensity of the post-process
  71601. * @type {number}
  71602. */
  71603. _this.exposure = 0.3;
  71604. /**
  71605. * Dissipates each sample's contribution in range [0, 1]
  71606. * @type {number}
  71607. */
  71608. _this.decay = 0.96815;
  71609. /**
  71610. * Controls the overall intensity of each sample
  71611. * @type {number}
  71612. */
  71613. _this.weight = 0.58767;
  71614. /**
  71615. * Controls the density of each sample
  71616. * @type {number}
  71617. */
  71618. _this.density = 0.926;
  71619. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71620. engine = scene.getEngine();
  71621. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71622. // Configure mesh
  71623. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71624. // Configure
  71625. _this._createPass(scene, ratio.passRatio || ratio);
  71626. _this.onActivate = function (camera) {
  71627. if (!_this.isSupported) {
  71628. _this.dispose(camera);
  71629. }
  71630. _this.onActivate = null;
  71631. };
  71632. _this.onApplyObservable.add(function (effect) {
  71633. _this._updateMeshScreenCoordinates(scene);
  71634. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71635. effect.setFloat("exposure", _this.exposure);
  71636. effect.setFloat("decay", _this.decay);
  71637. effect.setFloat("weight", _this.weight);
  71638. effect.setFloat("density", _this.density);
  71639. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71640. });
  71641. return _this;
  71642. }
  71643. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71644. get: function () {
  71645. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71646. return false;
  71647. },
  71648. set: function (useDiffuseColor) {
  71649. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71650. },
  71651. enumerable: true,
  71652. configurable: true
  71653. });
  71654. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71655. return "VolumetricLightScatteringPostProcess";
  71656. };
  71657. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71658. var mesh = subMesh.getMesh();
  71659. // Render this.mesh as default
  71660. if (mesh === this.mesh && mesh.material) {
  71661. return mesh.material.isReady(mesh);
  71662. }
  71663. var defines = [];
  71664. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71665. var material = subMesh.getMaterial();
  71666. // Alpha test
  71667. if (material) {
  71668. if (material.needAlphaTesting()) {
  71669. defines.push("#define ALPHATEST");
  71670. }
  71671. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71672. attribs.push(BABYLON.VertexBuffer.UVKind);
  71673. defines.push("#define UV1");
  71674. }
  71675. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71676. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71677. defines.push("#define UV2");
  71678. }
  71679. }
  71680. // Bones
  71681. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71682. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71683. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71684. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71685. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71686. }
  71687. else {
  71688. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71689. }
  71690. // Instances
  71691. if (useInstances) {
  71692. defines.push("#define INSTANCES");
  71693. attribs.push("world0");
  71694. attribs.push("world1");
  71695. attribs.push("world2");
  71696. attribs.push("world3");
  71697. }
  71698. // Get correct effect
  71699. var join = defines.join("\n");
  71700. if (this._cachedDefines !== join) {
  71701. this._cachedDefines = join;
  71702. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71703. }
  71704. return this._volumetricLightScatteringPass.isReady();
  71705. };
  71706. /**
  71707. * Sets the new light position for light scattering effect
  71708. * @param {BABYLON.Vector3} The new custom light position
  71709. */
  71710. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71711. this.customMeshPosition = position;
  71712. };
  71713. /**
  71714. * Returns the light position for light scattering effect
  71715. * @return {BABYLON.Vector3} The custom light position
  71716. */
  71717. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  71718. return this.customMeshPosition;
  71719. };
  71720. /**
  71721. * Disposes the internal assets and detaches the post-process from the camera
  71722. */
  71723. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  71724. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  71725. if (rttIndex !== -1) {
  71726. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  71727. }
  71728. this._volumetricLightScatteringRTT.dispose();
  71729. _super.prototype.dispose.call(this, camera);
  71730. };
  71731. /**
  71732. * Returns the render target texture used by the post-process
  71733. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  71734. */
  71735. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  71736. return this._volumetricLightScatteringRTT;
  71737. };
  71738. // Private methods
  71739. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  71740. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  71741. return true;
  71742. }
  71743. return false;
  71744. };
  71745. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  71746. var _this = this;
  71747. var engine = scene.getEngine();
  71748. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71749. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71750. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71751. this._volumetricLightScatteringRTT.renderList = null;
  71752. this._volumetricLightScatteringRTT.renderParticles = false;
  71753. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  71754. var camera = this.getCamera();
  71755. if (camera) {
  71756. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71757. }
  71758. else {
  71759. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71760. }
  71761. // Custom render function for submeshes
  71762. var renderSubMesh = function (subMesh) {
  71763. var mesh = subMesh.getRenderingMesh();
  71764. if (_this._meshExcluded(mesh)) {
  71765. return;
  71766. }
  71767. var material = subMesh.getMaterial();
  71768. if (!material) {
  71769. return;
  71770. }
  71771. var scene = mesh.getScene();
  71772. var engine = scene.getEngine();
  71773. // Culling
  71774. engine.setState(material.backFaceCulling);
  71775. // Managing instances
  71776. var batch = mesh._getInstancesRenderList(subMesh._id);
  71777. if (batch.mustReturn) {
  71778. return;
  71779. }
  71780. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71781. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  71782. var effect = _this._volumetricLightScatteringPass;
  71783. if (mesh === _this.mesh) {
  71784. if (subMesh.effect) {
  71785. effect = subMesh.effect;
  71786. }
  71787. else {
  71788. effect = material.getEffect();
  71789. }
  71790. }
  71791. engine.enableEffect(effect);
  71792. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  71793. if (mesh === _this.mesh) {
  71794. material.bind(mesh.getWorldMatrix(), mesh);
  71795. }
  71796. else {
  71797. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  71798. // Alpha test
  71799. if (material && material.needAlphaTesting()) {
  71800. var alphaTexture = material.getAlphaTestTexture();
  71801. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  71802. if (alphaTexture) {
  71803. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71804. }
  71805. }
  71806. // Bones
  71807. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71808. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71809. }
  71810. }
  71811. // Draw
  71812. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  71813. }
  71814. };
  71815. // Render target texture callbacks
  71816. var savedSceneClearColor;
  71817. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  71818. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  71819. savedSceneClearColor = scene.clearColor;
  71820. scene.clearColor = sceneClearColor;
  71821. });
  71822. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  71823. scene.clearColor = savedSceneClearColor;
  71824. });
  71825. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71826. var engine = scene.getEngine();
  71827. var index;
  71828. if (depthOnlySubMeshes.length) {
  71829. engine.setColorWrite(false);
  71830. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71831. renderSubMesh(depthOnlySubMeshes.data[index]);
  71832. }
  71833. engine.setColorWrite(true);
  71834. }
  71835. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71836. renderSubMesh(opaqueSubMeshes.data[index]);
  71837. }
  71838. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71839. renderSubMesh(alphaTestSubMeshes.data[index]);
  71840. }
  71841. if (transparentSubMeshes.length) {
  71842. // Sort sub meshes
  71843. for (index = 0; index < transparentSubMeshes.length; index++) {
  71844. var submesh = transparentSubMeshes.data[index];
  71845. var boundingInfo = submesh.getBoundingInfo();
  71846. if (boundingInfo && scene.activeCamera) {
  71847. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  71848. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  71849. }
  71850. }
  71851. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  71852. sortedArray.sort(function (a, b) {
  71853. // Alpha index first
  71854. if (a._alphaIndex > b._alphaIndex) {
  71855. return 1;
  71856. }
  71857. if (a._alphaIndex < b._alphaIndex) {
  71858. return -1;
  71859. }
  71860. // Then distance to camera
  71861. if (a._distanceToCamera < b._distanceToCamera) {
  71862. return 1;
  71863. }
  71864. if (a._distanceToCamera > b._distanceToCamera) {
  71865. return -1;
  71866. }
  71867. return 0;
  71868. });
  71869. // Render sub meshes
  71870. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  71871. for (index = 0; index < sortedArray.length; index++) {
  71872. renderSubMesh(sortedArray[index]);
  71873. }
  71874. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71875. }
  71876. };
  71877. };
  71878. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  71879. var transform = scene.getTransformMatrix();
  71880. var meshPosition;
  71881. if (this.useCustomMeshPosition) {
  71882. meshPosition = this.customMeshPosition;
  71883. }
  71884. else if (this.attachedNode) {
  71885. meshPosition = this.attachedNode.position;
  71886. }
  71887. else {
  71888. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  71889. }
  71890. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  71891. this._screenCoordinates.x = pos.x / this._viewPort.width;
  71892. this._screenCoordinates.y = pos.y / this._viewPort.height;
  71893. if (this.invert)
  71894. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  71895. };
  71896. // Static methods
  71897. /**
  71898. * Creates a default mesh for the Volumeric Light Scattering post-process
  71899. * @param {string} The mesh name
  71900. * @param {BABYLON.Scene} The scene where to create the mesh
  71901. * @return {BABYLON.Mesh} the default mesh
  71902. */
  71903. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  71904. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  71905. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  71906. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  71907. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  71908. mesh.material = material;
  71909. return mesh;
  71910. };
  71911. __decorate([
  71912. BABYLON.serializeAsVector3()
  71913. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  71914. __decorate([
  71915. BABYLON.serialize()
  71916. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  71917. __decorate([
  71918. BABYLON.serialize()
  71919. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  71920. __decorate([
  71921. BABYLON.serializeAsMeshReference()
  71922. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  71923. __decorate([
  71924. BABYLON.serialize()
  71925. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  71926. __decorate([
  71927. BABYLON.serialize()
  71928. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  71929. __decorate([
  71930. BABYLON.serialize()
  71931. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  71932. __decorate([
  71933. BABYLON.serialize()
  71934. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  71935. __decorate([
  71936. BABYLON.serialize()
  71937. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  71938. return VolumetricLightScatteringPostProcess;
  71939. }(BABYLON.PostProcess));
  71940. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  71941. })(BABYLON || (BABYLON = {}));
  71942. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  71943. "use strict";
  71944. //
  71945. // This post-process allows the modification of rendered colors by using
  71946. // a 'look-up table' (LUT). This effect is also called Color Grading.
  71947. //
  71948. // The object needs to be provided an url to a texture containing the color
  71949. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  71950. // Use an image editing software to tweak the LUT to match your needs.
  71951. //
  71952. // For an example of a color LUT, see here:
  71953. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  71954. // For explanations on color grading, see here:
  71955. // http://udn.epicgames.com/Three/ColorGrading.html
  71956. //
  71957. var BABYLON;
  71958. (function (BABYLON) {
  71959. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  71960. __extends(ColorCorrectionPostProcess, _super);
  71961. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  71962. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  71963. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71964. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  71965. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71966. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71967. _this.onApply = function (effect) {
  71968. effect.setTexture("colorTable", _this._colorTableTexture);
  71969. };
  71970. return _this;
  71971. }
  71972. return ColorCorrectionPostProcess;
  71973. }(BABYLON.PostProcess));
  71974. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  71975. })(BABYLON || (BABYLON = {}));
  71976. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  71977. "use strict";
  71978. var BABYLON;
  71979. (function (BABYLON) {
  71980. var TonemappingOperator;
  71981. (function (TonemappingOperator) {
  71982. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  71983. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  71984. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  71985. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  71986. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  71987. ;
  71988. var TonemapPostProcess = /** @class */ (function (_super) {
  71989. __extends(TonemapPostProcess, _super);
  71990. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  71991. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71992. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71993. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  71994. _this._operator = _operator;
  71995. _this.exposureAdjustment = exposureAdjustment;
  71996. var defines = "#define ";
  71997. if (_this._operator === TonemappingOperator.Hable)
  71998. defines += "HABLE_TONEMAPPING";
  71999. else if (_this._operator === TonemappingOperator.Reinhard)
  72000. defines += "REINHARD_TONEMAPPING";
  72001. else if (_this._operator === TonemappingOperator.HejiDawson)
  72002. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  72003. else if (_this._operator === TonemappingOperator.Photographic)
  72004. defines += "PHOTOGRAPHIC_TONEMAPPING";
  72005. //sadly a second call to create the effect.
  72006. _this.updateEffect(defines);
  72007. _this.onApply = function (effect) {
  72008. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  72009. };
  72010. return _this;
  72011. }
  72012. return TonemapPostProcess;
  72013. }(BABYLON.PostProcess));
  72014. BABYLON.TonemapPostProcess = TonemapPostProcess;
  72015. })(BABYLON || (BABYLON = {}));
  72016. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  72017. "use strict";
  72018. var BABYLON;
  72019. (function (BABYLON) {
  72020. var DisplayPassPostProcess = /** @class */ (function (_super) {
  72021. __extends(DisplayPassPostProcess, _super);
  72022. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  72023. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  72024. }
  72025. return DisplayPassPostProcess;
  72026. }(BABYLON.PostProcess));
  72027. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  72028. })(BABYLON || (BABYLON = {}));
  72029. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  72030. "use strict";
  72031. var BABYLON;
  72032. (function (BABYLON) {
  72033. var HighlightsPostProcess = /** @class */ (function (_super) {
  72034. __extends(HighlightsPostProcess, _super);
  72035. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  72036. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72037. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  72038. }
  72039. return HighlightsPostProcess;
  72040. }(BABYLON.PostProcess));
  72041. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  72042. })(BABYLON || (BABYLON = {}));
  72043. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  72044. "use strict";
  72045. var BABYLON;
  72046. (function (BABYLON) {
  72047. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  72048. __extends(ImageProcessingPostProcess, _super);
  72049. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  72050. if (camera === void 0) { camera = null; }
  72051. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72052. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  72053. _this._fromLinearSpace = true;
  72054. /**
  72055. * Defines cache preventing GC.
  72056. */
  72057. _this._defines = {
  72058. IMAGEPROCESSING: false,
  72059. VIGNETTE: false,
  72060. VIGNETTEBLENDMODEMULTIPLY: false,
  72061. VIGNETTEBLENDMODEOPAQUE: false,
  72062. TONEMAPPING: false,
  72063. CONTRAST: false,
  72064. COLORCURVES: false,
  72065. COLORGRADING: false,
  72066. COLORGRADING3D: false,
  72067. FROMLINEARSPACE: false,
  72068. SAMPLER3DGREENDEPTH: false,
  72069. SAMPLER3DBGRMAP: false,
  72070. IMAGEPROCESSINGPOSTPROCESS: false,
  72071. EXPOSURE: false,
  72072. GRAIN: false,
  72073. };
  72074. // Setup the configuration as forced by the constructor. This would then not force the
  72075. // scene materials output in linear space and let untouched the default forward pass.
  72076. if (imageProcessingConfiguration) {
  72077. imageProcessingConfiguration.applyByPostProcess = true;
  72078. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  72079. // This will cause the shader to be compiled
  72080. _this.fromLinearSpace = false;
  72081. }
  72082. else {
  72083. _this._attachImageProcessingConfiguration(null, true);
  72084. _this.imageProcessingConfiguration.applyByPostProcess = true;
  72085. }
  72086. _this.onApply = function (effect) {
  72087. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  72088. };
  72089. return _this;
  72090. }
  72091. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  72092. /**
  72093. * Gets the image processing configuration used either in this material.
  72094. */
  72095. get: function () {
  72096. return this._imageProcessingConfiguration;
  72097. },
  72098. /**
  72099. * Sets the Default image processing configuration used either in the this material.
  72100. *
  72101. * If sets to null, the scene one is in use.
  72102. */
  72103. set: function (value) {
  72104. this._attachImageProcessingConfiguration(value);
  72105. },
  72106. enumerable: true,
  72107. configurable: true
  72108. });
  72109. /**
  72110. * Attaches a new image processing configuration to the PBR Material.
  72111. * @param configuration
  72112. */
  72113. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  72114. var _this = this;
  72115. if (doNotBuild === void 0) { doNotBuild = false; }
  72116. if (configuration === this._imageProcessingConfiguration) {
  72117. return;
  72118. }
  72119. // Detaches observer.
  72120. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72121. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72122. }
  72123. // Pick the scene configuration if needed.
  72124. if (!configuration) {
  72125. var scene = null;
  72126. var engine = this.getEngine();
  72127. var camera = this.getCamera();
  72128. if (camera) {
  72129. scene = camera.getScene();
  72130. }
  72131. else if (engine && engine.scenes) {
  72132. var scenes = engine.scenes;
  72133. scene = scenes[scenes.length - 1];
  72134. }
  72135. else {
  72136. scene = BABYLON.Engine.LastCreatedScene;
  72137. }
  72138. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  72139. }
  72140. else {
  72141. this._imageProcessingConfiguration = configuration;
  72142. }
  72143. // Attaches observer.
  72144. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  72145. _this._updateParameters();
  72146. });
  72147. // Ensure the effect will be rebuilt.
  72148. if (!doNotBuild) {
  72149. this._updateParameters();
  72150. }
  72151. };
  72152. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  72153. /**
  72154. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72155. */
  72156. get: function () {
  72157. return this.imageProcessingConfiguration.colorCurves;
  72158. },
  72159. /**
  72160. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72161. */
  72162. set: function (value) {
  72163. this.imageProcessingConfiguration.colorCurves = value;
  72164. },
  72165. enumerable: true,
  72166. configurable: true
  72167. });
  72168. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  72169. /**
  72170. * Gets wether the color curves effect is enabled.
  72171. */
  72172. get: function () {
  72173. return this.imageProcessingConfiguration.colorCurvesEnabled;
  72174. },
  72175. /**
  72176. * Sets wether the color curves effect is enabled.
  72177. */
  72178. set: function (value) {
  72179. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  72180. },
  72181. enumerable: true,
  72182. configurable: true
  72183. });
  72184. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  72185. /**
  72186. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72187. */
  72188. get: function () {
  72189. return this.imageProcessingConfiguration.colorGradingTexture;
  72190. },
  72191. /**
  72192. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72193. */
  72194. set: function (value) {
  72195. this.imageProcessingConfiguration.colorGradingTexture = value;
  72196. },
  72197. enumerable: true,
  72198. configurable: true
  72199. });
  72200. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  72201. /**
  72202. * Gets wether the color grading effect is enabled.
  72203. */
  72204. get: function () {
  72205. return this.imageProcessingConfiguration.colorGradingEnabled;
  72206. },
  72207. /**
  72208. * Gets wether the color grading effect is enabled.
  72209. */
  72210. set: function (value) {
  72211. this.imageProcessingConfiguration.colorGradingEnabled = value;
  72212. },
  72213. enumerable: true,
  72214. configurable: true
  72215. });
  72216. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  72217. /**
  72218. * Gets exposure used in the effect.
  72219. */
  72220. get: function () {
  72221. return this.imageProcessingConfiguration.exposure;
  72222. },
  72223. /**
  72224. * Sets exposure used in the effect.
  72225. */
  72226. set: function (value) {
  72227. this.imageProcessingConfiguration.exposure = value;
  72228. },
  72229. enumerable: true,
  72230. configurable: true
  72231. });
  72232. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  72233. /**
  72234. * Gets wether tonemapping is enabled or not.
  72235. */
  72236. get: function () {
  72237. return this._imageProcessingConfiguration.toneMappingEnabled;
  72238. },
  72239. /**
  72240. * Sets wether tonemapping is enabled or not
  72241. */
  72242. set: function (value) {
  72243. this._imageProcessingConfiguration.toneMappingEnabled = value;
  72244. },
  72245. enumerable: true,
  72246. configurable: true
  72247. });
  72248. ;
  72249. ;
  72250. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  72251. /**
  72252. * Gets contrast used in the effect.
  72253. */
  72254. get: function () {
  72255. return this.imageProcessingConfiguration.contrast;
  72256. },
  72257. /**
  72258. * Sets contrast used in the effect.
  72259. */
  72260. set: function (value) {
  72261. this.imageProcessingConfiguration.contrast = value;
  72262. },
  72263. enumerable: true,
  72264. configurable: true
  72265. });
  72266. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  72267. /**
  72268. * Gets Vignette stretch size.
  72269. */
  72270. get: function () {
  72271. return this.imageProcessingConfiguration.vignetteStretch;
  72272. },
  72273. /**
  72274. * Sets Vignette stretch size.
  72275. */
  72276. set: function (value) {
  72277. this.imageProcessingConfiguration.vignetteStretch = value;
  72278. },
  72279. enumerable: true,
  72280. configurable: true
  72281. });
  72282. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  72283. /**
  72284. * Gets Vignette centre X Offset.
  72285. */
  72286. get: function () {
  72287. return this.imageProcessingConfiguration.vignetteCentreX;
  72288. },
  72289. /**
  72290. * Sets Vignette centre X Offset.
  72291. */
  72292. set: function (value) {
  72293. this.imageProcessingConfiguration.vignetteCentreX = value;
  72294. },
  72295. enumerable: true,
  72296. configurable: true
  72297. });
  72298. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  72299. /**
  72300. * Gets Vignette centre Y Offset.
  72301. */
  72302. get: function () {
  72303. return this.imageProcessingConfiguration.vignetteCentreY;
  72304. },
  72305. /**
  72306. * Sets Vignette centre Y Offset.
  72307. */
  72308. set: function (value) {
  72309. this.imageProcessingConfiguration.vignetteCentreY = value;
  72310. },
  72311. enumerable: true,
  72312. configurable: true
  72313. });
  72314. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  72315. /**
  72316. * Gets Vignette weight or intensity of the vignette effect.
  72317. */
  72318. get: function () {
  72319. return this.imageProcessingConfiguration.vignetteWeight;
  72320. },
  72321. /**
  72322. * Sets Vignette weight or intensity of the vignette effect.
  72323. */
  72324. set: function (value) {
  72325. this.imageProcessingConfiguration.vignetteWeight = value;
  72326. },
  72327. enumerable: true,
  72328. configurable: true
  72329. });
  72330. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  72331. /**
  72332. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72333. * if vignetteEnabled is set to true.
  72334. */
  72335. get: function () {
  72336. return this.imageProcessingConfiguration.vignetteColor;
  72337. },
  72338. /**
  72339. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72340. * if vignetteEnabled is set to true.
  72341. */
  72342. set: function (value) {
  72343. this.imageProcessingConfiguration.vignetteColor = value;
  72344. },
  72345. enumerable: true,
  72346. configurable: true
  72347. });
  72348. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  72349. /**
  72350. * Gets Camera field of view used by the Vignette effect.
  72351. */
  72352. get: function () {
  72353. return this.imageProcessingConfiguration.vignetteCameraFov;
  72354. },
  72355. /**
  72356. * Sets Camera field of view used by the Vignette effect.
  72357. */
  72358. set: function (value) {
  72359. this.imageProcessingConfiguration.vignetteCameraFov = value;
  72360. },
  72361. enumerable: true,
  72362. configurable: true
  72363. });
  72364. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  72365. /**
  72366. * Gets the vignette blend mode allowing different kind of effect.
  72367. */
  72368. get: function () {
  72369. return this.imageProcessingConfiguration.vignetteBlendMode;
  72370. },
  72371. /**
  72372. * Sets the vignette blend mode allowing different kind of effect.
  72373. */
  72374. set: function (value) {
  72375. this.imageProcessingConfiguration.vignetteBlendMode = value;
  72376. },
  72377. enumerable: true,
  72378. configurable: true
  72379. });
  72380. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  72381. /**
  72382. * Gets wether the vignette effect is enabled.
  72383. */
  72384. get: function () {
  72385. return this.imageProcessingConfiguration.vignetteEnabled;
  72386. },
  72387. /**
  72388. * Sets wether the vignette effect is enabled.
  72389. */
  72390. set: function (value) {
  72391. this.imageProcessingConfiguration.vignetteEnabled = value;
  72392. },
  72393. enumerable: true,
  72394. configurable: true
  72395. });
  72396. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  72397. /**
  72398. * Gets wether the grain effect is enabled.
  72399. */
  72400. get: function () {
  72401. return this.imageProcessingConfiguration.grainEnabled;
  72402. },
  72403. /**
  72404. * Sets wether the grain effect is enabled.
  72405. */
  72406. set: function (value) {
  72407. this.imageProcessingConfiguration.grainEnabled = value;
  72408. },
  72409. enumerable: true,
  72410. configurable: true
  72411. });
  72412. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  72413. /**
  72414. * Gets the grain effect's intensity.
  72415. */
  72416. get: function () {
  72417. return this.imageProcessingConfiguration.grainIntensity;
  72418. },
  72419. /**
  72420. * Sets the grain effect's intensity.
  72421. */
  72422. set: function (value) {
  72423. this.imageProcessingConfiguration.grainIntensity = value;
  72424. },
  72425. enumerable: true,
  72426. configurable: true
  72427. });
  72428. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  72429. /**
  72430. * Gets wether the grain effect is animated.
  72431. */
  72432. get: function () {
  72433. return this.imageProcessingConfiguration.grainAnimated;
  72434. },
  72435. /**
  72436. * Sets wether the grain effect is animated.
  72437. */
  72438. set: function (value) {
  72439. this.imageProcessingConfiguration.grainAnimated = value;
  72440. },
  72441. enumerable: true,
  72442. configurable: true
  72443. });
  72444. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  72445. /**
  72446. * Gets wether the input of the processing is in Gamma or Linear Space.
  72447. */
  72448. get: function () {
  72449. return this._fromLinearSpace;
  72450. },
  72451. /**
  72452. * Sets wether the input of the processing is in Gamma or Linear Space.
  72453. */
  72454. set: function (value) {
  72455. if (this._fromLinearSpace === value) {
  72456. return;
  72457. }
  72458. this._fromLinearSpace = value;
  72459. this._updateParameters();
  72460. },
  72461. enumerable: true,
  72462. configurable: true
  72463. });
  72464. ImageProcessingPostProcess.prototype.getClassName = function () {
  72465. return "ImageProcessingPostProcess";
  72466. };
  72467. ImageProcessingPostProcess.prototype._updateParameters = function () {
  72468. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  72469. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  72470. var defines = "";
  72471. for (var define in this._defines) {
  72472. if (this._defines[define]) {
  72473. defines += "#define " + define + ";\r\n";
  72474. }
  72475. }
  72476. var samplers = ["textureSampler"];
  72477. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  72478. var uniforms = ["scale"];
  72479. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  72480. this.updateEffect(defines, uniforms, samplers);
  72481. };
  72482. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  72483. _super.prototype.dispose.call(this, camera);
  72484. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72485. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72486. }
  72487. this.imageProcessingConfiguration.applyByPostProcess = false;
  72488. };
  72489. __decorate([
  72490. BABYLON.serialize()
  72491. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  72492. return ImageProcessingPostProcess;
  72493. }(BABYLON.PostProcess));
  72494. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  72495. })(BABYLON || (BABYLON = {}));
  72496. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  72497. "use strict";
  72498. var BABYLON;
  72499. (function (BABYLON) {
  72500. var Bone = /** @class */ (function (_super) {
  72501. __extends(Bone, _super);
  72502. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  72503. if (parentBone === void 0) { parentBone = null; }
  72504. if (localMatrix === void 0) { localMatrix = null; }
  72505. if (restPose === void 0) { restPose = null; }
  72506. if (baseMatrix === void 0) { baseMatrix = null; }
  72507. if (index === void 0) { index = null; }
  72508. var _this = _super.call(this, name, skeleton.getScene()) || this;
  72509. _this.name = name;
  72510. _this.children = new Array();
  72511. _this.animations = new Array();
  72512. // Set this value to map this bone to a different index in the transform matrices.
  72513. // Set this value to -1 to exclude the bone from the transform matrices.
  72514. _this._index = null;
  72515. _this._worldTransform = new BABYLON.Matrix();
  72516. _this._absoluteTransform = new BABYLON.Matrix();
  72517. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  72518. _this._scaleMatrix = BABYLON.Matrix.Identity();
  72519. _this._scaleVector = BABYLON.Vector3.One();
  72520. _this._negateScaleChildren = BABYLON.Vector3.One();
  72521. _this._scalingDeterminant = 1;
  72522. _this._skeleton = skeleton;
  72523. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  72524. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  72525. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  72526. _this._index = index;
  72527. skeleton.bones.push(_this);
  72528. _this.setParent(parentBone, false);
  72529. _this._updateDifferenceMatrix();
  72530. return _this;
  72531. }
  72532. Object.defineProperty(Bone.prototype, "_matrix", {
  72533. get: function () {
  72534. return this._localMatrix;
  72535. },
  72536. set: function (val) {
  72537. if (this._localMatrix) {
  72538. this._localMatrix.copyFrom(val);
  72539. }
  72540. else {
  72541. this._localMatrix = val;
  72542. }
  72543. },
  72544. enumerable: true,
  72545. configurable: true
  72546. });
  72547. // Members
  72548. Bone.prototype.getSkeleton = function () {
  72549. return this._skeleton;
  72550. };
  72551. Bone.prototype.getParent = function () {
  72552. return this._parent;
  72553. };
  72554. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  72555. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72556. if (this._parent === parent) {
  72557. return;
  72558. }
  72559. if (this._parent) {
  72560. var index = this._parent.children.indexOf(this);
  72561. if (index !== -1) {
  72562. this._parent.children.splice(index, 1);
  72563. }
  72564. }
  72565. this._parent = parent;
  72566. if (this._parent) {
  72567. this._parent.children.push(this);
  72568. }
  72569. if (updateDifferenceMatrix) {
  72570. this._updateDifferenceMatrix();
  72571. }
  72572. };
  72573. Bone.prototype.getLocalMatrix = function () {
  72574. return this._localMatrix;
  72575. };
  72576. Bone.prototype.getBaseMatrix = function () {
  72577. return this._baseMatrix;
  72578. };
  72579. Bone.prototype.getRestPose = function () {
  72580. return this._restPose;
  72581. };
  72582. Bone.prototype.returnToRest = function () {
  72583. this.updateMatrix(this._restPose.clone());
  72584. };
  72585. Bone.prototype.getWorldMatrix = function () {
  72586. return this._worldTransform;
  72587. };
  72588. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72589. return this._invertedAbsoluteTransform;
  72590. };
  72591. Bone.prototype.getAbsoluteTransform = function () {
  72592. return this._absoluteTransform;
  72593. };
  72594. Object.defineProperty(Bone.prototype, "position", {
  72595. // Properties (matches AbstractMesh properties)
  72596. get: function () {
  72597. return this.getPosition();
  72598. },
  72599. set: function (newPosition) {
  72600. this.setPosition(newPosition);
  72601. },
  72602. enumerable: true,
  72603. configurable: true
  72604. });
  72605. Object.defineProperty(Bone.prototype, "rotation", {
  72606. get: function () {
  72607. return this.getRotation();
  72608. },
  72609. set: function (newRotation) {
  72610. this.setRotation(newRotation);
  72611. },
  72612. enumerable: true,
  72613. configurable: true
  72614. });
  72615. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72616. get: function () {
  72617. return this.getRotationQuaternion();
  72618. },
  72619. set: function (newRotation) {
  72620. this.setRotationQuaternion(newRotation);
  72621. },
  72622. enumerable: true,
  72623. configurable: true
  72624. });
  72625. Object.defineProperty(Bone.prototype, "scaling", {
  72626. get: function () {
  72627. return this.getScale();
  72628. },
  72629. set: function (newScaling) {
  72630. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72631. },
  72632. enumerable: true,
  72633. configurable: true
  72634. });
  72635. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72636. /**
  72637. * Gets the animation properties override
  72638. */
  72639. get: function () {
  72640. return this._skeleton.animationPropertiesOverride;
  72641. },
  72642. enumerable: true,
  72643. configurable: true
  72644. });
  72645. // Methods
  72646. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72647. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72648. this._baseMatrix = matrix.clone();
  72649. this._localMatrix = matrix.clone();
  72650. this._skeleton._markAsDirty();
  72651. if (updateDifferenceMatrix) {
  72652. this._updateDifferenceMatrix();
  72653. }
  72654. };
  72655. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72656. if (!rootMatrix) {
  72657. rootMatrix = this._baseMatrix;
  72658. }
  72659. if (this._parent) {
  72660. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72661. }
  72662. else {
  72663. this._absoluteTransform.copyFrom(rootMatrix);
  72664. }
  72665. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72666. for (var index = 0; index < this.children.length; index++) {
  72667. this.children[index]._updateDifferenceMatrix();
  72668. }
  72669. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72670. };
  72671. Bone.prototype.markAsDirty = function () {
  72672. this._currentRenderId++;
  72673. this._skeleton._markAsDirty();
  72674. };
  72675. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72676. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72677. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72678. // all animation may be coming from a library skeleton, so may need to create animation
  72679. if (this.animations.length === 0) {
  72680. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72681. this.animations[0].setKeys([]);
  72682. }
  72683. // get animation info / verify there is such a range from the source bone
  72684. var sourceRange = source.animations[0].getRange(rangeName);
  72685. if (!sourceRange) {
  72686. return false;
  72687. }
  72688. var from = sourceRange.from;
  72689. var to = sourceRange.to;
  72690. var sourceKeys = source.animations[0].getKeys();
  72691. // rescaling prep
  72692. var sourceBoneLength = source.length;
  72693. var sourceParent = source.getParent();
  72694. var parent = this.getParent();
  72695. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72696. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72697. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72698. var destKeys = this.animations[0].getKeys();
  72699. // loop vars declaration
  72700. var orig;
  72701. var origTranslation;
  72702. var mat;
  72703. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72704. orig = sourceKeys[key];
  72705. if (orig.frame >= from && orig.frame <= to) {
  72706. if (rescaleAsRequired) {
  72707. mat = orig.value.clone();
  72708. // scale based on parent ratio, when bone has parent
  72709. if (parentScalingReqd) {
  72710. origTranslation = mat.getTranslation();
  72711. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72712. // scale based on skeleton dimension ratio when root bone, and value is passed
  72713. }
  72714. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72715. origTranslation = mat.getTranslation();
  72716. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72717. // use original when root bone, and no data for skelDimensionsRatio
  72718. }
  72719. else {
  72720. mat = orig.value;
  72721. }
  72722. }
  72723. else {
  72724. mat = orig.value;
  72725. }
  72726. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72727. }
  72728. }
  72729. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72730. return true;
  72731. };
  72732. /**
  72733. * Translate the bone in local or world space.
  72734. * @param vec The amount to translate the bone.
  72735. * @param space The space that the translation is in.
  72736. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72737. */
  72738. Bone.prototype.translate = function (vec, space, mesh) {
  72739. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72740. var lm = this.getLocalMatrix();
  72741. if (space == BABYLON.Space.LOCAL) {
  72742. lm.m[12] += vec.x;
  72743. lm.m[13] += vec.y;
  72744. lm.m[14] += vec.z;
  72745. }
  72746. else {
  72747. var wm = null;
  72748. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72749. if (mesh) {
  72750. wm = mesh.getWorldMatrix();
  72751. }
  72752. this._skeleton.computeAbsoluteTransforms();
  72753. var tmat = Bone._tmpMats[0];
  72754. var tvec = Bone._tmpVecs[0];
  72755. if (this._parent) {
  72756. if (mesh && wm) {
  72757. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72758. tmat.multiplyToRef(wm, tmat);
  72759. }
  72760. else {
  72761. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72762. }
  72763. }
  72764. tmat.m[12] = 0;
  72765. tmat.m[13] = 0;
  72766. tmat.m[14] = 0;
  72767. tmat.invert();
  72768. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  72769. lm.m[12] += tvec.x;
  72770. lm.m[13] += tvec.y;
  72771. lm.m[14] += tvec.z;
  72772. }
  72773. this.markAsDirty();
  72774. };
  72775. /**
  72776. * Set the postion of the bone in local or world space.
  72777. * @param position The position to set the bone.
  72778. * @param space The space that the position is in.
  72779. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72780. */
  72781. Bone.prototype.setPosition = function (position, space, mesh) {
  72782. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72783. var lm = this.getLocalMatrix();
  72784. if (space == BABYLON.Space.LOCAL) {
  72785. lm.m[12] = position.x;
  72786. lm.m[13] = position.y;
  72787. lm.m[14] = position.z;
  72788. }
  72789. else {
  72790. var wm = null;
  72791. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72792. if (mesh) {
  72793. wm = mesh.getWorldMatrix();
  72794. }
  72795. this._skeleton.computeAbsoluteTransforms();
  72796. var tmat = Bone._tmpMats[0];
  72797. var vec = Bone._tmpVecs[0];
  72798. if (this._parent) {
  72799. if (mesh && wm) {
  72800. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72801. tmat.multiplyToRef(wm, tmat);
  72802. }
  72803. else {
  72804. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72805. }
  72806. }
  72807. tmat.invert();
  72808. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  72809. lm.m[12] = vec.x;
  72810. lm.m[13] = vec.y;
  72811. lm.m[14] = vec.z;
  72812. }
  72813. this.markAsDirty();
  72814. };
  72815. /**
  72816. * Set the absolute postion of the bone (world space).
  72817. * @param position The position to set the bone.
  72818. * @param mesh The mesh that this bone is attached to.
  72819. */
  72820. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  72821. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  72822. };
  72823. /**
  72824. * Set the scale of the bone on the x, y and z axes.
  72825. * @param x The scale of the bone on the x axis.
  72826. * @param x The scale of the bone on the y axis.
  72827. * @param z The scale of the bone on the z axis.
  72828. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72829. */
  72830. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  72831. if (scaleChildren === void 0) { scaleChildren = false; }
  72832. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  72833. if (!scaleChildren) {
  72834. this._negateScaleChildren.x = 1 / x;
  72835. this._negateScaleChildren.y = 1 / y;
  72836. this._negateScaleChildren.z = 1 / z;
  72837. }
  72838. this._syncScaleVector();
  72839. }
  72840. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  72841. };
  72842. /**
  72843. * Scale the bone on the x, y and z axes.
  72844. * @param x The amount to scale the bone on the x axis.
  72845. * @param x The amount to scale the bone on the y axis.
  72846. * @param z The amount to scale the bone on the z axis.
  72847. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72848. */
  72849. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  72850. if (scaleChildren === void 0) { scaleChildren = false; }
  72851. var locMat = this.getLocalMatrix();
  72852. var origLocMat = Bone._tmpMats[0];
  72853. origLocMat.copyFrom(locMat);
  72854. var origLocMatInv = Bone._tmpMats[1];
  72855. origLocMatInv.copyFrom(origLocMat);
  72856. origLocMatInv.invert();
  72857. var scaleMat = Bone._tmpMats[2];
  72858. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  72859. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  72860. this._scaleVector.x *= x;
  72861. this._scaleVector.y *= y;
  72862. this._scaleVector.z *= z;
  72863. locMat.multiplyToRef(origLocMatInv, locMat);
  72864. locMat.multiplyToRef(scaleMat, locMat);
  72865. locMat.multiplyToRef(origLocMat, locMat);
  72866. var parent = this.getParent();
  72867. if (parent) {
  72868. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  72869. }
  72870. else {
  72871. this.getAbsoluteTransform().copyFrom(locMat);
  72872. }
  72873. var len = this.children.length;
  72874. scaleMat.invert();
  72875. for (var i = 0; i < len; i++) {
  72876. var child = this.children[i];
  72877. var cm = child.getLocalMatrix();
  72878. cm.multiplyToRef(scaleMat, cm);
  72879. var lm = child.getLocalMatrix();
  72880. lm.m[12] *= x;
  72881. lm.m[13] *= y;
  72882. lm.m[14] *= z;
  72883. }
  72884. this.computeAbsoluteTransforms();
  72885. if (scaleChildren) {
  72886. for (var i = 0; i < len; i++) {
  72887. this.children[i].scale(x, y, z, scaleChildren);
  72888. }
  72889. }
  72890. this.markAsDirty();
  72891. };
  72892. /**
  72893. * Set the yaw, pitch, and roll of the bone in local or world space.
  72894. * @param yaw The rotation of the bone on the y axis.
  72895. * @param pitch The rotation of the bone on the x axis.
  72896. * @param roll The rotation of the bone on the z axis.
  72897. * @param space The space that the axes of rotation are in.
  72898. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72899. */
  72900. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  72901. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72902. var rotMat = Bone._tmpMats[0];
  72903. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  72904. var rotMatInv = Bone._tmpMats[1];
  72905. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72906. rotMatInv.multiplyToRef(rotMat, rotMat);
  72907. this._rotateWithMatrix(rotMat, space, mesh);
  72908. };
  72909. /**
  72910. * Rotate the bone on an axis in local or world space.
  72911. * @param axis The axis to rotate the bone on.
  72912. * @param amount The amount to rotate the bone.
  72913. * @param space The space that the axis is in.
  72914. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72915. */
  72916. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  72917. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72918. var rmat = Bone._tmpMats[0];
  72919. rmat.m[12] = 0;
  72920. rmat.m[13] = 0;
  72921. rmat.m[14] = 0;
  72922. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  72923. this._rotateWithMatrix(rmat, space, mesh);
  72924. };
  72925. /**
  72926. * Set the rotation of the bone to a particular axis angle in local or world space.
  72927. * @param axis The axis to rotate the bone on.
  72928. * @param angle The angle that the bone should be rotated to.
  72929. * @param space The space that the axis is in.
  72930. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72931. */
  72932. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  72933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72934. var rotMat = Bone._tmpMats[0];
  72935. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  72936. var rotMatInv = Bone._tmpMats[1];
  72937. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72938. rotMatInv.multiplyToRef(rotMat, rotMat);
  72939. this._rotateWithMatrix(rotMat, space, mesh);
  72940. };
  72941. /**
  72942. * Set the euler rotation of the bone in local of world space.
  72943. * @param rotation The euler rotation that the bone should be set to.
  72944. * @param space The space that the rotation is in.
  72945. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72946. */
  72947. Bone.prototype.setRotation = function (rotation, space, mesh) {
  72948. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72949. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  72950. };
  72951. /**
  72952. * Set the quaternion rotation of the bone in local of world space.
  72953. * @param quat The quaternion rotation that the bone should be set to.
  72954. * @param space The space that the rotation is in.
  72955. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72956. */
  72957. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  72958. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72959. var rotMatInv = Bone._tmpMats[0];
  72960. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72961. var rotMat = Bone._tmpMats[1];
  72962. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  72963. rotMatInv.multiplyToRef(rotMat, rotMat);
  72964. this._rotateWithMatrix(rotMat, space, mesh);
  72965. };
  72966. /**
  72967. * Set the rotation matrix of the bone in local of world space.
  72968. * @param rotMat The rotation matrix that the bone should be set to.
  72969. * @param space The space that the rotation is in.
  72970. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72971. */
  72972. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  72973. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72974. var rotMatInv = Bone._tmpMats[0];
  72975. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72976. var rotMat2 = Bone._tmpMats[1];
  72977. rotMat2.copyFrom(rotMat);
  72978. rotMatInv.multiplyToRef(rotMat, rotMat2);
  72979. this._rotateWithMatrix(rotMat2, space, mesh);
  72980. };
  72981. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  72982. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72983. var lmat = this.getLocalMatrix();
  72984. var lx = lmat.m[12];
  72985. var ly = lmat.m[13];
  72986. var lz = lmat.m[14];
  72987. var parent = this.getParent();
  72988. var parentScale = Bone._tmpMats[3];
  72989. var parentScaleInv = Bone._tmpMats[4];
  72990. if (parent) {
  72991. if (space == BABYLON.Space.WORLD) {
  72992. if (mesh) {
  72993. parentScale.copyFrom(mesh.getWorldMatrix());
  72994. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  72995. }
  72996. else {
  72997. parentScale.copyFrom(parent.getAbsoluteTransform());
  72998. }
  72999. }
  73000. else {
  73001. parentScale = parent._scaleMatrix;
  73002. }
  73003. parentScaleInv.copyFrom(parentScale);
  73004. parentScaleInv.invert();
  73005. lmat.multiplyToRef(parentScale, lmat);
  73006. lmat.multiplyToRef(rmat, lmat);
  73007. lmat.multiplyToRef(parentScaleInv, lmat);
  73008. }
  73009. else {
  73010. if (space == BABYLON.Space.WORLD && mesh) {
  73011. parentScale.copyFrom(mesh.getWorldMatrix());
  73012. parentScaleInv.copyFrom(parentScale);
  73013. parentScaleInv.invert();
  73014. lmat.multiplyToRef(parentScale, lmat);
  73015. lmat.multiplyToRef(rmat, lmat);
  73016. lmat.multiplyToRef(parentScaleInv, lmat);
  73017. }
  73018. else {
  73019. lmat.multiplyToRef(rmat, lmat);
  73020. }
  73021. }
  73022. lmat.m[12] = lx;
  73023. lmat.m[13] = ly;
  73024. lmat.m[14] = lz;
  73025. this.computeAbsoluteTransforms();
  73026. this.markAsDirty();
  73027. };
  73028. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  73029. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73030. if (space == BABYLON.Space.WORLD) {
  73031. var scaleMatrix = Bone._tmpMats[2];
  73032. scaleMatrix.copyFrom(this._scaleMatrix);
  73033. rotMatInv.copyFrom(this.getAbsoluteTransform());
  73034. if (mesh) {
  73035. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  73036. var meshScale = Bone._tmpMats[3];
  73037. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  73038. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  73039. }
  73040. rotMatInv.invert();
  73041. scaleMatrix.m[0] *= this._scalingDeterminant;
  73042. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73043. }
  73044. else {
  73045. rotMatInv.copyFrom(this.getLocalMatrix());
  73046. rotMatInv.invert();
  73047. var scaleMatrix = Bone._tmpMats[2];
  73048. scaleMatrix.copyFrom(this._scaleMatrix);
  73049. if (this._parent) {
  73050. var pscaleMatrix = Bone._tmpMats[3];
  73051. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  73052. pscaleMatrix.invert();
  73053. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  73054. }
  73055. else {
  73056. scaleMatrix.m[0] *= this._scalingDeterminant;
  73057. }
  73058. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73059. }
  73060. };
  73061. /**
  73062. * Get the scale of the bone
  73063. * @returns the scale of the bone
  73064. */
  73065. Bone.prototype.getScale = function () {
  73066. return this._scaleVector.clone();
  73067. };
  73068. /**
  73069. * Copy the scale of the bone to a vector3.
  73070. * @param result The vector3 to copy the scale to
  73071. */
  73072. Bone.prototype.getScaleToRef = function (result) {
  73073. result.copyFrom(this._scaleVector);
  73074. };
  73075. /**
  73076. * Get the position of the bone in local or world space.
  73077. * @param space The space that the returned position is in.
  73078. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73079. * @returns The position of the bone
  73080. */
  73081. Bone.prototype.getPosition = function (space, mesh) {
  73082. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73083. if (mesh === void 0) { mesh = null; }
  73084. var pos = BABYLON.Vector3.Zero();
  73085. this.getPositionToRef(space, mesh, pos);
  73086. return pos;
  73087. };
  73088. /**
  73089. * Copy the position of the bone to a vector3 in local or world space.
  73090. * @param space The space that the returned position is in.
  73091. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73092. * @param result The vector3 to copy the position to.
  73093. */
  73094. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  73095. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73096. if (space == BABYLON.Space.LOCAL) {
  73097. var lm = this.getLocalMatrix();
  73098. result.x = lm.m[12];
  73099. result.y = lm.m[13];
  73100. result.z = lm.m[14];
  73101. }
  73102. else {
  73103. var wm = null;
  73104. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73105. if (mesh) {
  73106. wm = mesh.getWorldMatrix();
  73107. }
  73108. this._skeleton.computeAbsoluteTransforms();
  73109. var tmat = Bone._tmpMats[0];
  73110. if (mesh && wm) {
  73111. tmat.copyFrom(this.getAbsoluteTransform());
  73112. tmat.multiplyToRef(wm, tmat);
  73113. }
  73114. else {
  73115. tmat = this.getAbsoluteTransform();
  73116. }
  73117. result.x = tmat.m[12];
  73118. result.y = tmat.m[13];
  73119. result.z = tmat.m[14];
  73120. }
  73121. };
  73122. /**
  73123. * Get the absolute position of the bone (world space).
  73124. * @param mesh The mesh that this bone is attached to.
  73125. * @returns The absolute position of the bone
  73126. */
  73127. Bone.prototype.getAbsolutePosition = function (mesh) {
  73128. if (mesh === void 0) { mesh = null; }
  73129. var pos = BABYLON.Vector3.Zero();
  73130. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  73131. return pos;
  73132. };
  73133. /**
  73134. * Copy the absolute position of the bone (world space) to the result param.
  73135. * @param mesh The mesh that this bone is attached to.
  73136. * @param result The vector3 to copy the absolute position to.
  73137. */
  73138. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  73139. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  73140. };
  73141. /**
  73142. * Compute the absolute transforms of this bone and its children.
  73143. */
  73144. Bone.prototype.computeAbsoluteTransforms = function () {
  73145. if (this._parent) {
  73146. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  73147. }
  73148. else {
  73149. this._absoluteTransform.copyFrom(this._localMatrix);
  73150. var poseMatrix = this._skeleton.getPoseMatrix();
  73151. if (poseMatrix) {
  73152. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  73153. }
  73154. }
  73155. var children = this.children;
  73156. var len = children.length;
  73157. for (var i = 0; i < len; i++) {
  73158. children[i].computeAbsoluteTransforms();
  73159. }
  73160. };
  73161. Bone.prototype._syncScaleVector = function () {
  73162. var lm = this.getLocalMatrix();
  73163. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  73164. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  73165. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  73166. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  73167. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  73168. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  73169. this._scaleVector.x = xs * Math.sqrt(xsq);
  73170. this._scaleVector.y = ys * Math.sqrt(ysq);
  73171. this._scaleVector.z = zs * Math.sqrt(zsq);
  73172. if (this._parent) {
  73173. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  73174. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  73175. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  73176. }
  73177. 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);
  73178. };
  73179. /**
  73180. * Get the world direction from an axis that is in the local space of the bone.
  73181. * @param localAxis The local direction that is used to compute the world direction.
  73182. * @param mesh The mesh that this bone is attached to.
  73183. * @returns The world direction
  73184. */
  73185. Bone.prototype.getDirection = function (localAxis, mesh) {
  73186. if (mesh === void 0) { mesh = null; }
  73187. var result = BABYLON.Vector3.Zero();
  73188. this.getDirectionToRef(localAxis, mesh, result);
  73189. return result;
  73190. };
  73191. /**
  73192. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  73193. * @param localAxis The local direction that is used to compute the world direction.
  73194. * @param mesh The mesh that this bone is attached to.
  73195. * @param result The vector3 that the world direction will be copied to.
  73196. */
  73197. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  73198. if (mesh === void 0) { mesh = null; }
  73199. var wm = null;
  73200. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73201. if (mesh) {
  73202. wm = mesh.getWorldMatrix();
  73203. }
  73204. this._skeleton.computeAbsoluteTransforms();
  73205. var mat = Bone._tmpMats[0];
  73206. mat.copyFrom(this.getAbsoluteTransform());
  73207. if (mesh && wm) {
  73208. mat.multiplyToRef(wm, mat);
  73209. }
  73210. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  73211. result.normalize();
  73212. };
  73213. /**
  73214. * Get the euler rotation of the bone in local or world space.
  73215. * @param space The space that the rotation should be in.
  73216. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73217. * @returns The euler rotation
  73218. */
  73219. Bone.prototype.getRotation = function (space, mesh) {
  73220. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73221. if (mesh === void 0) { mesh = null; }
  73222. var result = BABYLON.Vector3.Zero();
  73223. this.getRotationToRef(space, mesh, result);
  73224. return result;
  73225. };
  73226. /**
  73227. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  73228. * @param space The space that the rotation should be in.
  73229. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73230. * @param result The vector3 that the rotation should be copied to.
  73231. */
  73232. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  73233. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73234. if (mesh === void 0) { mesh = null; }
  73235. var quat = Bone._tmpQuat;
  73236. this.getRotationQuaternionToRef(space, mesh, quat);
  73237. quat.toEulerAnglesToRef(result);
  73238. };
  73239. /**
  73240. * Get the quaternion rotation of the bone in either local or world space.
  73241. * @param space The space that the rotation should be in.
  73242. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73243. * @returns The quaternion rotation
  73244. */
  73245. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  73246. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73247. if (mesh === void 0) { mesh = null; }
  73248. var result = BABYLON.Quaternion.Identity();
  73249. this.getRotationQuaternionToRef(space, mesh, result);
  73250. return result;
  73251. };
  73252. /**
  73253. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  73254. * @param space The space that the rotation should be in.
  73255. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73256. * @param result The quaternion that the rotation should be copied to.
  73257. */
  73258. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  73259. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73260. if (mesh === void 0) { mesh = null; }
  73261. if (space == BABYLON.Space.LOCAL) {
  73262. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73263. }
  73264. else {
  73265. var mat = Bone._tmpMats[0];
  73266. var amat = this.getAbsoluteTransform();
  73267. if (mesh) {
  73268. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73269. }
  73270. else {
  73271. mat.copyFrom(amat);
  73272. }
  73273. mat.m[0] *= this._scalingDeterminant;
  73274. mat.m[1] *= this._scalingDeterminant;
  73275. mat.m[2] *= this._scalingDeterminant;
  73276. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73277. }
  73278. };
  73279. /**
  73280. * Get the rotation matrix of the bone in local or world space.
  73281. * @param space The space that the rotation should be in.
  73282. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73283. * @returns The rotation matrix
  73284. */
  73285. Bone.prototype.getRotationMatrix = function (space, mesh) {
  73286. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73287. var result = BABYLON.Matrix.Identity();
  73288. this.getRotationMatrixToRef(space, mesh, result);
  73289. return result;
  73290. };
  73291. /**
  73292. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  73293. * @param space The space that the rotation should be in.
  73294. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73295. * @param result The quaternion that the rotation should be copied to.
  73296. */
  73297. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  73298. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73299. if (space == BABYLON.Space.LOCAL) {
  73300. this.getLocalMatrix().getRotationMatrixToRef(result);
  73301. }
  73302. else {
  73303. var mat = Bone._tmpMats[0];
  73304. var amat = this.getAbsoluteTransform();
  73305. if (mesh) {
  73306. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73307. }
  73308. else {
  73309. mat.copyFrom(amat);
  73310. }
  73311. mat.m[0] *= this._scalingDeterminant;
  73312. mat.m[1] *= this._scalingDeterminant;
  73313. mat.m[2] *= this._scalingDeterminant;
  73314. mat.getRotationMatrixToRef(result);
  73315. }
  73316. };
  73317. /**
  73318. * Get the world position of a point that is in the local space of the bone.
  73319. * @param position The local position
  73320. * @param mesh The mesh that this bone is attached to.
  73321. * @returns The world position
  73322. */
  73323. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  73324. if (mesh === void 0) { mesh = null; }
  73325. var result = BABYLON.Vector3.Zero();
  73326. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  73327. return result;
  73328. };
  73329. /**
  73330. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  73331. * @param position The local position
  73332. * @param mesh The mesh that this bone is attached to.
  73333. * @param result The vector3 that the world position should be copied to.
  73334. */
  73335. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  73336. if (mesh === void 0) { mesh = null; }
  73337. var wm = null;
  73338. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73339. if (mesh) {
  73340. wm = mesh.getWorldMatrix();
  73341. }
  73342. this._skeleton.computeAbsoluteTransforms();
  73343. var tmat = Bone._tmpMats[0];
  73344. if (mesh && wm) {
  73345. tmat.copyFrom(this.getAbsoluteTransform());
  73346. tmat.multiplyToRef(wm, tmat);
  73347. }
  73348. else {
  73349. tmat = this.getAbsoluteTransform();
  73350. }
  73351. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73352. };
  73353. /**
  73354. * Get the local position of a point that is in world space.
  73355. * @param position The world position
  73356. * @param mesh The mesh that this bone is attached to.
  73357. * @returns The local position
  73358. */
  73359. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  73360. if (mesh === void 0) { mesh = null; }
  73361. var result = BABYLON.Vector3.Zero();
  73362. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  73363. return result;
  73364. };
  73365. /**
  73366. * Get the local position of a point that is in world space and copy it to the result param.
  73367. * @param position The world position
  73368. * @param mesh The mesh that this bone is attached to.
  73369. * @param result The vector3 that the local position should be copied to.
  73370. */
  73371. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  73372. if (mesh === void 0) { mesh = null; }
  73373. var wm = null;
  73374. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73375. if (mesh) {
  73376. wm = mesh.getWorldMatrix();
  73377. }
  73378. this._skeleton.computeAbsoluteTransforms();
  73379. var tmat = Bone._tmpMats[0];
  73380. tmat.copyFrom(this.getAbsoluteTransform());
  73381. if (mesh && wm) {
  73382. tmat.multiplyToRef(wm, tmat);
  73383. }
  73384. tmat.invert();
  73385. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73386. };
  73387. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73388. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  73389. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73390. return Bone;
  73391. }(BABYLON.Node));
  73392. BABYLON.Bone = Bone;
  73393. })(BABYLON || (BABYLON = {}));
  73394. //# sourceMappingURL=babylon.bone.js.map
  73395. "use strict";
  73396. var BABYLON;
  73397. (function (BABYLON) {
  73398. var BoneIKController = /** @class */ (function () {
  73399. function BoneIKController(mesh, bone, options) {
  73400. this.targetPosition = BABYLON.Vector3.Zero();
  73401. this.poleTargetPosition = BABYLON.Vector3.Zero();
  73402. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  73403. this.poleAngle = 0;
  73404. this.slerpAmount = 1;
  73405. this._bone1Quat = BABYLON.Quaternion.Identity();
  73406. this._bone1Mat = BABYLON.Matrix.Identity();
  73407. this._bone2Ang = Math.PI;
  73408. this._maxAngle = Math.PI;
  73409. this._rightHandedSystem = false;
  73410. this._bendAxis = BABYLON.Vector3.Right();
  73411. this._slerping = false;
  73412. this._adjustRoll = 0;
  73413. this._bone2 = bone;
  73414. this._bone1 = bone.getParent();
  73415. if (!this._bone1) {
  73416. return;
  73417. }
  73418. this.mesh = mesh;
  73419. var bonePos = bone.getPosition();
  73420. if (bone.getAbsoluteTransform().determinant() > 0) {
  73421. this._rightHandedSystem = true;
  73422. this._bendAxis.x = 0;
  73423. this._bendAxis.y = 0;
  73424. this._bendAxis.z = -1;
  73425. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  73426. this._adjustRoll = Math.PI * .5;
  73427. this._bendAxis.z = 1;
  73428. }
  73429. }
  73430. if (this._bone1.length) {
  73431. var boneScale1 = this._bone1.getScale();
  73432. var boneScale2 = this._bone2.getScale();
  73433. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  73434. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  73435. }
  73436. else if (this._bone1.children[0]) {
  73437. mesh.computeWorldMatrix(true);
  73438. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  73439. var pos2 = this._bone2.getAbsolutePosition(mesh);
  73440. var pos3 = this._bone1.getAbsolutePosition(mesh);
  73441. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  73442. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  73443. }
  73444. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  73445. this.maxAngle = Math.PI;
  73446. if (options) {
  73447. if (options.targetMesh) {
  73448. this.targetMesh = options.targetMesh;
  73449. this.targetMesh.computeWorldMatrix(true);
  73450. }
  73451. if (options.poleTargetMesh) {
  73452. this.poleTargetMesh = options.poleTargetMesh;
  73453. this.poleTargetMesh.computeWorldMatrix(true);
  73454. }
  73455. else if (options.poleTargetBone) {
  73456. this.poleTargetBone = options.poleTargetBone;
  73457. }
  73458. else if (this._bone1.getParent()) {
  73459. this.poleTargetBone = this._bone1.getParent();
  73460. }
  73461. if (options.poleTargetLocalOffset) {
  73462. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  73463. }
  73464. if (options.poleAngle) {
  73465. this.poleAngle = options.poleAngle;
  73466. }
  73467. if (options.bendAxis) {
  73468. this._bendAxis.copyFrom(options.bendAxis);
  73469. }
  73470. if (options.maxAngle) {
  73471. this.maxAngle = options.maxAngle;
  73472. }
  73473. if (options.slerpAmount) {
  73474. this.slerpAmount = options.slerpAmount;
  73475. }
  73476. }
  73477. }
  73478. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  73479. get: function () {
  73480. return this._maxAngle;
  73481. },
  73482. set: function (value) {
  73483. this._setMaxAngle(value);
  73484. },
  73485. enumerable: true,
  73486. configurable: true
  73487. });
  73488. BoneIKController.prototype._setMaxAngle = function (ang) {
  73489. if (ang < 0) {
  73490. ang = 0;
  73491. }
  73492. if (ang > Math.PI || ang == undefined) {
  73493. ang = Math.PI;
  73494. }
  73495. this._maxAngle = ang;
  73496. var a = this._bone1Length;
  73497. var b = this._bone2Length;
  73498. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  73499. };
  73500. BoneIKController.prototype.update = function () {
  73501. var bone1 = this._bone1;
  73502. if (!bone1) {
  73503. return;
  73504. }
  73505. var target = this.targetPosition;
  73506. var poleTarget = this.poleTargetPosition;
  73507. var mat1 = BoneIKController._tmpMats[0];
  73508. var mat2 = BoneIKController._tmpMats[1];
  73509. if (this.targetMesh) {
  73510. target.copyFrom(this.targetMesh.getAbsolutePosition());
  73511. }
  73512. if (this.poleTargetBone) {
  73513. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  73514. }
  73515. else if (this.poleTargetMesh) {
  73516. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  73517. }
  73518. var bonePos = BoneIKController._tmpVecs[0];
  73519. var zaxis = BoneIKController._tmpVecs[1];
  73520. var xaxis = BoneIKController._tmpVecs[2];
  73521. var yaxis = BoneIKController._tmpVecs[3];
  73522. var upAxis = BoneIKController._tmpVecs[4];
  73523. var _tmpQuat = BoneIKController._tmpQuat;
  73524. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  73525. poleTarget.subtractToRef(bonePos, upAxis);
  73526. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  73527. upAxis.y = 1;
  73528. }
  73529. else {
  73530. upAxis.normalize();
  73531. }
  73532. target.subtractToRef(bonePos, yaxis);
  73533. yaxis.normalize();
  73534. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  73535. zaxis.normalize();
  73536. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  73537. xaxis.normalize();
  73538. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  73539. var a = this._bone1Length;
  73540. var b = this._bone2Length;
  73541. var c = BABYLON.Vector3.Distance(bonePos, target);
  73542. if (this._maxReach > 0) {
  73543. c = Math.min(this._maxReach, c);
  73544. }
  73545. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  73546. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  73547. if (acosa > 1) {
  73548. acosa = 1;
  73549. }
  73550. if (acosb > 1) {
  73551. acosb = 1;
  73552. }
  73553. if (acosa < -1) {
  73554. acosa = -1;
  73555. }
  73556. if (acosb < -1) {
  73557. acosb = -1;
  73558. }
  73559. var angA = Math.acos(acosa);
  73560. var angB = Math.acos(acosb);
  73561. var angC = -angA - angB;
  73562. if (this._rightHandedSystem) {
  73563. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  73564. mat2.multiplyToRef(mat1, mat1);
  73565. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73566. mat2.multiplyToRef(mat1, mat1);
  73567. }
  73568. else {
  73569. var _tmpVec = BoneIKController._tmpVecs[5];
  73570. _tmpVec.copyFrom(this._bendAxis);
  73571. _tmpVec.x *= -1;
  73572. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73573. mat2.multiplyToRef(mat1, mat1);
  73574. }
  73575. if (this.poleAngle) {
  73576. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73577. mat1.multiplyToRef(mat2, mat1);
  73578. }
  73579. if (this._bone1) {
  73580. if (this.slerpAmount < 1) {
  73581. if (!this._slerping) {
  73582. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73583. }
  73584. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73585. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73586. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73587. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73588. this._slerping = true;
  73589. }
  73590. else {
  73591. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73592. this._bone1Mat.copyFrom(mat1);
  73593. this._slerping = false;
  73594. }
  73595. }
  73596. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73597. this._bone2Ang = angC;
  73598. };
  73599. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73600. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73601. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73602. return BoneIKController;
  73603. }());
  73604. BABYLON.BoneIKController = BoneIKController;
  73605. })(BABYLON || (BABYLON = {}));
  73606. //# sourceMappingURL=babylon.boneIKController.js.map
  73607. "use strict";
  73608. var BABYLON;
  73609. (function (BABYLON) {
  73610. var BoneLookController = /** @class */ (function () {
  73611. /**
  73612. * Create a BoneLookController
  73613. * @param mesh the mesh that the bone belongs to
  73614. * @param bone the bone that will be looking to the target
  73615. * @param target the target Vector3 to look at
  73616. * @param settings optional settings:
  73617. * - maxYaw: the maximum angle the bone will yaw to
  73618. * - minYaw: the minimum angle the bone will yaw to
  73619. * - maxPitch: the maximum angle the bone will pitch to
  73620. * - minPitch: the minimum angle the bone will yaw to
  73621. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73622. * - upAxis: the up axis of the coordinate system
  73623. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73624. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73625. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73626. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73627. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73628. * - adjustRoll: used to make an adjustment to the roll of the bone
  73629. **/
  73630. function BoneLookController(mesh, bone, target, options) {
  73631. /**
  73632. * The up axis of the coordinate system that is used when the bone is rotated.
  73633. */
  73634. this.upAxis = BABYLON.Vector3.Up();
  73635. /**
  73636. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73637. */
  73638. this.upAxisSpace = BABYLON.Space.LOCAL;
  73639. /**
  73640. * Used to make an adjustment to the yaw of the bone.
  73641. */
  73642. this.adjustYaw = 0;
  73643. /**
  73644. * Used to make an adjustment to the pitch of the bone.
  73645. */
  73646. this.adjustPitch = 0;
  73647. /**
  73648. * Used to make an adjustment to the roll of the bone.
  73649. */
  73650. this.adjustRoll = 0;
  73651. /**
  73652. * 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).
  73653. */
  73654. this.slerpAmount = 1;
  73655. this._boneQuat = BABYLON.Quaternion.Identity();
  73656. this._slerping = false;
  73657. this._firstFrameSkipped = false;
  73658. this._fowardAxis = BABYLON.Vector3.Forward();
  73659. this.mesh = mesh;
  73660. this.bone = bone;
  73661. this.target = target;
  73662. if (options) {
  73663. if (options.adjustYaw) {
  73664. this.adjustYaw = options.adjustYaw;
  73665. }
  73666. if (options.adjustPitch) {
  73667. this.adjustPitch = options.adjustPitch;
  73668. }
  73669. if (options.adjustRoll) {
  73670. this.adjustRoll = options.adjustRoll;
  73671. }
  73672. if (options.maxYaw != null) {
  73673. this.maxYaw = options.maxYaw;
  73674. }
  73675. else {
  73676. this.maxYaw = Math.PI;
  73677. }
  73678. if (options.minYaw != null) {
  73679. this.minYaw = options.minYaw;
  73680. }
  73681. else {
  73682. this.minYaw = -Math.PI;
  73683. }
  73684. if (options.maxPitch != null) {
  73685. this.maxPitch = options.maxPitch;
  73686. }
  73687. else {
  73688. this.maxPitch = Math.PI;
  73689. }
  73690. if (options.minPitch != null) {
  73691. this.minPitch = options.minPitch;
  73692. }
  73693. else {
  73694. this.minPitch = -Math.PI;
  73695. }
  73696. if (options.slerpAmount != null) {
  73697. this.slerpAmount = options.slerpAmount;
  73698. }
  73699. if (options.upAxis != null) {
  73700. this.upAxis = options.upAxis;
  73701. }
  73702. if (options.upAxisSpace != null) {
  73703. this.upAxisSpace = options.upAxisSpace;
  73704. }
  73705. if (options.yawAxis != null || options.pitchAxis != null) {
  73706. var newYawAxis = BABYLON.Axis.Y;
  73707. var newPitchAxis = BABYLON.Axis.X;
  73708. if (options.yawAxis != null) {
  73709. newYawAxis = options.yawAxis.clone();
  73710. newYawAxis.normalize();
  73711. }
  73712. if (options.pitchAxis != null) {
  73713. newPitchAxis = options.pitchAxis.clone();
  73714. newPitchAxis.normalize();
  73715. }
  73716. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73717. this._transformYawPitch = BABYLON.Matrix.Identity();
  73718. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73719. this._transformYawPitchInv = this._transformYawPitch.clone();
  73720. this._transformYawPitch.invert();
  73721. }
  73722. }
  73723. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73724. this.upAxisSpace = BABYLON.Space.LOCAL;
  73725. }
  73726. }
  73727. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73728. /**
  73729. * Get/set the minimum yaw angle that the bone can look to.
  73730. */
  73731. get: function () {
  73732. return this._minYaw;
  73733. },
  73734. set: function (value) {
  73735. this._minYaw = value;
  73736. this._minYawSin = Math.sin(value);
  73737. this._minYawCos = Math.cos(value);
  73738. if (this._maxYaw != null) {
  73739. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73740. this._yawRange = this._maxYaw - this._minYaw;
  73741. }
  73742. },
  73743. enumerable: true,
  73744. configurable: true
  73745. });
  73746. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73747. /**
  73748. * Get/set the maximum yaw angle that the bone can look to.
  73749. */
  73750. get: function () {
  73751. return this._maxYaw;
  73752. },
  73753. set: function (value) {
  73754. this._maxYaw = value;
  73755. this._maxYawSin = Math.sin(value);
  73756. this._maxYawCos = Math.cos(value);
  73757. if (this._minYaw != null) {
  73758. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73759. this._yawRange = this._maxYaw - this._minYaw;
  73760. }
  73761. },
  73762. enumerable: true,
  73763. configurable: true
  73764. });
  73765. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  73766. /**
  73767. * Get/set the minimum pitch angle that the bone can look to.
  73768. */
  73769. get: function () {
  73770. return this._minPitch;
  73771. },
  73772. set: function (value) {
  73773. this._minPitch = value;
  73774. this._minPitchTan = Math.tan(value);
  73775. },
  73776. enumerable: true,
  73777. configurable: true
  73778. });
  73779. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  73780. /**
  73781. * Get/set the maximum pitch angle that the bone can look to.
  73782. */
  73783. get: function () {
  73784. return this._maxPitch;
  73785. },
  73786. set: function (value) {
  73787. this._maxPitch = value;
  73788. this._maxPitchTan = Math.tan(value);
  73789. },
  73790. enumerable: true,
  73791. configurable: true
  73792. });
  73793. /**
  73794. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  73795. */
  73796. BoneLookController.prototype.update = function () {
  73797. //skip the first frame when slerping so that the mesh rotation is correct
  73798. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  73799. this._firstFrameSkipped = true;
  73800. return;
  73801. }
  73802. var bone = this.bone;
  73803. var bonePos = BoneLookController._tmpVecs[0];
  73804. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  73805. var target = this.target;
  73806. var _tmpMat1 = BoneLookController._tmpMats[0];
  73807. var _tmpMat2 = BoneLookController._tmpMats[1];
  73808. var mesh = this.mesh;
  73809. var parentBone = bone.getParent();
  73810. var upAxis = BoneLookController._tmpVecs[1];
  73811. upAxis.copyFrom(this.upAxis);
  73812. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  73813. if (this._transformYawPitch) {
  73814. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  73815. }
  73816. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  73817. }
  73818. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  73819. mesh.getDirectionToRef(upAxis, upAxis);
  73820. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  73821. upAxis.normalize();
  73822. }
  73823. }
  73824. var checkYaw = false;
  73825. var checkPitch = false;
  73826. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  73827. checkYaw = true;
  73828. }
  73829. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  73830. checkPitch = true;
  73831. }
  73832. if (checkYaw || checkPitch) {
  73833. var spaceMat = BoneLookController._tmpMats[2];
  73834. var spaceMatInv = BoneLookController._tmpMats[3];
  73835. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  73836. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  73837. }
  73838. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  73839. spaceMat.copyFrom(mesh.getWorldMatrix());
  73840. }
  73841. else {
  73842. var forwardAxis = BoneLookController._tmpVecs[2];
  73843. forwardAxis.copyFrom(this._fowardAxis);
  73844. if (this._transformYawPitch) {
  73845. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  73846. }
  73847. if (parentBone) {
  73848. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  73849. }
  73850. else {
  73851. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  73852. }
  73853. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  73854. rightAxis.normalize();
  73855. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  73856. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  73857. }
  73858. spaceMat.invertToRef(spaceMatInv);
  73859. var xzlen = null;
  73860. if (checkPitch) {
  73861. var localTarget = BoneLookController._tmpVecs[3];
  73862. target.subtractToRef(bonePos, localTarget);
  73863. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73864. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73865. var pitch = Math.atan2(localTarget.y, xzlen);
  73866. var newPitch = pitch;
  73867. if (pitch > this._maxPitch) {
  73868. localTarget.y = this._maxPitchTan * xzlen;
  73869. newPitch = this._maxPitch;
  73870. }
  73871. else if (pitch < this._minPitch) {
  73872. localTarget.y = this._minPitchTan * xzlen;
  73873. newPitch = this._minPitch;
  73874. }
  73875. if (pitch != newPitch) {
  73876. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73877. localTarget.addInPlace(bonePos);
  73878. target = localTarget;
  73879. }
  73880. }
  73881. if (checkYaw) {
  73882. var localTarget = BoneLookController._tmpVecs[4];
  73883. target.subtractToRef(bonePos, localTarget);
  73884. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73885. var yaw = Math.atan2(localTarget.x, localTarget.z);
  73886. var newYaw = yaw;
  73887. if (yaw > this._maxYaw || yaw < this._minYaw) {
  73888. if (xzlen == null) {
  73889. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73890. }
  73891. if (this._yawRange > Math.PI) {
  73892. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  73893. localTarget.z = this._maxYawCos * xzlen;
  73894. localTarget.x = this._maxYawSin * xzlen;
  73895. newYaw = this._maxYaw;
  73896. }
  73897. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  73898. localTarget.z = this._minYawCos * xzlen;
  73899. localTarget.x = this._minYawSin * xzlen;
  73900. newYaw = this._minYaw;
  73901. }
  73902. }
  73903. else {
  73904. if (yaw > this._maxYaw) {
  73905. localTarget.z = this._maxYawCos * xzlen;
  73906. localTarget.x = this._maxYawSin * xzlen;
  73907. newYaw = this._maxYaw;
  73908. }
  73909. else if (yaw < this._minYaw) {
  73910. localTarget.z = this._minYawCos * xzlen;
  73911. localTarget.x = this._minYawSin * xzlen;
  73912. newYaw = this._minYaw;
  73913. }
  73914. }
  73915. }
  73916. if (this._slerping && this._yawRange > Math.PI) {
  73917. //are we going to be crossing into the min/max region?
  73918. var boneFwd = BoneLookController._tmpVecs[8];
  73919. boneFwd.copyFrom(BABYLON.Axis.Z);
  73920. if (this._transformYawPitch) {
  73921. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  73922. }
  73923. var boneRotMat = BoneLookController._tmpMats[4];
  73924. this._boneQuat.toRotationMatrix(boneRotMat);
  73925. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  73926. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  73927. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  73928. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  73929. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  73930. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  73931. if (angBtwTar > angBtwMidYaw) {
  73932. if (xzlen == null) {
  73933. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73934. }
  73935. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  73936. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  73937. if (angBtwMin < angBtwMax) {
  73938. newYaw = boneYaw + Math.PI * .75;
  73939. localTarget.z = Math.cos(newYaw) * xzlen;
  73940. localTarget.x = Math.sin(newYaw) * xzlen;
  73941. }
  73942. else {
  73943. newYaw = boneYaw - Math.PI * .75;
  73944. localTarget.z = Math.cos(newYaw) * xzlen;
  73945. localTarget.x = Math.sin(newYaw) * xzlen;
  73946. }
  73947. }
  73948. }
  73949. if (yaw != newYaw) {
  73950. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73951. localTarget.addInPlace(bonePos);
  73952. target = localTarget;
  73953. }
  73954. }
  73955. }
  73956. var zaxis = BoneLookController._tmpVecs[5];
  73957. var xaxis = BoneLookController._tmpVecs[6];
  73958. var yaxis = BoneLookController._tmpVecs[7];
  73959. var _tmpQuat = BoneLookController._tmpQuat;
  73960. target.subtractToRef(bonePos, zaxis);
  73961. zaxis.normalize();
  73962. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  73963. xaxis.normalize();
  73964. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  73965. yaxis.normalize();
  73966. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  73967. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  73968. return;
  73969. }
  73970. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  73971. return;
  73972. }
  73973. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  73974. return;
  73975. }
  73976. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  73977. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  73978. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  73979. }
  73980. if (this.slerpAmount < 1) {
  73981. if (!this._slerping) {
  73982. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  73983. }
  73984. if (this._transformYawPitch) {
  73985. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73986. }
  73987. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  73988. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  73989. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  73990. this._slerping = true;
  73991. }
  73992. else {
  73993. if (this._transformYawPitch) {
  73994. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73995. }
  73996. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  73997. this._slerping = false;
  73998. }
  73999. };
  74000. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  74001. var angDiff = ang2 - ang1;
  74002. angDiff %= Math.PI * 2;
  74003. if (angDiff > Math.PI) {
  74004. angDiff -= Math.PI * 2;
  74005. }
  74006. else if (angDiff < -Math.PI) {
  74007. angDiff += Math.PI * 2;
  74008. }
  74009. return angDiff;
  74010. };
  74011. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  74012. ang1 %= (2 * Math.PI);
  74013. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74014. ang2 %= (2 * Math.PI);
  74015. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74016. var ab = 0;
  74017. if (ang1 < ang2) {
  74018. ab = ang2 - ang1;
  74019. }
  74020. else {
  74021. ab = ang1 - ang2;
  74022. }
  74023. if (ab > Math.PI) {
  74024. ab = Math.PI * 2 - ab;
  74025. }
  74026. return ab;
  74027. };
  74028. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  74029. ang %= (2 * Math.PI);
  74030. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  74031. ang1 %= (2 * Math.PI);
  74032. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74033. ang2 %= (2 * Math.PI);
  74034. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74035. if (ang1 < ang2) {
  74036. if (ang > ang1 && ang < ang2) {
  74037. return true;
  74038. }
  74039. }
  74040. else {
  74041. if (ang > ang2 && ang < ang1) {
  74042. return true;
  74043. }
  74044. }
  74045. return false;
  74046. };
  74047. 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()];
  74048. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  74049. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  74050. return BoneLookController;
  74051. }());
  74052. BABYLON.BoneLookController = BoneLookController;
  74053. })(BABYLON || (BABYLON = {}));
  74054. //# sourceMappingURL=babylon.boneLookController.js.map
  74055. "use strict";
  74056. var BABYLON;
  74057. (function (BABYLON) {
  74058. var Skeleton = /** @class */ (function () {
  74059. function Skeleton(name, id, scene) {
  74060. this.name = name;
  74061. this.id = id;
  74062. this.bones = new Array();
  74063. this.needInitialSkinMatrix = false;
  74064. this._isDirty = true;
  74065. this._meshesWithPoseMatrix = new Array();
  74066. this._identity = BABYLON.Matrix.Identity();
  74067. this._ranges = {};
  74068. this._lastAbsoluteTransformsUpdateId = -1;
  74069. /**
  74070. * Specifies if the skeleton should be serialized.
  74071. */
  74072. this.doNotSerialize = false;
  74073. // Events
  74074. /**
  74075. * An event triggered before computing the skeleton's matrices
  74076. * @type {BABYLON.Observable}
  74077. */
  74078. this.onBeforeComputeObservable = new BABYLON.Observable();
  74079. this.bones = [];
  74080. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74081. scene.skeletons.push(this);
  74082. //make sure it will recalculate the matrix next time prepare is called.
  74083. this._isDirty = true;
  74084. }
  74085. // Members
  74086. Skeleton.prototype.getTransformMatrices = function (mesh) {
  74087. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  74088. return mesh._bonesTransformMatrices;
  74089. }
  74090. if (!this._transformMatrices) {
  74091. this.prepare();
  74092. }
  74093. return this._transformMatrices;
  74094. };
  74095. Skeleton.prototype.getScene = function () {
  74096. return this._scene;
  74097. };
  74098. // Methods
  74099. /**
  74100. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  74101. */
  74102. Skeleton.prototype.toString = function (fullDetails) {
  74103. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  74104. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  74105. if (fullDetails) {
  74106. ret += ", Ranges: {";
  74107. var first = true;
  74108. for (var name_1 in this._ranges) {
  74109. if (first) {
  74110. ret += ", ";
  74111. first = false;
  74112. }
  74113. ret += name_1;
  74114. }
  74115. ret += "}";
  74116. }
  74117. return ret;
  74118. };
  74119. /**
  74120. * Get bone's index searching by name
  74121. * @param {string} name is bone's name to search for
  74122. * @return {number} Indice of the bone. Returns -1 if not found
  74123. */
  74124. Skeleton.prototype.getBoneIndexByName = function (name) {
  74125. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  74126. if (this.bones[boneIndex].name === name) {
  74127. return boneIndex;
  74128. }
  74129. }
  74130. return -1;
  74131. };
  74132. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  74133. // check name not already in use
  74134. if (!this._ranges[name]) {
  74135. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  74136. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74137. if (this.bones[i].animations[0]) {
  74138. this.bones[i].animations[0].createRange(name, from, to);
  74139. }
  74140. }
  74141. }
  74142. };
  74143. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  74144. if (deleteFrames === void 0) { deleteFrames = true; }
  74145. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74146. if (this.bones[i].animations[0]) {
  74147. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  74148. }
  74149. }
  74150. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  74151. };
  74152. Skeleton.prototype.getAnimationRange = function (name) {
  74153. return this._ranges[name];
  74154. };
  74155. /**
  74156. * Returns as an Array, all AnimationRanges defined on this skeleton
  74157. */
  74158. Skeleton.prototype.getAnimationRanges = function () {
  74159. var animationRanges = [];
  74160. var name;
  74161. var i = 0;
  74162. for (name in this._ranges) {
  74163. animationRanges[i] = this._ranges[name];
  74164. i++;
  74165. }
  74166. return animationRanges;
  74167. };
  74168. /**
  74169. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  74170. */
  74171. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  74172. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  74173. if (this._ranges[name] || !source.getAnimationRange(name)) {
  74174. return false;
  74175. }
  74176. var ret = true;
  74177. var frameOffset = this._getHighestAnimationFrame() + 1;
  74178. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  74179. var boneDict = {};
  74180. var sourceBones = source.bones;
  74181. var nBones;
  74182. var i;
  74183. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  74184. boneDict[sourceBones[i].name] = sourceBones[i];
  74185. }
  74186. if (this.bones.length !== sourceBones.length) {
  74187. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  74188. ret = false;
  74189. }
  74190. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  74191. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  74192. var boneName = this.bones[i].name;
  74193. var sourceBone = boneDict[boneName];
  74194. if (sourceBone) {
  74195. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  74196. }
  74197. else {
  74198. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  74199. ret = false;
  74200. }
  74201. }
  74202. // do not call createAnimationRange(), since it also is done to bones, which was already done
  74203. var range = source.getAnimationRange(name);
  74204. if (range) {
  74205. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  74206. }
  74207. return ret;
  74208. };
  74209. Skeleton.prototype.returnToRest = function () {
  74210. for (var index = 0; index < this.bones.length; index++) {
  74211. this.bones[index].returnToRest();
  74212. }
  74213. };
  74214. Skeleton.prototype._getHighestAnimationFrame = function () {
  74215. var ret = 0;
  74216. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74217. if (this.bones[i].animations[0]) {
  74218. var highest = this.bones[i].animations[0].getHighestFrame();
  74219. if (ret < highest) {
  74220. ret = highest;
  74221. }
  74222. }
  74223. }
  74224. return ret;
  74225. };
  74226. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  74227. var range = this.getAnimationRange(name);
  74228. if (!range) {
  74229. return null;
  74230. }
  74231. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  74232. };
  74233. Skeleton.prototype._markAsDirty = function () {
  74234. this._isDirty = true;
  74235. };
  74236. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  74237. this._meshesWithPoseMatrix.push(mesh);
  74238. };
  74239. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  74240. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  74241. if (index > -1) {
  74242. this._meshesWithPoseMatrix.splice(index, 1);
  74243. }
  74244. };
  74245. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  74246. this.onBeforeComputeObservable.notifyObservers(this);
  74247. for (var index = 0; index < this.bones.length; index++) {
  74248. var bone = this.bones[index];
  74249. var parentBone = bone.getParent();
  74250. if (parentBone) {
  74251. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  74252. }
  74253. else {
  74254. if (initialSkinMatrix) {
  74255. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  74256. }
  74257. else {
  74258. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  74259. }
  74260. }
  74261. if (bone._index !== -1) {
  74262. var mappedIndex = bone._index === null ? index : bone._index;
  74263. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  74264. }
  74265. }
  74266. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  74267. };
  74268. Skeleton.prototype.prepare = function () {
  74269. if (!this._isDirty) {
  74270. return;
  74271. }
  74272. if (this.needInitialSkinMatrix) {
  74273. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  74274. var mesh = this._meshesWithPoseMatrix[index];
  74275. var poseMatrix = mesh.getPoseMatrix();
  74276. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  74277. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74278. }
  74279. if (this._synchronizedWithMesh !== mesh) {
  74280. this._synchronizedWithMesh = mesh;
  74281. // Prepare bones
  74282. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  74283. var bone = this.bones[boneIndex];
  74284. if (!bone.getParent()) {
  74285. var matrix = bone.getBaseMatrix();
  74286. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  74287. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  74288. }
  74289. }
  74290. }
  74291. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  74292. }
  74293. }
  74294. else {
  74295. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  74296. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74297. }
  74298. this._computeTransformMatrices(this._transformMatrices, null);
  74299. }
  74300. this._isDirty = false;
  74301. this._scene._activeBones.addCount(this.bones.length, false);
  74302. };
  74303. Skeleton.prototype.getAnimatables = function () {
  74304. if (!this._animatables || this._animatables.length !== this.bones.length) {
  74305. this._animatables = [];
  74306. for (var index = 0; index < this.bones.length; index++) {
  74307. this._animatables.push(this.bones[index]);
  74308. }
  74309. }
  74310. return this._animatables;
  74311. };
  74312. Skeleton.prototype.clone = function (name, id) {
  74313. var result = new Skeleton(name, id || name, this._scene);
  74314. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74315. for (var index = 0; index < this.bones.length; index++) {
  74316. var source = this.bones[index];
  74317. var parentBone = null;
  74318. var parent_1 = source.getParent();
  74319. if (parent_1) {
  74320. var parentIndex = this.bones.indexOf(parent_1);
  74321. parentBone = result.bones[parentIndex];
  74322. }
  74323. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  74324. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  74325. }
  74326. if (this._ranges) {
  74327. result._ranges = {};
  74328. for (var rangeName in this._ranges) {
  74329. var range = this._ranges[rangeName];
  74330. if (range) {
  74331. result._ranges[rangeName] = range.clone();
  74332. }
  74333. }
  74334. }
  74335. this._isDirty = true;
  74336. return result;
  74337. };
  74338. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  74339. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  74340. this.bones.forEach(function (bone) {
  74341. bone.animations.forEach(function (animation) {
  74342. animation.enableBlending = true;
  74343. animation.blendingSpeed = blendingSpeed;
  74344. });
  74345. });
  74346. };
  74347. Skeleton.prototype.dispose = function () {
  74348. this._meshesWithPoseMatrix = [];
  74349. // Animations
  74350. this.getScene().stopAnimation(this);
  74351. // Remove from scene
  74352. this.getScene().removeSkeleton(this);
  74353. };
  74354. Skeleton.prototype.serialize = function () {
  74355. var serializationObject = {};
  74356. serializationObject.name = this.name;
  74357. serializationObject.id = this.id;
  74358. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  74359. serializationObject.bones = [];
  74360. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74361. for (var index = 0; index < this.bones.length; index++) {
  74362. var bone = this.bones[index];
  74363. var parent_2 = bone.getParent();
  74364. var serializedBone = {
  74365. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  74366. name: bone.name,
  74367. matrix: bone.getBaseMatrix().toArray(),
  74368. rest: bone.getRestPose().toArray()
  74369. };
  74370. serializationObject.bones.push(serializedBone);
  74371. if (bone.length) {
  74372. serializedBone.length = bone.length;
  74373. }
  74374. if (bone.animations && bone.animations.length > 0) {
  74375. serializedBone.animation = bone.animations[0].serialize();
  74376. }
  74377. serializationObject.ranges = [];
  74378. for (var name in this._ranges) {
  74379. var source = this._ranges[name];
  74380. if (!source) {
  74381. continue;
  74382. }
  74383. var range = {};
  74384. range.name = name;
  74385. range.from = source.from;
  74386. range.to = source.to;
  74387. serializationObject.ranges.push(range);
  74388. }
  74389. }
  74390. return serializationObject;
  74391. };
  74392. Skeleton.Parse = function (parsedSkeleton, scene) {
  74393. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  74394. if (parsedSkeleton.dimensionsAtRest) {
  74395. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  74396. }
  74397. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  74398. var index;
  74399. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  74400. var parsedBone = parsedSkeleton.bones[index];
  74401. var parentBone = null;
  74402. if (parsedBone.parentBoneIndex > -1) {
  74403. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  74404. }
  74405. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  74406. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  74407. if (parsedBone.length) {
  74408. bone.length = parsedBone.length;
  74409. }
  74410. if (parsedBone.animation) {
  74411. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  74412. }
  74413. }
  74414. // placed after bones, so createAnimationRange can cascade down
  74415. if (parsedSkeleton.ranges) {
  74416. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  74417. var data = parsedSkeleton.ranges[index];
  74418. skeleton.createAnimationRange(data.name, data.from, data.to);
  74419. }
  74420. }
  74421. return skeleton;
  74422. };
  74423. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  74424. if (forceUpdate === void 0) { forceUpdate = false; }
  74425. var renderId = this._scene.getRenderId();
  74426. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  74427. this.bones[0].computeAbsoluteTransforms();
  74428. this._lastAbsoluteTransformsUpdateId = renderId;
  74429. }
  74430. };
  74431. Skeleton.prototype.getPoseMatrix = function () {
  74432. var poseMatrix = null;
  74433. if (this._meshesWithPoseMatrix.length > 0) {
  74434. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  74435. }
  74436. return poseMatrix;
  74437. };
  74438. Skeleton.prototype.sortBones = function () {
  74439. var bones = new Array();
  74440. var visited = new Array(this.bones.length);
  74441. for (var index = 0; index < this.bones.length; index++) {
  74442. this._sortBones(index, bones, visited);
  74443. }
  74444. this.bones = bones;
  74445. };
  74446. Skeleton.prototype._sortBones = function (index, bones, visited) {
  74447. if (visited[index]) {
  74448. return;
  74449. }
  74450. visited[index] = true;
  74451. var bone = this.bones[index];
  74452. if (bone._index === undefined) {
  74453. bone._index = index;
  74454. }
  74455. var parentBone = bone.getParent();
  74456. if (parentBone) {
  74457. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  74458. }
  74459. bones.push(bone);
  74460. };
  74461. return Skeleton;
  74462. }());
  74463. BABYLON.Skeleton = Skeleton;
  74464. })(BABYLON || (BABYLON = {}));
  74465. //# sourceMappingURL=babylon.skeleton.js.map
  74466. "use strict";
  74467. var BABYLON;
  74468. (function (BABYLON) {
  74469. var SphericalPolynomial = /** @class */ (function () {
  74470. function SphericalPolynomial() {
  74471. this.x = BABYLON.Vector3.Zero();
  74472. this.y = BABYLON.Vector3.Zero();
  74473. this.z = BABYLON.Vector3.Zero();
  74474. this.xx = BABYLON.Vector3.Zero();
  74475. this.yy = BABYLON.Vector3.Zero();
  74476. this.zz = BABYLON.Vector3.Zero();
  74477. this.xy = BABYLON.Vector3.Zero();
  74478. this.yz = BABYLON.Vector3.Zero();
  74479. this.zx = BABYLON.Vector3.Zero();
  74480. }
  74481. SphericalPolynomial.prototype.addAmbient = function (color) {
  74482. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74483. this.xx = this.xx.add(colorVector);
  74484. this.yy = this.yy.add(colorVector);
  74485. this.zz = this.zz.add(colorVector);
  74486. };
  74487. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  74488. var result = new SphericalPolynomial();
  74489. result.x = harmonics.L11.scale(1.02333);
  74490. result.y = harmonics.L1_1.scale(1.02333);
  74491. result.z = harmonics.L10.scale(1.02333);
  74492. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  74493. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  74494. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  74495. result.yz = harmonics.L2_1.scale(0.858086);
  74496. result.zx = harmonics.L21.scale(0.858086);
  74497. result.xy = harmonics.L2_2.scale(0.858086);
  74498. result.scale(1.0 / Math.PI);
  74499. return result;
  74500. };
  74501. SphericalPolynomial.prototype.scale = function (scale) {
  74502. this.x = this.x.scale(scale);
  74503. this.y = this.y.scale(scale);
  74504. this.z = this.z.scale(scale);
  74505. this.xx = this.xx.scale(scale);
  74506. this.yy = this.yy.scale(scale);
  74507. this.zz = this.zz.scale(scale);
  74508. this.yz = this.yz.scale(scale);
  74509. this.zx = this.zx.scale(scale);
  74510. this.xy = this.xy.scale(scale);
  74511. };
  74512. return SphericalPolynomial;
  74513. }());
  74514. BABYLON.SphericalPolynomial = SphericalPolynomial;
  74515. var SphericalHarmonics = /** @class */ (function () {
  74516. function SphericalHarmonics() {
  74517. this.L00 = BABYLON.Vector3.Zero();
  74518. this.L1_1 = BABYLON.Vector3.Zero();
  74519. this.L10 = BABYLON.Vector3.Zero();
  74520. this.L11 = BABYLON.Vector3.Zero();
  74521. this.L2_2 = BABYLON.Vector3.Zero();
  74522. this.L2_1 = BABYLON.Vector3.Zero();
  74523. this.L20 = BABYLON.Vector3.Zero();
  74524. this.L21 = BABYLON.Vector3.Zero();
  74525. this.L22 = BABYLON.Vector3.Zero();
  74526. }
  74527. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  74528. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74529. var c = colorVector.scale(deltaSolidAngle);
  74530. this.L00 = this.L00.add(c.scale(0.282095));
  74531. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  74532. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  74533. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  74534. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  74535. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  74536. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  74537. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  74538. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  74539. };
  74540. SphericalHarmonics.prototype.scale = function (scale) {
  74541. this.L00 = this.L00.scale(scale);
  74542. this.L1_1 = this.L1_1.scale(scale);
  74543. this.L10 = this.L10.scale(scale);
  74544. this.L11 = this.L11.scale(scale);
  74545. this.L2_2 = this.L2_2.scale(scale);
  74546. this.L2_1 = this.L2_1.scale(scale);
  74547. this.L20 = this.L20.scale(scale);
  74548. this.L21 = this.L21.scale(scale);
  74549. this.L22 = this.L22.scale(scale);
  74550. };
  74551. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  74552. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  74553. //
  74554. // E_lm = A_l * L_lm
  74555. //
  74556. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  74557. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  74558. // the scaling factors are given in equation 9.
  74559. // Constant (Band 0)
  74560. this.L00 = this.L00.scale(3.141593);
  74561. // Linear (Band 1)
  74562. this.L1_1 = this.L1_1.scale(2.094395);
  74563. this.L10 = this.L10.scale(2.094395);
  74564. this.L11 = this.L11.scale(2.094395);
  74565. // Quadratic (Band 2)
  74566. this.L2_2 = this.L2_2.scale(0.785398);
  74567. this.L2_1 = this.L2_1.scale(0.785398);
  74568. this.L20 = this.L20.scale(0.785398);
  74569. this.L21 = this.L21.scale(0.785398);
  74570. this.L22 = this.L22.scale(0.785398);
  74571. };
  74572. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74573. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74574. // L = (1/pi) * E * rho
  74575. //
  74576. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74577. this.scale(1.0 / Math.PI);
  74578. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74579. // (The pixel shader must apply albedo after texture fetches, etc).
  74580. };
  74581. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74582. var result = new SphericalHarmonics();
  74583. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74584. result.L1_1 = polynomial.y.scale(0.977204);
  74585. result.L10 = polynomial.z.scale(0.977204);
  74586. result.L11 = polynomial.x.scale(0.977204);
  74587. result.L2_2 = polynomial.xy.scale(1.16538);
  74588. result.L2_1 = polynomial.yz.scale(1.16538);
  74589. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74590. result.L21 = polynomial.zx.scale(1.16538);
  74591. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74592. result.scale(Math.PI);
  74593. return result;
  74594. };
  74595. return SphericalHarmonics;
  74596. }());
  74597. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74598. })(BABYLON || (BABYLON = {}));
  74599. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74600. "use strict";
  74601. var BABYLON;
  74602. (function (BABYLON) {
  74603. var FileFaceOrientation = /** @class */ (function () {
  74604. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74605. this.name = name;
  74606. this.worldAxisForNormal = worldAxisForNormal;
  74607. this.worldAxisForFileX = worldAxisForFileX;
  74608. this.worldAxisForFileY = worldAxisForFileY;
  74609. }
  74610. return FileFaceOrientation;
  74611. }());
  74612. ;
  74613. /**
  74614. * Helper class dealing with the extraction of spherical polynomial dataArray
  74615. * from a cube map.
  74616. */
  74617. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74618. function CubeMapToSphericalPolynomialTools() {
  74619. }
  74620. /**
  74621. * Converts a texture to the according Spherical Polynomial data.
  74622. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74623. *
  74624. * @param texture The texture to extract the information from.
  74625. * @return The Spherical Polynomial data.
  74626. */
  74627. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74628. if (!texture.isCube) {
  74629. // Only supports cube Textures currently.
  74630. return null;
  74631. }
  74632. var size = texture.getSize().width;
  74633. var right = texture.readPixels(0);
  74634. var left = texture.readPixels(1);
  74635. var up;
  74636. var down;
  74637. if (texture.isRenderTarget) {
  74638. up = texture.readPixels(3);
  74639. down = texture.readPixels(2);
  74640. }
  74641. else {
  74642. up = texture.readPixels(2);
  74643. down = texture.readPixels(3);
  74644. }
  74645. var front = texture.readPixels(4);
  74646. var back = texture.readPixels(5);
  74647. var gammaSpace = texture.gammaSpace;
  74648. // Always read as RGBA.
  74649. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74650. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74651. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74652. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74653. }
  74654. var cubeInfo = {
  74655. size: size,
  74656. right: right,
  74657. left: left,
  74658. up: up,
  74659. down: down,
  74660. front: front,
  74661. back: back,
  74662. format: format,
  74663. type: type,
  74664. gammaSpace: gammaSpace,
  74665. };
  74666. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74667. };
  74668. /**
  74669. * Converts a cubemap to the according Spherical Polynomial data.
  74670. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74671. *
  74672. * @param cubeInfo The Cube map to extract the information from.
  74673. * @return The Spherical Polynomial data.
  74674. */
  74675. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74676. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74677. var totalSolidAngle = 0.0;
  74678. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74679. var du = 2.0 / cubeInfo.size;
  74680. var dv = du;
  74681. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74682. var minUV = du * 0.5 - 1.0;
  74683. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74684. var fileFace = this.FileFaces[faceIndex];
  74685. var dataArray = cubeInfo[fileFace.name];
  74686. var v = minUV;
  74687. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74688. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74689. // Because SP is still linear, so summation is fine in that basis.
  74690. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74691. for (var y = 0; y < cubeInfo.size; y++) {
  74692. var u = minUV;
  74693. for (var x = 0; x < cubeInfo.size; x++) {
  74694. // World direction (not normalised)
  74695. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74696. worldDirection.normalize();
  74697. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74698. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74699. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74700. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74701. // Handle Integer types.
  74702. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74703. r /= 255;
  74704. g /= 255;
  74705. b /= 255;
  74706. }
  74707. // Handle Gamma space textures.
  74708. if (cubeInfo.gammaSpace) {
  74709. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74710. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74711. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74712. }
  74713. var color = new BABYLON.Color3(r, g, b);
  74714. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74715. totalSolidAngle += deltaSolidAngle;
  74716. u += du;
  74717. }
  74718. v += dv;
  74719. }
  74720. }
  74721. // Solid angle for entire sphere is 4*pi
  74722. var sphereSolidAngle = 4.0 * Math.PI;
  74723. // Adjust the solid angle to allow for how many faces we processed.
  74724. var facesProcessed = 6.0;
  74725. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74726. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74727. // This is needed because the numerical integration over the cube uses a
  74728. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74729. // and also to compensate for accumulative error due to float precision in the summation.
  74730. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74731. sphericalHarmonics.scale(correctionFactor);
  74732. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74733. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74734. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74735. };
  74736. CubeMapToSphericalPolynomialTools.FileFaces = [
  74737. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74738. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74739. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74740. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74741. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74742. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74743. ];
  74744. return CubeMapToSphericalPolynomialTools;
  74745. }());
  74746. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74747. })(BABYLON || (BABYLON = {}));
  74748. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74749. "use strict";
  74750. var BABYLON;
  74751. (function (BABYLON) {
  74752. /**
  74753. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74754. */
  74755. var PanoramaToCubeMapTools = /** @class */ (function () {
  74756. function PanoramaToCubeMapTools() {
  74757. }
  74758. /**
  74759. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74760. *
  74761. * @param float32Array The source data.
  74762. * @param inputWidth The width of the input panorama.
  74763. * @param inputhHeight The height of the input panorama.
  74764. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  74765. * @return The cubemap data
  74766. */
  74767. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  74768. if (!float32Array) {
  74769. throw "ConvertPanoramaToCubemap: input cannot be null";
  74770. }
  74771. if (float32Array.length != inputWidth * inputHeight * 3) {
  74772. throw "ConvertPanoramaToCubemap: input size is wrong";
  74773. }
  74774. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  74775. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  74776. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  74777. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  74778. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  74779. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  74780. return {
  74781. front: textureFront,
  74782. back: textureBack,
  74783. left: textureLeft,
  74784. right: textureRight,
  74785. up: textureUp,
  74786. down: textureDown,
  74787. size: size,
  74788. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  74789. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  74790. gammaSpace: false,
  74791. };
  74792. };
  74793. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  74794. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  74795. var textureArray = new Float32Array(buffer);
  74796. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  74797. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  74798. var dy = 1 / texSize;
  74799. var fy = 0;
  74800. for (var y = 0; y < texSize; y++) {
  74801. var xv1 = faceData[0];
  74802. var xv2 = faceData[2];
  74803. for (var x = 0; x < texSize; x++) {
  74804. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  74805. v.normalize();
  74806. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  74807. // 3 channels per pixels
  74808. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  74809. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  74810. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  74811. xv1 = xv1.add(rotDX1);
  74812. xv2 = xv2.add(rotDX2);
  74813. }
  74814. fy += dy;
  74815. }
  74816. return textureArray;
  74817. };
  74818. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  74819. var theta = Math.atan2(vDir.z, vDir.x);
  74820. var phi = Math.acos(vDir.y);
  74821. while (theta < -Math.PI)
  74822. theta += 2 * Math.PI;
  74823. while (theta > Math.PI)
  74824. theta -= 2 * Math.PI;
  74825. var dx = theta / Math.PI;
  74826. var dy = phi / Math.PI;
  74827. // recenter.
  74828. dx = dx * 0.5 + 0.5;
  74829. var px = Math.round(dx * inputWidth);
  74830. if (px < 0)
  74831. px = 0;
  74832. else if (px >= inputWidth)
  74833. px = inputWidth - 1;
  74834. var py = Math.round(dy * inputHeight);
  74835. if (py < 0)
  74836. py = 0;
  74837. else if (py >= inputHeight)
  74838. py = inputHeight - 1;
  74839. var inputY = (inputHeight - py - 1);
  74840. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  74841. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  74842. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  74843. return {
  74844. r: r,
  74845. g: g,
  74846. b: b
  74847. };
  74848. };
  74849. PanoramaToCubeMapTools.FACE_FRONT = [
  74850. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74851. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74852. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74853. new BABYLON.Vector3(1.0, 1.0, -1.0)
  74854. ];
  74855. PanoramaToCubeMapTools.FACE_BACK = [
  74856. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74857. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74858. new BABYLON.Vector3(1.0, 1.0, 1.0),
  74859. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  74860. ];
  74861. PanoramaToCubeMapTools.FACE_RIGHT = [
  74862. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74863. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74864. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74865. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74866. ];
  74867. PanoramaToCubeMapTools.FACE_LEFT = [
  74868. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74869. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74870. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74871. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  74872. ];
  74873. PanoramaToCubeMapTools.FACE_DOWN = [
  74874. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74875. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74876. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74877. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74878. ];
  74879. PanoramaToCubeMapTools.FACE_UP = [
  74880. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74881. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74882. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74883. new BABYLON.Vector3(1.0, -1.0, -1.0)
  74884. ];
  74885. return PanoramaToCubeMapTools;
  74886. }());
  74887. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  74888. })(BABYLON || (BABYLON = {}));
  74889. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  74890. "use strict";
  74891. var BABYLON;
  74892. (function (BABYLON) {
  74893. ;
  74894. /**
  74895. * This groups tools to convert HDR texture to native colors array.
  74896. */
  74897. var HDRTools = /** @class */ (function () {
  74898. function HDRTools() {
  74899. }
  74900. HDRTools.Ldexp = function (mantissa, exponent) {
  74901. if (exponent > 1023) {
  74902. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  74903. }
  74904. if (exponent < -1074) {
  74905. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  74906. }
  74907. return mantissa * Math.pow(2, exponent);
  74908. };
  74909. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  74910. if (exponent > 0) {
  74911. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  74912. float32array[index + 0] = red * exponent;
  74913. float32array[index + 1] = green * exponent;
  74914. float32array[index + 2] = blue * exponent;
  74915. }
  74916. else {
  74917. float32array[index + 0] = 0;
  74918. float32array[index + 1] = 0;
  74919. float32array[index + 2] = 0;
  74920. }
  74921. };
  74922. HDRTools.readStringLine = function (uint8array, startIndex) {
  74923. var line = "";
  74924. var character = "";
  74925. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  74926. character = String.fromCharCode(uint8array[i]);
  74927. if (character == "\n") {
  74928. break;
  74929. }
  74930. line += character;
  74931. }
  74932. return line;
  74933. };
  74934. /**
  74935. * Reads header information from an RGBE texture stored in a native array.
  74936. * More information on this format are available here:
  74937. * https://en.wikipedia.org/wiki/RGBE_image_format
  74938. *
  74939. * @param uint8array The binary file stored in native array.
  74940. * @return The header information.
  74941. */
  74942. HDRTools.RGBE_ReadHeader = function (uint8array) {
  74943. var height = 0;
  74944. var width = 0;
  74945. var line = this.readStringLine(uint8array, 0);
  74946. if (line[0] != '#' || line[1] != '?') {
  74947. throw "Bad HDR Format.";
  74948. }
  74949. var endOfHeader = false;
  74950. var findFormat = false;
  74951. var lineIndex = 0;
  74952. do {
  74953. lineIndex += (line.length + 1);
  74954. line = this.readStringLine(uint8array, lineIndex);
  74955. if (line == "FORMAT=32-bit_rle_rgbe") {
  74956. findFormat = true;
  74957. }
  74958. else if (line.length == 0) {
  74959. endOfHeader = true;
  74960. }
  74961. } while (!endOfHeader);
  74962. if (!findFormat) {
  74963. throw "HDR Bad header format, unsupported FORMAT";
  74964. }
  74965. lineIndex += (line.length + 1);
  74966. line = this.readStringLine(uint8array, lineIndex);
  74967. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  74968. var match = sizeRegexp.exec(line);
  74969. // TODO. Support +Y and -X if needed.
  74970. if (!match || match.length < 3) {
  74971. throw "HDR Bad header format, no size";
  74972. }
  74973. width = parseInt(match[2]);
  74974. height = parseInt(match[1]);
  74975. if (width < 8 || width > 0x7fff) {
  74976. throw "HDR Bad header format, unsupported size";
  74977. }
  74978. lineIndex += (line.length + 1);
  74979. return {
  74980. height: height,
  74981. width: width,
  74982. dataPosition: lineIndex
  74983. };
  74984. };
  74985. /**
  74986. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  74987. * This RGBE texture needs to store the information as a panorama.
  74988. *
  74989. * More information on this format are available here:
  74990. * https://en.wikipedia.org/wiki/RGBE_image_format
  74991. *
  74992. * @param buffer The binary file stored in an array buffer.
  74993. * @param size The expected size of the extracted cubemap.
  74994. * @return The Cube Map information.
  74995. */
  74996. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  74997. var uint8array = new Uint8Array(buffer);
  74998. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  74999. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75000. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  75001. return cubeMapData;
  75002. };
  75003. /**
  75004. * Returns the pixels data extracted from an RGBE texture.
  75005. * This pixels will be stored left to right up to down in the R G B order in one array.
  75006. *
  75007. * More information on this format are available here:
  75008. * https://en.wikipedia.org/wiki/RGBE_image_format
  75009. *
  75010. * @param uint8array The binary file stored in an array buffer.
  75011. * @param hdrInfo The header information of the file.
  75012. * @return The pixels data in RGB right to left up to down order.
  75013. */
  75014. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  75015. // Keep for multi format supports.
  75016. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75017. };
  75018. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  75019. var num_scanlines = hdrInfo.height;
  75020. var scanline_width = hdrInfo.width;
  75021. var a, b, c, d, count;
  75022. var dataIndex = hdrInfo.dataPosition;
  75023. var index = 0, endIndex = 0, i = 0;
  75024. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  75025. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  75026. // 3 channels of 4 bytes per pixel in float.
  75027. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  75028. var resultArray = new Float32Array(resultBuffer);
  75029. // read in each successive scanline
  75030. while (num_scanlines > 0) {
  75031. a = uint8array[dataIndex++];
  75032. b = uint8array[dataIndex++];
  75033. c = uint8array[dataIndex++];
  75034. d = uint8array[dataIndex++];
  75035. if (a != 2 || b != 2 || (c & 0x80)) {
  75036. // this file is not run length encoded
  75037. throw "HDR Bad header format, not RLE";
  75038. }
  75039. if (((c << 8) | d) != scanline_width) {
  75040. throw "HDR Bad header format, wrong scan line width";
  75041. }
  75042. index = 0;
  75043. // read each of the four channels for the scanline into the buffer
  75044. for (i = 0; i < 4; i++) {
  75045. endIndex = (i + 1) * scanline_width;
  75046. while (index < endIndex) {
  75047. a = uint8array[dataIndex++];
  75048. b = uint8array[dataIndex++];
  75049. if (a > 128) {
  75050. // a run of the same value
  75051. count = a - 128;
  75052. if ((count == 0) || (count > endIndex - index)) {
  75053. throw "HDR Bad Format, bad scanline data (run)";
  75054. }
  75055. while (count-- > 0) {
  75056. scanLineArray[index++] = b;
  75057. }
  75058. }
  75059. else {
  75060. // a non-run
  75061. count = a;
  75062. if ((count == 0) || (count > endIndex - index)) {
  75063. throw "HDR Bad Format, bad scanline data (non-run)";
  75064. }
  75065. scanLineArray[index++] = b;
  75066. if (--count > 0) {
  75067. for (var j = 0; j < count; j++) {
  75068. scanLineArray[index++] = uint8array[dataIndex++];
  75069. }
  75070. }
  75071. }
  75072. }
  75073. }
  75074. // now convert data from buffer into floats
  75075. for (i = 0; i < scanline_width; i++) {
  75076. a = scanLineArray[i];
  75077. b = scanLineArray[i + scanline_width];
  75078. c = scanLineArray[i + 2 * scanline_width];
  75079. d = scanLineArray[i + 3 * scanline_width];
  75080. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  75081. }
  75082. num_scanlines--;
  75083. }
  75084. return resultArray;
  75085. };
  75086. return HDRTools;
  75087. }());
  75088. BABYLON.HDRTools = HDRTools;
  75089. })(BABYLON || (BABYLON = {}));
  75090. //# sourceMappingURL=babylon.hdr.js.map
  75091. "use strict";
  75092. var BABYLON;
  75093. (function (BABYLON) {
  75094. /**
  75095. * This represents a texture coming from an HDR input.
  75096. *
  75097. * The only supported format is currently panorama picture stored in RGBE format.
  75098. * Example of such files can be found on HDRLib: http://hdrlib.com/
  75099. */
  75100. var HDRCubeTexture = /** @class */ (function (_super) {
  75101. __extends(HDRCubeTexture, _super);
  75102. /**
  75103. * Instantiates an HDRTexture from the following parameters.
  75104. *
  75105. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  75106. * @param scene The scene the texture will be used in
  75107. * @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.
  75108. * @param noMipmap Forces to not generate the mipmap if true
  75109. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  75110. * @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)
  75111. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  75112. */
  75113. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  75114. if (noMipmap === void 0) { noMipmap = false; }
  75115. if (generateHarmonics === void 0) { generateHarmonics = true; }
  75116. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  75117. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  75118. if (onLoad === void 0) { onLoad = null; }
  75119. if (onError === void 0) { onError = null; }
  75120. var _this = _super.call(this, scene) || this;
  75121. _this._useInGammaSpace = false;
  75122. _this._generateHarmonics = true;
  75123. _this._isBABYLONPreprocessed = false;
  75124. _this._onLoad = null;
  75125. _this._onError = null;
  75126. /**
  75127. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  75128. */
  75129. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  75130. /**
  75131. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  75132. * This is usefull at run time to apply the good shader.
  75133. */
  75134. _this.isPMREM = false;
  75135. _this._isBlocking = true;
  75136. /**
  75137. * Gets or sets the center of the bounding box associated with the cube texture
  75138. * It must define where the camera used to render the texture was set
  75139. */
  75140. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  75141. if (!url) {
  75142. return _this;
  75143. }
  75144. _this.name = url;
  75145. _this.url = url;
  75146. _this.hasAlpha = false;
  75147. _this.isCube = true;
  75148. _this._textureMatrix = BABYLON.Matrix.Identity();
  75149. _this._onLoad = onLoad;
  75150. _this._onError = onError;
  75151. _this.gammaSpace = false;
  75152. var caps = scene.getEngine().getCaps();
  75153. if (size) {
  75154. _this._isBABYLONPreprocessed = false;
  75155. _this._noMipmap = noMipmap;
  75156. _this._size = size;
  75157. _this._useInGammaSpace = useInGammaSpace;
  75158. _this._usePMREMGenerator = usePMREMGenerator &&
  75159. caps.textureLOD &&
  75160. caps.textureFloat &&
  75161. !_this._useInGammaSpace;
  75162. }
  75163. else {
  75164. _this._isBABYLONPreprocessed = true;
  75165. _this._noMipmap = false;
  75166. _this._useInGammaSpace = false;
  75167. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  75168. !_this._useInGammaSpace;
  75169. }
  75170. _this.isPMREM = _this._usePMREMGenerator;
  75171. _this._texture = _this._getFromCache(url, _this._noMipmap);
  75172. if (!_this._texture) {
  75173. if (!scene.useDelayedTextureLoading) {
  75174. _this.loadTexture();
  75175. }
  75176. else {
  75177. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  75178. }
  75179. }
  75180. return _this;
  75181. }
  75182. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  75183. /**
  75184. * Gets wether or not the texture is blocking during loading.
  75185. */
  75186. get: function () {
  75187. return this._isBlocking;
  75188. },
  75189. /**
  75190. * Sets wether or not the texture is blocking during loading.
  75191. */
  75192. set: function (value) {
  75193. this._isBlocking = value;
  75194. },
  75195. enumerable: true,
  75196. configurable: true
  75197. });
  75198. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  75199. get: function () {
  75200. return this._boundingBoxSize;
  75201. },
  75202. /**
  75203. * Gets or sets the size of the bounding box associated with the cube texture
  75204. * When defined, the cubemap will switch to local mode
  75205. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  75206. * @example https://www.babylonjs-playground.com/#RNASML
  75207. */
  75208. set: function (value) {
  75209. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  75210. return;
  75211. }
  75212. this._boundingBoxSize = value;
  75213. var scene = this.getScene();
  75214. if (scene) {
  75215. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  75216. }
  75217. },
  75218. enumerable: true,
  75219. configurable: true
  75220. });
  75221. /**
  75222. * Occurs when the file is a preprocessed .babylon.hdr file.
  75223. */
  75224. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  75225. var _this = this;
  75226. var mipLevels = 0;
  75227. var floatArrayView = null;
  75228. var scene = this.getScene();
  75229. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  75230. var mips = new Array();
  75231. if (!floatArrayView) {
  75232. return mips;
  75233. }
  75234. var startIndex = 30;
  75235. for (var level = 0; level < mipLevels; level++) {
  75236. mips.push([]);
  75237. // Fill each pixel of the mip level.
  75238. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  75239. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75240. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  75241. mips[level].push(faceData);
  75242. startIndex += faceSize;
  75243. }
  75244. }
  75245. return mips;
  75246. } : null;
  75247. var callback = function (buffer) {
  75248. var scene = _this.getScene();
  75249. if (!scene) {
  75250. return null;
  75251. }
  75252. // Create Native Array Views
  75253. var intArrayView = new Int32Array(buffer);
  75254. floatArrayView = new Float32Array(buffer);
  75255. // Fill header.
  75256. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  75257. _this._size = intArrayView[1]; // CubeMap max mip face size.
  75258. // Update Texture Information.
  75259. if (!_this._texture) {
  75260. return null;
  75261. }
  75262. _this._texture.updateSize(_this._size, _this._size);
  75263. // Fill polynomial information.
  75264. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  75265. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  75266. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  75267. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  75268. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  75269. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  75270. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  75271. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  75272. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  75273. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  75274. _this.sphericalPolynomial = sphericalPolynomial;
  75275. // Fill pixel data.
  75276. mipLevels = intArrayView[29]; // Number of mip levels.
  75277. var startIndex = 30;
  75278. var data = [];
  75279. var faceSize = Math.pow(_this._size, 2) * 3;
  75280. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75281. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  75282. startIndex += faceSize;
  75283. }
  75284. var results = [];
  75285. var byteArray = null;
  75286. // Push each faces.
  75287. for (var k = 0; k < 6; k++) {
  75288. var dataFace = null;
  75289. // To be deprecated.
  75290. if (version === 1) {
  75291. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  75292. dataFace = data[j];
  75293. }
  75294. // If special cases.
  75295. if (!mipmapGenerator && dataFace) {
  75296. if (!scene.getEngine().getCaps().textureFloat) {
  75297. // 3 channels of 1 bytes per pixel in bytes.
  75298. var byteBuffer = new ArrayBuffer(faceSize);
  75299. byteArray = new Uint8Array(byteBuffer);
  75300. }
  75301. for (var i = 0; i < _this._size * _this._size; i++) {
  75302. // Put in gamma space if requested.
  75303. if (_this._useInGammaSpace) {
  75304. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75305. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75306. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75307. }
  75308. // Convert to int texture for fallback.
  75309. if (byteArray) {
  75310. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75311. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75312. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75313. // May use luminance instead if the result is not accurate.
  75314. var max = Math.max(Math.max(r, g), b);
  75315. if (max > 255) {
  75316. var scale = 255 / max;
  75317. r *= scale;
  75318. g *= scale;
  75319. b *= scale;
  75320. }
  75321. byteArray[(i * 3) + 0] = r;
  75322. byteArray[(i * 3) + 1] = g;
  75323. byteArray[(i * 3) + 2] = b;
  75324. }
  75325. }
  75326. }
  75327. // Fill the array accordingly.
  75328. if (byteArray) {
  75329. results.push(byteArray);
  75330. }
  75331. else {
  75332. results.push(dataFace);
  75333. }
  75334. }
  75335. return results;
  75336. };
  75337. if (scene) {
  75338. 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);
  75339. }
  75340. };
  75341. /**
  75342. * Occurs when the file is raw .hdr file.
  75343. */
  75344. HDRCubeTexture.prototype.loadHDRTexture = function () {
  75345. var _this = this;
  75346. var callback = function (buffer) {
  75347. var scene = _this.getScene();
  75348. if (!scene) {
  75349. return null;
  75350. }
  75351. // Extract the raw linear data.
  75352. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  75353. // Generate harmonics if needed.
  75354. if (_this._generateHarmonics) {
  75355. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  75356. _this.sphericalPolynomial = sphericalPolynomial;
  75357. }
  75358. var results = [];
  75359. var byteArray = null;
  75360. // Push each faces.
  75361. for (var j = 0; j < 6; j++) {
  75362. // Create uintarray fallback.
  75363. if (!scene.getEngine().getCaps().textureFloat) {
  75364. // 3 channels of 1 bytes per pixel in bytes.
  75365. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  75366. byteArray = new Uint8Array(byteBuffer);
  75367. }
  75368. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  75369. // If special cases.
  75370. if (_this._useInGammaSpace || byteArray) {
  75371. for (var i = 0; i < _this._size * _this._size; i++) {
  75372. // Put in gamma space if requested.
  75373. if (_this._useInGammaSpace) {
  75374. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75375. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75376. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75377. }
  75378. // Convert to int texture for fallback.
  75379. if (byteArray) {
  75380. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75381. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75382. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75383. // May use luminance instead if the result is not accurate.
  75384. var max = Math.max(Math.max(r, g), b);
  75385. if (max > 255) {
  75386. var scale = 255 / max;
  75387. r *= scale;
  75388. g *= scale;
  75389. b *= scale;
  75390. }
  75391. byteArray[(i * 3) + 0] = r;
  75392. byteArray[(i * 3) + 1] = g;
  75393. byteArray[(i * 3) + 2] = b;
  75394. }
  75395. }
  75396. }
  75397. if (byteArray) {
  75398. results.push(byteArray);
  75399. }
  75400. else {
  75401. results.push(dataFace);
  75402. }
  75403. }
  75404. return results;
  75405. };
  75406. var mipmapGenerator = null;
  75407. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  75408. // if (!this._noMipmap &&
  75409. // this._usePMREMGenerator) {
  75410. // mipmapGenerator = (data: ArrayBufferView[]) => {
  75411. // // Custom setup of the generator matching with the PBR shader values.
  75412. // var generator = new BABYLON.PMREMGenerator(data,
  75413. // this._size,
  75414. // this._size,
  75415. // 0,
  75416. // 3,
  75417. // this.getScene().getEngine().getCaps().textureFloat,
  75418. // 2048,
  75419. // 0.25,
  75420. // false,
  75421. // true);
  75422. // return generator.filterCubeMap();
  75423. // };
  75424. // }
  75425. var scene = this.getScene();
  75426. if (scene) {
  75427. 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);
  75428. }
  75429. };
  75430. /**
  75431. * Starts the loading process of the texture.
  75432. */
  75433. HDRCubeTexture.prototype.loadTexture = function () {
  75434. if (this._isBABYLONPreprocessed) {
  75435. this.loadBabylonTexture();
  75436. }
  75437. else {
  75438. this.loadHDRTexture();
  75439. }
  75440. };
  75441. HDRCubeTexture.prototype.clone = function () {
  75442. var scene = this.getScene();
  75443. if (!scene) {
  75444. return this;
  75445. }
  75446. var size = (this._isBABYLONPreprocessed ? null : this._size);
  75447. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  75448. // Base texture
  75449. newTexture.level = this.level;
  75450. newTexture.wrapU = this.wrapU;
  75451. newTexture.wrapV = this.wrapV;
  75452. newTexture.coordinatesIndex = this.coordinatesIndex;
  75453. newTexture.coordinatesMode = this.coordinatesMode;
  75454. return newTexture;
  75455. };
  75456. // Methods
  75457. HDRCubeTexture.prototype.delayLoad = function () {
  75458. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  75459. return;
  75460. }
  75461. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  75462. this._texture = this._getFromCache(this.url, this._noMipmap);
  75463. if (!this._texture) {
  75464. this.loadTexture();
  75465. }
  75466. };
  75467. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  75468. return this._textureMatrix;
  75469. };
  75470. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  75471. this._textureMatrix = value;
  75472. };
  75473. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  75474. var texture = null;
  75475. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  75476. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  75477. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  75478. texture.name = parsedTexture.name;
  75479. texture.hasAlpha = parsedTexture.hasAlpha;
  75480. texture.level = parsedTexture.level;
  75481. texture.coordinatesMode = parsedTexture.coordinatesMode;
  75482. texture.isBlocking = parsedTexture.isBlocking;
  75483. }
  75484. if (texture) {
  75485. if (parsedTexture.boundingBoxPosition) {
  75486. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  75487. }
  75488. if (parsedTexture.boundingBoxSize) {
  75489. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  75490. }
  75491. }
  75492. return texture;
  75493. };
  75494. HDRCubeTexture.prototype.serialize = function () {
  75495. if (!this.name) {
  75496. return null;
  75497. }
  75498. var serializationObject = {};
  75499. serializationObject.name = this.name;
  75500. serializationObject.hasAlpha = this.hasAlpha;
  75501. serializationObject.isCube = true;
  75502. serializationObject.level = this.level;
  75503. serializationObject.size = this._size;
  75504. serializationObject.coordinatesMode = this.coordinatesMode;
  75505. serializationObject.useInGammaSpace = this._useInGammaSpace;
  75506. serializationObject.generateHarmonics = this._generateHarmonics;
  75507. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  75508. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  75509. serializationObject.customType = "BABYLON.HDRCubeTexture";
  75510. serializationObject.noMipmap = this._noMipmap;
  75511. serializationObject.isBlocking = this._isBlocking;
  75512. return serializationObject;
  75513. };
  75514. /**
  75515. * Saves as a file the data contained in the texture in a binary format.
  75516. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75517. * as the spherical used in the lighting.
  75518. * @param url The HDR file url.
  75519. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75520. * @param onError Method called if any error happens during download.
  75521. * @return The packed binary data.
  75522. */
  75523. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  75524. if (onError === void 0) { onError = null; }
  75525. var callback = function (buffer) {
  75526. var data = new Blob([buffer], { type: 'application/octet-stream' });
  75527. // Returns a URL you can use as a href.
  75528. var objUrl = window.URL.createObjectURL(data);
  75529. // Simulates a link to it and click to dowload.
  75530. var a = document.createElement("a");
  75531. document.body.appendChild(a);
  75532. a.style.display = "none";
  75533. a.href = objUrl;
  75534. a.download = "envmap.babylon.hdr";
  75535. a.click();
  75536. };
  75537. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  75538. };
  75539. /**
  75540. * Serializes the data contained in the texture in a binary format.
  75541. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75542. * as the spherical used in the lighting.
  75543. * @param url The HDR file url.
  75544. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75545. * @param onError Method called if any error happens during download.
  75546. * @return The packed binary data.
  75547. */
  75548. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  75549. if (onError === void 0) { onError = null; }
  75550. // Needs the url tho create the texture.
  75551. if (!url) {
  75552. return;
  75553. }
  75554. // Check Power of two size.
  75555. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  75556. return;
  75557. }
  75558. // Coming Back in 3.x.
  75559. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  75560. };
  75561. HDRCubeTexture._facesMapping = [
  75562. "right",
  75563. "left",
  75564. "up",
  75565. "down",
  75566. "front",
  75567. "back"
  75568. ];
  75569. return HDRCubeTexture;
  75570. }(BABYLON.BaseTexture));
  75571. BABYLON.HDRCubeTexture = HDRCubeTexture;
  75572. })(BABYLON || (BABYLON = {}));
  75573. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75574. "use strict";
  75575. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  75576. // Huge respect for a such great lib.
  75577. // Earcut license:
  75578. // Copyright (c) 2016, Mapbox
  75579. //
  75580. // Permission to use, copy, modify, and/or distribute this software for any purpose
  75581. // with or without fee is hereby granted, provided that the above copyright notice
  75582. // and this permission notice appear in all copies.
  75583. //
  75584. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  75585. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  75586. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  75587. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  75588. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  75589. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  75590. // THIS SOFTWARE.
  75591. var Earcut;
  75592. (function (Earcut) {
  75593. /**
  75594. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  75595. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  75596. * @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).
  75597. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  75598. */
  75599. function earcut(data, holeIndices, dim) {
  75600. dim = dim || 2;
  75601. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  75602. if (!outerNode)
  75603. return triangles;
  75604. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  75605. if (hasHoles)
  75606. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  75607. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  75608. if (data.length > 80 * dim) {
  75609. minX = maxX = data[0];
  75610. minY = maxY = data[1];
  75611. for (var i = dim; i < outerLen; i += dim) {
  75612. x = data[i];
  75613. y = data[i + 1];
  75614. if (x < minX)
  75615. minX = x;
  75616. if (y < minY)
  75617. minY = y;
  75618. if (x > maxX)
  75619. maxX = x;
  75620. if (y > maxY)
  75621. maxY = y;
  75622. }
  75623. // minX, minY and size are later used to transform coords into integers for z-order calculation
  75624. size = Math.max(maxX - minX, maxY - minY);
  75625. }
  75626. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  75627. return triangles;
  75628. }
  75629. Earcut.earcut = earcut;
  75630. var Node = /** @class */ (function () {
  75631. function Node(i, x, y) {
  75632. this.i = i;
  75633. this.x = x;
  75634. this.y = y;
  75635. this.prev = null;
  75636. this.next = null;
  75637. this.z = null;
  75638. this.prevZ = null;
  75639. this.nextZ = null;
  75640. this.steiner = false;
  75641. }
  75642. return Node;
  75643. }());
  75644. // create a circular doubly linked list from polygon points in the specified winding order
  75645. function linkedList(data, start, end, dim, clockwise) {
  75646. var i, last = null;
  75647. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  75648. for (i = start; i < end; i += dim)
  75649. last = insertNode(i, data[i], data[i + 1], last);
  75650. }
  75651. else {
  75652. for (i = end - dim; i >= start; i -= dim)
  75653. last = insertNode(i, data[i], data[i + 1], last);
  75654. }
  75655. if (last && equals(last, last.next)) {
  75656. removeNode(last);
  75657. last = last.next;
  75658. }
  75659. return last;
  75660. }
  75661. // eliminate colinear or duplicate points
  75662. function filterPoints(start, end) {
  75663. if (!start)
  75664. return start;
  75665. if (!end)
  75666. end = start;
  75667. var p = start, again;
  75668. do {
  75669. again = false;
  75670. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  75671. removeNode(p);
  75672. p = end = p.prev;
  75673. if (p === p.next)
  75674. return undefined;
  75675. again = true;
  75676. }
  75677. else {
  75678. p = p.next;
  75679. }
  75680. } while (again || p !== end);
  75681. return end;
  75682. }
  75683. // main ear slicing loop which triangulates a polygon (given as a linked list)
  75684. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  75685. if (!ear)
  75686. return;
  75687. // interlink polygon nodes in z-order
  75688. if (!pass && size)
  75689. indexCurve(ear, minX, minY, size);
  75690. var stop = ear, prev, next;
  75691. // iterate through ears, slicing them one by one
  75692. while (ear.prev !== ear.next) {
  75693. prev = ear.prev;
  75694. next = ear.next;
  75695. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  75696. // cut off the triangle
  75697. triangles.push(prev.i / dim);
  75698. triangles.push(ear.i / dim);
  75699. triangles.push(next.i / dim);
  75700. removeNode(ear);
  75701. // skipping the next vertice leads to less sliver triangles
  75702. ear = next.next;
  75703. stop = next.next;
  75704. continue;
  75705. }
  75706. ear = next;
  75707. // if we looped through the whole remaining polygon and can't find any more ears
  75708. if (ear === stop) {
  75709. // try filtering points and slicing again
  75710. if (!pass) {
  75711. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  75712. // if this didn't work, try curing all small self-intersections locally
  75713. }
  75714. else if (pass === 1) {
  75715. ear = cureLocalIntersections(ear, triangles, dim);
  75716. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  75717. // as a last resort, try splitting the remaining polygon into two
  75718. }
  75719. else if (pass === 2) {
  75720. splitEarcut(ear, triangles, dim, minX, minY, size);
  75721. }
  75722. break;
  75723. }
  75724. }
  75725. }
  75726. // check whether a polygon node forms a valid ear with adjacent nodes
  75727. function isEar(ear) {
  75728. var a = ear.prev, b = ear, c = ear.next;
  75729. if (area(a, b, c) >= 0)
  75730. return false; // reflex, can't be an ear
  75731. // now make sure we don't have other points inside the potential ear
  75732. var p = ear.next.next;
  75733. while (p !== ear.prev) {
  75734. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75735. area(p.prev, p, p.next) >= 0)
  75736. return false;
  75737. p = p.next;
  75738. }
  75739. return true;
  75740. }
  75741. function isEarHashed(ear, minX, minY, size) {
  75742. var a = ear.prev, b = ear, c = ear.next;
  75743. if (area(a, b, c) >= 0)
  75744. return false; // reflex, can't be an ear
  75745. // triangle bbox; min & max are calculated like this for speed
  75746. 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);
  75747. // z-order range for the current triangle bbox;
  75748. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  75749. // first look for points inside the triangle in increasing z-order
  75750. var p = ear.nextZ;
  75751. while (p && p.z <= maxZ) {
  75752. if (p !== ear.prev &&
  75753. p !== ear.next &&
  75754. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75755. area(p.prev, p, p.next) >= 0)
  75756. return false;
  75757. p = p.nextZ;
  75758. }
  75759. // then look for points in decreasing z-order
  75760. p = ear.prevZ;
  75761. while (p && p.z >= minZ) {
  75762. if (p !== ear.prev &&
  75763. p !== ear.next &&
  75764. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75765. area(p.prev, p, p.next) >= 0)
  75766. return false;
  75767. p = p.prevZ;
  75768. }
  75769. return true;
  75770. }
  75771. // go through all polygon nodes and cure small local self-intersections
  75772. function cureLocalIntersections(start, triangles, dim) {
  75773. var p = start;
  75774. do {
  75775. var a = p.prev, b = p.next.next;
  75776. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  75777. triangles.push(a.i / dim);
  75778. triangles.push(p.i / dim);
  75779. triangles.push(b.i / dim);
  75780. // remove two nodes involved
  75781. removeNode(p);
  75782. removeNode(p.next);
  75783. p = start = b;
  75784. }
  75785. p = p.next;
  75786. } while (p !== start);
  75787. return p;
  75788. }
  75789. // try splitting polygon into two and triangulate them independently
  75790. function splitEarcut(start, triangles, dim, minX, minY, size) {
  75791. // look for a valid diagonal that divides the polygon into two
  75792. var a = start;
  75793. do {
  75794. var b = a.next.next;
  75795. while (b !== a.prev) {
  75796. if (a.i !== b.i && isValidDiagonal(a, b)) {
  75797. // split the polygon in two by the diagonal
  75798. var c = splitPolygon(a, b);
  75799. // filter colinear points around the cuts
  75800. a = filterPoints(a, a.next);
  75801. c = filterPoints(c, c.next);
  75802. // run earcut on each half
  75803. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  75804. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  75805. return;
  75806. }
  75807. b = b.next;
  75808. }
  75809. a = a.next;
  75810. } while (a !== start);
  75811. }
  75812. // link every hole into the outer loop, producing a single-ring polygon without holes
  75813. function eliminateHoles(data, holeIndices, outerNode, dim) {
  75814. var queue = [], i, len, start, end, list;
  75815. for (i = 0, len = holeIndices.length; i < len; i++) {
  75816. start = holeIndices[i] * dim;
  75817. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75818. list = linkedList(data, start, end, dim, false);
  75819. if (list === list.next)
  75820. list.steiner = true;
  75821. queue.push(getLeftmost(list));
  75822. }
  75823. queue.sort(compareX);
  75824. // process holes from left to right
  75825. for (i = 0; i < queue.length; i++) {
  75826. eliminateHole(queue[i], outerNode);
  75827. outerNode = filterPoints(outerNode, outerNode.next);
  75828. }
  75829. return outerNode;
  75830. }
  75831. function compareX(a, b) {
  75832. return a.x - b.x;
  75833. }
  75834. // find a bridge between vertices that connects hole with an outer ring and and link it
  75835. function eliminateHole(hole, outerNode) {
  75836. outerNode = findHoleBridge(hole, outerNode);
  75837. if (outerNode) {
  75838. var b = splitPolygon(outerNode, hole);
  75839. filterPoints(b, b.next);
  75840. }
  75841. }
  75842. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  75843. function findHoleBridge(hole, outerNode) {
  75844. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  75845. // find a segment intersected by a ray from the hole's leftmost point to the left;
  75846. // segment's endpoint with lesser x will be potential connection point
  75847. do {
  75848. if (hy <= p.y && hy >= p.next.y) {
  75849. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  75850. if (x <= hx && x > qx) {
  75851. qx = x;
  75852. if (x === hx) {
  75853. if (hy === p.y)
  75854. return p;
  75855. if (hy === p.next.y)
  75856. return p.next;
  75857. }
  75858. m = p.x < p.next.x ? p : p.next;
  75859. }
  75860. }
  75861. p = p.next;
  75862. } while (p !== outerNode);
  75863. if (!m)
  75864. return null;
  75865. if (hx === qx)
  75866. return m.prev; // hole touches outer segment; pick lower endpoint
  75867. // look for points inside the triangle of hole point, segment intersection and endpoint;
  75868. // if there are no points found, we have a valid connection;
  75869. // otherwise choose the point of the minimum angle with the ray as connection point
  75870. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  75871. p = m.next;
  75872. while (p !== stop) {
  75873. if (hx >= p.x &&
  75874. p.x >= mx &&
  75875. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  75876. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  75877. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  75878. m = p;
  75879. tanMin = tan;
  75880. }
  75881. }
  75882. p = p.next;
  75883. }
  75884. return m;
  75885. }
  75886. // interlink polygon nodes in z-order
  75887. function indexCurve(start, minX, minY, size) {
  75888. var p = start;
  75889. do {
  75890. if (p.z === null)
  75891. p.z = zOrder(p.x, p.y, minX, minY, size);
  75892. p.prevZ = p.prev;
  75893. p.nextZ = p.next;
  75894. p = p.next;
  75895. } while (p !== start);
  75896. p.prevZ.nextZ = null;
  75897. p.prevZ = null;
  75898. sortLinked(p);
  75899. }
  75900. // Simon Tatham's linked list merge sort algorithm
  75901. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  75902. function sortLinked(list) {
  75903. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  75904. do {
  75905. p = list;
  75906. list = null;
  75907. tail = null;
  75908. numMerges = 0;
  75909. while (p) {
  75910. numMerges++;
  75911. q = p;
  75912. pSize = 0;
  75913. for (i = 0; i < inSize; i++) {
  75914. pSize++;
  75915. q = q.nextZ;
  75916. if (!q)
  75917. break;
  75918. }
  75919. qSize = inSize;
  75920. while (pSize > 0 || (qSize > 0 && q)) {
  75921. if (pSize === 0) {
  75922. e = q;
  75923. q = q.nextZ;
  75924. qSize--;
  75925. }
  75926. else if (qSize === 0 || !q) {
  75927. e = p;
  75928. p = p.nextZ;
  75929. pSize--;
  75930. }
  75931. else if (p.z <= q.z) {
  75932. e = p;
  75933. p = p.nextZ;
  75934. pSize--;
  75935. }
  75936. else {
  75937. e = q;
  75938. q = q.nextZ;
  75939. qSize--;
  75940. }
  75941. if (tail)
  75942. tail.nextZ = e;
  75943. else
  75944. list = e;
  75945. e.prevZ = tail;
  75946. tail = e;
  75947. }
  75948. p = q;
  75949. }
  75950. tail.nextZ = null;
  75951. inSize *= 2;
  75952. } while (numMerges > 1);
  75953. return list;
  75954. }
  75955. // z-order of a point given coords and size of the data bounding box
  75956. function zOrder(x, y, minX, minY, size) {
  75957. // coords are transformed into non-negative 15-bit integer range
  75958. x = 32767 * (x - minX) / size;
  75959. y = 32767 * (y - minY) / size;
  75960. x = (x | (x << 8)) & 0x00FF00FF;
  75961. x = (x | (x << 4)) & 0x0F0F0F0F;
  75962. x = (x | (x << 2)) & 0x33333333;
  75963. x = (x | (x << 1)) & 0x55555555;
  75964. y = (y | (y << 8)) & 0x00FF00FF;
  75965. y = (y | (y << 4)) & 0x0F0F0F0F;
  75966. y = (y | (y << 2)) & 0x33333333;
  75967. y = (y | (y << 1)) & 0x55555555;
  75968. return x | (y << 1);
  75969. }
  75970. // find the leftmost node of a polygon ring
  75971. function getLeftmost(start) {
  75972. var p = start, leftmost = start;
  75973. do {
  75974. if (p.x < leftmost.x)
  75975. leftmost = p;
  75976. p = p.next;
  75977. } while (p !== start);
  75978. return leftmost;
  75979. }
  75980. // check if a point lies within a convex triangle
  75981. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  75982. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  75983. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  75984. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  75985. }
  75986. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  75987. function isValidDiagonal(a, b) {
  75988. return a.next.i !== b.i &&
  75989. a.prev.i !== b.i &&
  75990. !intersectsPolygon(a, b) &&
  75991. locallyInside(a, b) &&
  75992. locallyInside(b, a) &&
  75993. middleInside(a, b);
  75994. }
  75995. // signed area of a triangle
  75996. function area(p, q, r) {
  75997. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  75998. }
  75999. // check if two points are equal
  76000. function equals(p1, p2) {
  76001. return p1.x === p2.x && p1.y === p2.y;
  76002. }
  76003. // check if two segments intersect
  76004. function intersects(p1, q1, p2, q2) {
  76005. if ((equals(p1, q1) && equals(p2, q2)) ||
  76006. (equals(p1, q2) && equals(p2, q1)))
  76007. return true;
  76008. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  76009. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  76010. }
  76011. // check if a polygon diagonal intersects any polygon segments
  76012. function intersectsPolygon(a, b) {
  76013. var p = a;
  76014. do {
  76015. if (p.i !== a.i &&
  76016. p.next.i !== a.i &&
  76017. p.i !== b.i &&
  76018. p.next.i !== b.i &&
  76019. intersects(p, p.next, a, b))
  76020. return true;
  76021. p = p.next;
  76022. } while (p !== a);
  76023. return false;
  76024. }
  76025. // check if a polygon diagonal is locally inside the polygon
  76026. function locallyInside(a, b) {
  76027. return area(a.prev, a, a.next) < 0
  76028. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  76029. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  76030. }
  76031. // check if the middle point of a polygon diagonal is inside the polygon
  76032. function middleInside(a, b) {
  76033. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  76034. do {
  76035. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  76036. inside = !inside;
  76037. p = p.next;
  76038. } while (p !== a);
  76039. return inside;
  76040. }
  76041. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  76042. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  76043. function splitPolygon(a, b) {
  76044. 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;
  76045. a.next = b;
  76046. b.prev = a;
  76047. a2.next = an;
  76048. an.prev = a2;
  76049. b2.next = a2;
  76050. a2.prev = b2;
  76051. bp.next = b2;
  76052. b2.prev = bp;
  76053. return b2;
  76054. }
  76055. // create a node and optionally link it with previous one (in a circular doubly linked list)
  76056. function insertNode(i, x, y, last) {
  76057. var p = new Node(i, x, y);
  76058. if (!last) {
  76059. p.prev = p;
  76060. p.next = p;
  76061. }
  76062. else {
  76063. p.next = last.next;
  76064. p.prev = last;
  76065. last.next.prev = p;
  76066. last.next = p;
  76067. }
  76068. return p;
  76069. }
  76070. function removeNode(p) {
  76071. p.next.prev = p.prev;
  76072. p.prev.next = p.next;
  76073. if (p.prevZ)
  76074. p.prevZ.nextZ = p.nextZ;
  76075. if (p.nextZ)
  76076. p.nextZ.prevZ = p.prevZ;
  76077. }
  76078. /**
  76079. * return a percentage difference between the polygon area and its triangulation area;
  76080. * used to verify correctness of triangulation
  76081. */
  76082. function deviation(data, holeIndices, dim, triangles) {
  76083. var hasHoles = holeIndices && holeIndices.length;
  76084. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  76085. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  76086. if (hasHoles) {
  76087. for (var i = 0, len = holeIndices.length; i < len; i++) {
  76088. var start = holeIndices[i] * dim;
  76089. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  76090. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  76091. }
  76092. }
  76093. var trianglesArea = 0;
  76094. for (i = 0; i < triangles.length; i += 3) {
  76095. var a = triangles[i] * dim;
  76096. var b = triangles[i + 1] * dim;
  76097. var c = triangles[i + 2] * dim;
  76098. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  76099. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  76100. }
  76101. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  76102. }
  76103. Earcut.deviation = deviation;
  76104. ;
  76105. function signedArea(data, start, end, dim) {
  76106. var sum = 0;
  76107. for (var i = start, j = end - dim; i < end; i += dim) {
  76108. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  76109. j = i;
  76110. }
  76111. return sum;
  76112. }
  76113. /**
  76114. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  76115. */
  76116. function flatten(data) {
  76117. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  76118. for (var i = 0; i < data.length; i++) {
  76119. for (var j = 0; j < data[i].length; j++) {
  76120. for (var d = 0; d < dim; d++)
  76121. result.vertices.push(data[i][j][d]);
  76122. }
  76123. if (i > 0) {
  76124. holeIndex += data[i - 1].length;
  76125. result.holes.push(holeIndex);
  76126. }
  76127. }
  76128. return result;
  76129. }
  76130. Earcut.flatten = flatten;
  76131. ;
  76132. })(Earcut || (Earcut = {}));
  76133. //# sourceMappingURL=babylon.earcut.js.map
  76134. "use strict";
  76135. var BABYLON;
  76136. (function (BABYLON) {
  76137. var IndexedVector2 = /** @class */ (function (_super) {
  76138. __extends(IndexedVector2, _super);
  76139. function IndexedVector2(original, index) {
  76140. var _this = _super.call(this, original.x, original.y) || this;
  76141. _this.index = index;
  76142. return _this;
  76143. }
  76144. return IndexedVector2;
  76145. }(BABYLON.Vector2));
  76146. var PolygonPoints = /** @class */ (function () {
  76147. function PolygonPoints() {
  76148. this.elements = new Array();
  76149. }
  76150. PolygonPoints.prototype.add = function (originalPoints) {
  76151. var _this = this;
  76152. var result = new Array();
  76153. originalPoints.forEach(function (point) {
  76154. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  76155. var newPoint = new IndexedVector2(point, _this.elements.length);
  76156. result.push(newPoint);
  76157. _this.elements.push(newPoint);
  76158. }
  76159. });
  76160. return result;
  76161. };
  76162. PolygonPoints.prototype.computeBounds = function () {
  76163. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76164. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76165. this.elements.forEach(function (point) {
  76166. // x
  76167. if (point.x < lmin.x) {
  76168. lmin.x = point.x;
  76169. }
  76170. else if (point.x > lmax.x) {
  76171. lmax.x = point.x;
  76172. }
  76173. // y
  76174. if (point.y < lmin.y) {
  76175. lmin.y = point.y;
  76176. }
  76177. else if (point.y > lmax.y) {
  76178. lmax.y = point.y;
  76179. }
  76180. });
  76181. return {
  76182. min: lmin,
  76183. max: lmax,
  76184. width: lmax.x - lmin.x,
  76185. height: lmax.y - lmin.y
  76186. };
  76187. };
  76188. return PolygonPoints;
  76189. }());
  76190. var Polygon = /** @class */ (function () {
  76191. function Polygon() {
  76192. }
  76193. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  76194. return [
  76195. new BABYLON.Vector2(xmin, ymin),
  76196. new BABYLON.Vector2(xmax, ymin),
  76197. new BABYLON.Vector2(xmax, ymax),
  76198. new BABYLON.Vector2(xmin, ymax)
  76199. ];
  76200. };
  76201. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  76202. if (cx === void 0) { cx = 0; }
  76203. if (cy === void 0) { cy = 0; }
  76204. if (numberOfSides === void 0) { numberOfSides = 32; }
  76205. var result = new Array();
  76206. var angle = 0;
  76207. var increment = (Math.PI * 2) / numberOfSides;
  76208. for (var i = 0; i < numberOfSides; i++) {
  76209. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  76210. angle -= increment;
  76211. }
  76212. return result;
  76213. };
  76214. Polygon.Parse = function (input) {
  76215. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  76216. var i, result = [];
  76217. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  76218. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  76219. }
  76220. return result;
  76221. };
  76222. Polygon.StartingAt = function (x, y) {
  76223. return BABYLON.Path2.StartingAt(x, y);
  76224. };
  76225. return Polygon;
  76226. }());
  76227. BABYLON.Polygon = Polygon;
  76228. var PolygonMeshBuilder = /** @class */ (function () {
  76229. function PolygonMeshBuilder(name, contours, scene) {
  76230. this._points = new PolygonPoints();
  76231. this._outlinepoints = new PolygonPoints();
  76232. this._holes = new Array();
  76233. this._epoints = new Array();
  76234. this._eholes = new Array();
  76235. this._name = name;
  76236. this._scene = scene;
  76237. var points;
  76238. if (contours instanceof BABYLON.Path2) {
  76239. points = contours.getPoints();
  76240. }
  76241. else {
  76242. points = contours;
  76243. }
  76244. this._addToepoint(points);
  76245. this._points.add(points);
  76246. this._outlinepoints.add(points);
  76247. }
  76248. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  76249. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  76250. var p = points_1[_i];
  76251. this._epoints.push(p.x, p.y);
  76252. }
  76253. };
  76254. PolygonMeshBuilder.prototype.addHole = function (hole) {
  76255. this._points.add(hole);
  76256. var holepoints = new PolygonPoints();
  76257. holepoints.add(hole);
  76258. this._holes.push(holepoints);
  76259. this._eholes.push(this._epoints.length / 2);
  76260. this._addToepoint(hole);
  76261. return this;
  76262. };
  76263. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  76264. var _this = this;
  76265. if (updatable === void 0) { updatable = false; }
  76266. if (depth === void 0) { depth = 0; }
  76267. var result = new BABYLON.Mesh(this._name, this._scene);
  76268. var normals = new Array();
  76269. var positions = new Array();
  76270. var uvs = new Array();
  76271. var bounds = this._points.computeBounds();
  76272. this._points.elements.forEach(function (p) {
  76273. normals.push(0, 1.0, 0);
  76274. positions.push(p.x, 0, p.y);
  76275. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  76276. });
  76277. var indices = new Array();
  76278. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  76279. for (var i = 0; i < res.length; i++) {
  76280. indices.push(res[i]);
  76281. }
  76282. if (depth > 0) {
  76283. var positionscount = (positions.length / 3); //get the current pointcount
  76284. this._points.elements.forEach(function (p) {
  76285. normals.push(0, -1.0, 0);
  76286. positions.push(p.x, -depth, p.y);
  76287. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  76288. });
  76289. var totalCount = indices.length;
  76290. for (var i = 0; i < totalCount; i += 3) {
  76291. var i0 = indices[i + 0];
  76292. var i1 = indices[i + 1];
  76293. var i2 = indices[i + 2];
  76294. indices.push(i2 + positionscount);
  76295. indices.push(i1 + positionscount);
  76296. indices.push(i0 + positionscount);
  76297. }
  76298. //Add the sides
  76299. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  76300. this._holes.forEach(function (hole) {
  76301. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  76302. });
  76303. }
  76304. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  76305. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  76306. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  76307. result.setIndices(indices);
  76308. return result;
  76309. };
  76310. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  76311. var StartIndex = positions.length / 3;
  76312. var ulength = 0;
  76313. for (var i = 0; i < points.elements.length; i++) {
  76314. var p = points.elements[i];
  76315. var p1;
  76316. if ((i + 1) > points.elements.length - 1) {
  76317. p1 = points.elements[0];
  76318. }
  76319. else {
  76320. p1 = points.elements[i + 1];
  76321. }
  76322. positions.push(p.x, 0, p.y);
  76323. positions.push(p.x, -depth, p.y);
  76324. positions.push(p1.x, 0, p1.y);
  76325. positions.push(p1.x, -depth, p1.y);
  76326. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  76327. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  76328. var v3 = v2.subtract(v1);
  76329. var v4 = new BABYLON.Vector3(0, 1, 0);
  76330. var vn = BABYLON.Vector3.Cross(v3, v4);
  76331. vn = vn.normalize();
  76332. uvs.push(ulength / bounds.width, 0);
  76333. uvs.push(ulength / bounds.width, 1);
  76334. ulength += v3.length();
  76335. uvs.push((ulength / bounds.width), 0);
  76336. uvs.push((ulength / bounds.width), 1);
  76337. if (!flip) {
  76338. normals.push(-vn.x, -vn.y, -vn.z);
  76339. normals.push(-vn.x, -vn.y, -vn.z);
  76340. normals.push(-vn.x, -vn.y, -vn.z);
  76341. normals.push(-vn.x, -vn.y, -vn.z);
  76342. indices.push(StartIndex);
  76343. indices.push(StartIndex + 1);
  76344. indices.push(StartIndex + 2);
  76345. indices.push(StartIndex + 1);
  76346. indices.push(StartIndex + 3);
  76347. indices.push(StartIndex + 2);
  76348. }
  76349. else {
  76350. normals.push(vn.x, vn.y, vn.z);
  76351. normals.push(vn.x, vn.y, vn.z);
  76352. normals.push(vn.x, vn.y, vn.z);
  76353. normals.push(vn.x, vn.y, vn.z);
  76354. indices.push(StartIndex);
  76355. indices.push(StartIndex + 2);
  76356. indices.push(StartIndex + 1);
  76357. indices.push(StartIndex + 1);
  76358. indices.push(StartIndex + 2);
  76359. indices.push(StartIndex + 3);
  76360. }
  76361. StartIndex += 4;
  76362. }
  76363. ;
  76364. };
  76365. return PolygonMeshBuilder;
  76366. }());
  76367. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76368. })(BABYLON || (BABYLON = {}));
  76369. //# sourceMappingURL=babylon.polygonMesh.js.map
  76370. "use strict";
  76371. var BABYLON;
  76372. (function (BABYLON) {
  76373. // Unique ID when we import meshes from Babylon to CSG
  76374. var currentCSGMeshId = 0;
  76375. // # class Vertex
  76376. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76377. // one to provide additional features like texture coordinates and vertex
  76378. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76379. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76380. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76381. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76382. // is not used anywhere else.
  76383. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76384. var Vertex = /** @class */ (function () {
  76385. function Vertex(pos, normal, uv) {
  76386. this.pos = pos;
  76387. this.normal = normal;
  76388. this.uv = uv;
  76389. }
  76390. Vertex.prototype.clone = function () {
  76391. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76392. };
  76393. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76394. // orientation of a polygon is flipped.
  76395. Vertex.prototype.flip = function () {
  76396. this.normal = this.normal.scale(-1);
  76397. };
  76398. // Create a new vertex between this vertex and `other` by linearly
  76399. // interpolating all properties using a parameter of `t`. Subclasses should
  76400. // override this to interpolate additional properties.
  76401. Vertex.prototype.interpolate = function (other, t) {
  76402. 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));
  76403. };
  76404. return Vertex;
  76405. }());
  76406. // # class Plane
  76407. // Represents a plane in 3D space.
  76408. var Plane = /** @class */ (function () {
  76409. function Plane(normal, w) {
  76410. this.normal = normal;
  76411. this.w = w;
  76412. }
  76413. Plane.FromPoints = function (a, b, c) {
  76414. var v0 = c.subtract(a);
  76415. var v1 = b.subtract(a);
  76416. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76417. return null;
  76418. }
  76419. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76420. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76421. };
  76422. Plane.prototype.clone = function () {
  76423. return new Plane(this.normal.clone(), this.w);
  76424. };
  76425. Plane.prototype.flip = function () {
  76426. this.normal.scaleInPlace(-1);
  76427. this.w = -this.w;
  76428. };
  76429. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76430. // fragments in the appropriate lists. Coplanar polygons go into either
  76431. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76432. // respect to this plane. Polygons in front or in back of this plane go into
  76433. // either `front` or `back`.
  76434. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76435. var COPLANAR = 0;
  76436. var FRONT = 1;
  76437. var BACK = 2;
  76438. var SPANNING = 3;
  76439. // Classify each point as well as the entire polygon into one of the above
  76440. // four classes.
  76441. var polygonType = 0;
  76442. var types = [];
  76443. var i;
  76444. var t;
  76445. for (i = 0; i < polygon.vertices.length; i++) {
  76446. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76447. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76448. polygonType |= type;
  76449. types.push(type);
  76450. }
  76451. // Put the polygon in the correct list, splitting it when necessary.
  76452. switch (polygonType) {
  76453. case COPLANAR:
  76454. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76455. break;
  76456. case FRONT:
  76457. front.push(polygon);
  76458. break;
  76459. case BACK:
  76460. back.push(polygon);
  76461. break;
  76462. case SPANNING:
  76463. var f = [], b = [];
  76464. for (i = 0; i < polygon.vertices.length; i++) {
  76465. var j = (i + 1) % polygon.vertices.length;
  76466. var ti = types[i], tj = types[j];
  76467. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76468. if (ti !== BACK)
  76469. f.push(vi);
  76470. if (ti !== FRONT)
  76471. b.push(ti !== BACK ? vi.clone() : vi);
  76472. if ((ti | tj) === SPANNING) {
  76473. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76474. var v = vi.interpolate(vj, t);
  76475. f.push(v);
  76476. b.push(v.clone());
  76477. }
  76478. }
  76479. var poly;
  76480. if (f.length >= 3) {
  76481. poly = new Polygon(f, polygon.shared);
  76482. if (poly.plane)
  76483. front.push(poly);
  76484. }
  76485. if (b.length >= 3) {
  76486. poly = new Polygon(b, polygon.shared);
  76487. if (poly.plane)
  76488. back.push(poly);
  76489. }
  76490. break;
  76491. }
  76492. };
  76493. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76494. // point is on the plane.
  76495. Plane.EPSILON = 1e-5;
  76496. return Plane;
  76497. }());
  76498. // # class Polygon
  76499. // Represents a convex polygon. The vertices used to initialize a polygon must
  76500. // be coplanar and form a convex loop.
  76501. //
  76502. // Each convex polygon has a `shared` property, which is shared between all
  76503. // polygons that are clones of each other or were split from the same polygon.
  76504. // This can be used to define per-polygon properties (such as surface color).
  76505. var Polygon = /** @class */ (function () {
  76506. function Polygon(vertices, shared) {
  76507. this.vertices = vertices;
  76508. this.shared = shared;
  76509. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76510. }
  76511. Polygon.prototype.clone = function () {
  76512. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76513. return new Polygon(vertices, this.shared);
  76514. };
  76515. Polygon.prototype.flip = function () {
  76516. this.vertices.reverse().map(function (v) { v.flip(); });
  76517. this.plane.flip();
  76518. };
  76519. return Polygon;
  76520. }());
  76521. // # class Node
  76522. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76523. // by picking a polygon to split along. That polygon (and all other coplanar
  76524. // polygons) are added directly to that node and the other polygons are added to
  76525. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76526. // no distinction between internal and leaf nodes.
  76527. var Node = /** @class */ (function () {
  76528. function Node(polygons) {
  76529. this.plane = null;
  76530. this.front = null;
  76531. this.back = null;
  76532. this.polygons = new Array();
  76533. if (polygons) {
  76534. this.build(polygons);
  76535. }
  76536. }
  76537. Node.prototype.clone = function () {
  76538. var node = new Node();
  76539. node.plane = this.plane && this.plane.clone();
  76540. node.front = this.front && this.front.clone();
  76541. node.back = this.back && this.back.clone();
  76542. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76543. return node;
  76544. };
  76545. // Convert solid space to empty space and empty space to solid space.
  76546. Node.prototype.invert = function () {
  76547. for (var i = 0; i < this.polygons.length; i++) {
  76548. this.polygons[i].flip();
  76549. }
  76550. if (this.plane) {
  76551. this.plane.flip();
  76552. }
  76553. if (this.front) {
  76554. this.front.invert();
  76555. }
  76556. if (this.back) {
  76557. this.back.invert();
  76558. }
  76559. var temp = this.front;
  76560. this.front = this.back;
  76561. this.back = temp;
  76562. };
  76563. // Recursively remove all polygons in `polygons` that are inside this BSP
  76564. // tree.
  76565. Node.prototype.clipPolygons = function (polygons) {
  76566. if (!this.plane)
  76567. return polygons.slice();
  76568. var front = new Array(), back = new Array();
  76569. for (var i = 0; i < polygons.length; i++) {
  76570. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76571. }
  76572. if (this.front) {
  76573. front = this.front.clipPolygons(front);
  76574. }
  76575. if (this.back) {
  76576. back = this.back.clipPolygons(back);
  76577. }
  76578. else {
  76579. back = [];
  76580. }
  76581. return front.concat(back);
  76582. };
  76583. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76584. // `bsp`.
  76585. Node.prototype.clipTo = function (bsp) {
  76586. this.polygons = bsp.clipPolygons(this.polygons);
  76587. if (this.front)
  76588. this.front.clipTo(bsp);
  76589. if (this.back)
  76590. this.back.clipTo(bsp);
  76591. };
  76592. // Return a list of all polygons in this BSP tree.
  76593. Node.prototype.allPolygons = function () {
  76594. var polygons = this.polygons.slice();
  76595. if (this.front)
  76596. polygons = polygons.concat(this.front.allPolygons());
  76597. if (this.back)
  76598. polygons = polygons.concat(this.back.allPolygons());
  76599. return polygons;
  76600. };
  76601. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76602. // new polygons are filtered down to the bottom of the tree and become new
  76603. // nodes there. Each set of polygons is partitioned using the first polygon
  76604. // (no heuristic is used to pick a good split).
  76605. Node.prototype.build = function (polygons) {
  76606. if (!polygons.length)
  76607. return;
  76608. if (!this.plane)
  76609. this.plane = polygons[0].plane.clone();
  76610. var front = new Array(), back = new Array();
  76611. for (var i = 0; i < polygons.length; i++) {
  76612. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76613. }
  76614. if (front.length) {
  76615. if (!this.front)
  76616. this.front = new Node();
  76617. this.front.build(front);
  76618. }
  76619. if (back.length) {
  76620. if (!this.back)
  76621. this.back = new Node();
  76622. this.back.build(back);
  76623. }
  76624. };
  76625. return Node;
  76626. }());
  76627. var CSG = /** @class */ (function () {
  76628. function CSG() {
  76629. this.polygons = new Array();
  76630. }
  76631. // Convert BABYLON.Mesh to BABYLON.CSG
  76632. CSG.FromMesh = function (mesh) {
  76633. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76634. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76635. if (mesh instanceof BABYLON.Mesh) {
  76636. mesh.computeWorldMatrix(true);
  76637. matrix = mesh.getWorldMatrix();
  76638. meshPosition = mesh.position.clone();
  76639. meshRotation = mesh.rotation.clone();
  76640. if (mesh.rotationQuaternion) {
  76641. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76642. }
  76643. meshScaling = mesh.scaling.clone();
  76644. }
  76645. else {
  76646. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76647. }
  76648. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76649. var subMeshes = mesh.subMeshes;
  76650. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76651. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76652. vertices = [];
  76653. for (var j = 0; j < 3; j++) {
  76654. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76655. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76656. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76657. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76658. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76659. vertex = new Vertex(position, normal, uv);
  76660. vertices.push(vertex);
  76661. }
  76662. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76663. // To handle the case of degenerated triangle
  76664. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76665. if (polygon.plane)
  76666. polygons.push(polygon);
  76667. }
  76668. }
  76669. var csg = CSG.FromPolygons(polygons);
  76670. csg.matrix = matrix;
  76671. csg.position = meshPosition;
  76672. csg.rotation = meshRotation;
  76673. csg.scaling = meshScaling;
  76674. csg.rotationQuaternion = meshRotationQuaternion;
  76675. currentCSGMeshId++;
  76676. return csg;
  76677. };
  76678. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76679. CSG.FromPolygons = function (polygons) {
  76680. var csg = new CSG();
  76681. csg.polygons = polygons;
  76682. return csg;
  76683. };
  76684. CSG.prototype.clone = function () {
  76685. var csg = new CSG();
  76686. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76687. csg.copyTransformAttributes(this);
  76688. return csg;
  76689. };
  76690. CSG.prototype.union = function (csg) {
  76691. var a = new Node(this.clone().polygons);
  76692. var b = new Node(csg.clone().polygons);
  76693. a.clipTo(b);
  76694. b.clipTo(a);
  76695. b.invert();
  76696. b.clipTo(a);
  76697. b.invert();
  76698. a.build(b.allPolygons());
  76699. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76700. };
  76701. CSG.prototype.unionInPlace = function (csg) {
  76702. var a = new Node(this.polygons);
  76703. var b = new Node(csg.polygons);
  76704. a.clipTo(b);
  76705. b.clipTo(a);
  76706. b.invert();
  76707. b.clipTo(a);
  76708. b.invert();
  76709. a.build(b.allPolygons());
  76710. this.polygons = a.allPolygons();
  76711. };
  76712. CSG.prototype.subtract = function (csg) {
  76713. var a = new Node(this.clone().polygons);
  76714. var b = new Node(csg.clone().polygons);
  76715. a.invert();
  76716. a.clipTo(b);
  76717. b.clipTo(a);
  76718. b.invert();
  76719. b.clipTo(a);
  76720. b.invert();
  76721. a.build(b.allPolygons());
  76722. a.invert();
  76723. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76724. };
  76725. CSG.prototype.subtractInPlace = function (csg) {
  76726. var a = new Node(this.polygons);
  76727. var b = new Node(csg.polygons);
  76728. a.invert();
  76729. a.clipTo(b);
  76730. b.clipTo(a);
  76731. b.invert();
  76732. b.clipTo(a);
  76733. b.invert();
  76734. a.build(b.allPolygons());
  76735. a.invert();
  76736. this.polygons = a.allPolygons();
  76737. };
  76738. CSG.prototype.intersect = function (csg) {
  76739. var a = new Node(this.clone().polygons);
  76740. var b = new Node(csg.clone().polygons);
  76741. a.invert();
  76742. b.clipTo(a);
  76743. b.invert();
  76744. a.clipTo(b);
  76745. b.clipTo(a);
  76746. a.build(b.allPolygons());
  76747. a.invert();
  76748. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76749. };
  76750. CSG.prototype.intersectInPlace = function (csg) {
  76751. var a = new Node(this.polygons);
  76752. var b = new Node(csg.polygons);
  76753. a.invert();
  76754. b.clipTo(a);
  76755. b.invert();
  76756. a.clipTo(b);
  76757. b.clipTo(a);
  76758. a.build(b.allPolygons());
  76759. a.invert();
  76760. this.polygons = a.allPolygons();
  76761. };
  76762. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76763. // not modified.
  76764. CSG.prototype.inverse = function () {
  76765. var csg = this.clone();
  76766. csg.inverseInPlace();
  76767. return csg;
  76768. };
  76769. CSG.prototype.inverseInPlace = function () {
  76770. this.polygons.map(function (p) { p.flip(); });
  76771. };
  76772. // This is used to keep meshes transformations so they can be restored
  76773. // when we build back a Babylon Mesh
  76774. // NB : All CSG operations are performed in world coordinates
  76775. CSG.prototype.copyTransformAttributes = function (csg) {
  76776. this.matrix = csg.matrix;
  76777. this.position = csg.position;
  76778. this.rotation = csg.rotation;
  76779. this.scaling = csg.scaling;
  76780. this.rotationQuaternion = csg.rotationQuaternion;
  76781. return this;
  76782. };
  76783. // Build Raw mesh from CSG
  76784. // Coordinates here are in world space
  76785. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76786. var matrix = this.matrix.clone();
  76787. matrix.invert();
  76788. 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;
  76789. if (keepSubMeshes) {
  76790. // Sort Polygons, since subMeshes are indices range
  76791. polygons.sort(function (a, b) {
  76792. if (a.shared.meshId === b.shared.meshId) {
  76793. return a.shared.subMeshId - b.shared.subMeshId;
  76794. }
  76795. else {
  76796. return a.shared.meshId - b.shared.meshId;
  76797. }
  76798. });
  76799. }
  76800. for (var i = 0, il = polygons.length; i < il; i++) {
  76801. polygon = polygons[i];
  76802. // Building SubMeshes
  76803. if (!subMesh_dict[polygon.shared.meshId]) {
  76804. subMesh_dict[polygon.shared.meshId] = {};
  76805. }
  76806. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76807. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76808. indexStart: +Infinity,
  76809. indexEnd: -Infinity,
  76810. materialIndex: polygon.shared.materialIndex
  76811. };
  76812. }
  76813. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76814. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76815. polygonIndices[0] = 0;
  76816. polygonIndices[1] = j - 1;
  76817. polygonIndices[2] = j;
  76818. for (var k = 0; k < 3; k++) {
  76819. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76820. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76821. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76822. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76823. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76824. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76825. // Check if 2 points can be merged
  76826. if (!(typeof vertex_idx !== 'undefined' &&
  76827. normals[vertex_idx * 3] === localNormal.x &&
  76828. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76829. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76830. uvs[vertex_idx * 2] === uv.x &&
  76831. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76832. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  76833. uvs.push(uv.x, uv.y);
  76834. normals.push(normal.x, normal.y, normal.z);
  76835. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  76836. }
  76837. indices.push(vertex_idx);
  76838. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  76839. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  76840. currentIndex++;
  76841. }
  76842. }
  76843. }
  76844. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  76845. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  76846. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  76847. mesh.setIndices(indices, null);
  76848. if (keepSubMeshes) {
  76849. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  76850. var materialIndexOffset = 0, materialMaxIndex;
  76851. mesh.subMeshes = new Array();
  76852. for (var m in subMesh_dict) {
  76853. materialMaxIndex = -1;
  76854. for (var sm in subMesh_dict[m]) {
  76855. subMesh_obj = subMesh_dict[m][sm];
  76856. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  76857. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  76858. }
  76859. materialIndexOffset += ++materialMaxIndex;
  76860. }
  76861. }
  76862. return mesh;
  76863. };
  76864. // Build Mesh from CSG taking material and transforms into account
  76865. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  76866. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  76867. mesh.material = material;
  76868. mesh.position.copyFrom(this.position);
  76869. mesh.rotation.copyFrom(this.rotation);
  76870. if (this.rotationQuaternion) {
  76871. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  76872. }
  76873. mesh.scaling.copyFrom(this.scaling);
  76874. mesh.computeWorldMatrix(true);
  76875. return mesh;
  76876. };
  76877. return CSG;
  76878. }());
  76879. BABYLON.CSG = CSG;
  76880. })(BABYLON || (BABYLON = {}));
  76881. //# sourceMappingURL=babylon.csg.js.map
  76882. "use strict";
  76883. var BABYLON;
  76884. (function (BABYLON) {
  76885. var LensFlare = /** @class */ (function () {
  76886. function LensFlare(size, position, color, imgUrl, system) {
  76887. this.size = size;
  76888. this.position = position;
  76889. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76890. this.color = color || new BABYLON.Color3(1, 1, 1);
  76891. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  76892. this._system = system;
  76893. system.lensFlares.push(this);
  76894. }
  76895. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  76896. return new LensFlare(size, position, color, imgUrl, system);
  76897. };
  76898. LensFlare.prototype.dispose = function () {
  76899. if (this.texture) {
  76900. this.texture.dispose();
  76901. }
  76902. // Remove from scene
  76903. var index = this._system.lensFlares.indexOf(this);
  76904. this._system.lensFlares.splice(index, 1);
  76905. };
  76906. ;
  76907. return LensFlare;
  76908. }());
  76909. BABYLON.LensFlare = LensFlare;
  76910. })(BABYLON || (BABYLON = {}));
  76911. //# sourceMappingURL=babylon.lensFlare.js.map
  76912. "use strict";
  76913. var BABYLON;
  76914. (function (BABYLON) {
  76915. var LensFlareSystem = /** @class */ (function () {
  76916. function LensFlareSystem(name, emitter, scene) {
  76917. this.name = name;
  76918. this.lensFlares = new Array();
  76919. this.borderLimit = 300;
  76920. this.viewportBorder = 0;
  76921. this.layerMask = 0x0FFFFFFF;
  76922. this._vertexBuffers = {};
  76923. this._isEnabled = true;
  76924. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76925. this._emitter = emitter;
  76926. this.id = name;
  76927. scene.lensFlareSystems.push(this);
  76928. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76929. var engine = scene.getEngine();
  76930. // VBO
  76931. var vertices = [];
  76932. vertices.push(1, 1);
  76933. vertices.push(-1, 1);
  76934. vertices.push(-1, -1);
  76935. vertices.push(1, -1);
  76936. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76937. // Indices
  76938. var indices = [];
  76939. indices.push(0);
  76940. indices.push(1);
  76941. indices.push(2);
  76942. indices.push(0);
  76943. indices.push(2);
  76944. indices.push(3);
  76945. this._indexBuffer = engine.createIndexBuffer(indices);
  76946. // Effects
  76947. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  76948. }
  76949. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  76950. get: function () {
  76951. return this._isEnabled;
  76952. },
  76953. set: function (value) {
  76954. this._isEnabled = value;
  76955. },
  76956. enumerable: true,
  76957. configurable: true
  76958. });
  76959. LensFlareSystem.prototype.getScene = function () {
  76960. return this._scene;
  76961. };
  76962. LensFlareSystem.prototype.getEmitter = function () {
  76963. return this._emitter;
  76964. };
  76965. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  76966. this._emitter = newEmitter;
  76967. };
  76968. LensFlareSystem.prototype.getEmitterPosition = function () {
  76969. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  76970. };
  76971. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  76972. var position = this.getEmitterPosition();
  76973. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  76974. this._positionX = position.x;
  76975. this._positionY = position.y;
  76976. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  76977. if (this.viewportBorder > 0) {
  76978. globalViewport.x -= this.viewportBorder;
  76979. globalViewport.y -= this.viewportBorder;
  76980. globalViewport.width += this.viewportBorder * 2;
  76981. globalViewport.height += this.viewportBorder * 2;
  76982. position.x += this.viewportBorder;
  76983. position.y += this.viewportBorder;
  76984. this._positionX += this.viewportBorder;
  76985. this._positionY += this.viewportBorder;
  76986. }
  76987. if (position.z > 0) {
  76988. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  76989. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  76990. return true;
  76991. }
  76992. return true;
  76993. }
  76994. return false;
  76995. };
  76996. LensFlareSystem.prototype._isVisible = function () {
  76997. if (!this._isEnabled || !this._scene.activeCamera) {
  76998. return false;
  76999. }
  77000. var emitterPosition = this.getEmitterPosition();
  77001. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  77002. var distance = direction.length();
  77003. direction.normalize();
  77004. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  77005. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  77006. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  77007. };
  77008. LensFlareSystem.prototype.render = function () {
  77009. if (!this._effect.isReady() || !this._scene.activeCamera)
  77010. return false;
  77011. var engine = this._scene.getEngine();
  77012. var viewport = this._scene.activeCamera.viewport;
  77013. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  77014. // Position
  77015. if (!this.computeEffectivePosition(globalViewport)) {
  77016. return false;
  77017. }
  77018. // Visibility
  77019. if (!this._isVisible()) {
  77020. return false;
  77021. }
  77022. // Intensity
  77023. var awayX;
  77024. var awayY;
  77025. if (this._positionX < this.borderLimit + globalViewport.x) {
  77026. awayX = this.borderLimit + globalViewport.x - this._positionX;
  77027. }
  77028. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  77029. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  77030. }
  77031. else {
  77032. awayX = 0;
  77033. }
  77034. if (this._positionY < this.borderLimit + globalViewport.y) {
  77035. awayY = this.borderLimit + globalViewport.y - this._positionY;
  77036. }
  77037. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  77038. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  77039. }
  77040. else {
  77041. awayY = 0;
  77042. }
  77043. var away = (awayX > awayY) ? awayX : awayY;
  77044. away -= this.viewportBorder;
  77045. if (away > this.borderLimit) {
  77046. away = this.borderLimit;
  77047. }
  77048. var intensity = 1.0 - (away / this.borderLimit);
  77049. if (intensity < 0) {
  77050. return false;
  77051. }
  77052. if (intensity > 1.0) {
  77053. intensity = 1.0;
  77054. }
  77055. if (this.viewportBorder > 0) {
  77056. globalViewport.x += this.viewportBorder;
  77057. globalViewport.y += this.viewportBorder;
  77058. globalViewport.width -= this.viewportBorder * 2;
  77059. globalViewport.height -= this.viewportBorder * 2;
  77060. this._positionX -= this.viewportBorder;
  77061. this._positionY -= this.viewportBorder;
  77062. }
  77063. // Position
  77064. var centerX = globalViewport.x + globalViewport.width / 2;
  77065. var centerY = globalViewport.y + globalViewport.height / 2;
  77066. var distX = centerX - this._positionX;
  77067. var distY = centerY - this._positionY;
  77068. // Effects
  77069. engine.enableEffect(this._effect);
  77070. engine.setState(false);
  77071. engine.setDepthBuffer(false);
  77072. // VBOs
  77073. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77074. // Flares
  77075. for (var index = 0; index < this.lensFlares.length; index++) {
  77076. var flare = this.lensFlares[index];
  77077. engine.setAlphaMode(flare.alphaMode);
  77078. var x = centerX - (distX * flare.position);
  77079. var y = centerY - (distY * flare.position);
  77080. var cw = flare.size;
  77081. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  77082. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  77083. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  77084. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  77085. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  77086. // Texture
  77087. this._effect.setTexture("textureSampler", flare.texture);
  77088. // Color
  77089. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  77090. // Draw order
  77091. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77092. }
  77093. engine.setDepthBuffer(true);
  77094. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77095. return true;
  77096. };
  77097. LensFlareSystem.prototype.dispose = function () {
  77098. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77099. if (vertexBuffer) {
  77100. vertexBuffer.dispose();
  77101. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77102. }
  77103. if (this._indexBuffer) {
  77104. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77105. this._indexBuffer = null;
  77106. }
  77107. while (this.lensFlares.length) {
  77108. this.lensFlares[0].dispose();
  77109. }
  77110. // Remove from scene
  77111. var index = this._scene.lensFlareSystems.indexOf(this);
  77112. this._scene.lensFlareSystems.splice(index, 1);
  77113. };
  77114. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  77115. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  77116. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  77117. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  77118. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  77119. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  77120. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  77121. var parsedFlare = parsedLensFlareSystem.flares[index];
  77122. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  77123. }
  77124. return lensFlareSystem;
  77125. };
  77126. LensFlareSystem.prototype.serialize = function () {
  77127. var serializationObject = {};
  77128. serializationObject.id = this.id;
  77129. serializationObject.name = this.name;
  77130. serializationObject.emitterId = this.getEmitter().id;
  77131. serializationObject.borderLimit = this.borderLimit;
  77132. serializationObject.flares = [];
  77133. for (var index = 0; index < this.lensFlares.length; index++) {
  77134. var flare = this.lensFlares[index];
  77135. serializationObject.flares.push({
  77136. size: flare.size,
  77137. position: flare.position,
  77138. color: flare.color.asArray(),
  77139. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  77140. });
  77141. }
  77142. return serializationObject;
  77143. };
  77144. return LensFlareSystem;
  77145. }());
  77146. BABYLON.LensFlareSystem = LensFlareSystem;
  77147. })(BABYLON || (BABYLON = {}));
  77148. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  77149. "use strict";
  77150. var BABYLON;
  77151. (function (BABYLON) {
  77152. /**
  77153. * This is a holder class for the physics joint created by the physics plugin.
  77154. * It holds a set of functions to control the underlying joint.
  77155. */
  77156. var PhysicsJoint = /** @class */ (function () {
  77157. function PhysicsJoint(type, jointData) {
  77158. this.type = type;
  77159. this.jointData = jointData;
  77160. jointData.nativeParams = jointData.nativeParams || {};
  77161. }
  77162. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  77163. get: function () {
  77164. return this._physicsJoint;
  77165. },
  77166. set: function (newJoint) {
  77167. if (this._physicsJoint) {
  77168. //remove from the wolrd
  77169. }
  77170. this._physicsJoint = newJoint;
  77171. },
  77172. enumerable: true,
  77173. configurable: true
  77174. });
  77175. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  77176. set: function (physicsPlugin) {
  77177. this._physicsPlugin = physicsPlugin;
  77178. },
  77179. enumerable: true,
  77180. configurable: true
  77181. });
  77182. /**
  77183. * Execute a function that is physics-plugin specific.
  77184. * @param {Function} func the function that will be executed.
  77185. * It accepts two parameters: the physics world and the physics joint.
  77186. */
  77187. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  77188. func(this._physicsPlugin.world, this._physicsJoint);
  77189. };
  77190. //TODO check if the native joints are the same
  77191. //Joint Types
  77192. PhysicsJoint.DistanceJoint = 0;
  77193. PhysicsJoint.HingeJoint = 1;
  77194. PhysicsJoint.BallAndSocketJoint = 2;
  77195. PhysicsJoint.WheelJoint = 3;
  77196. PhysicsJoint.SliderJoint = 4;
  77197. //OIMO
  77198. PhysicsJoint.PrismaticJoint = 5;
  77199. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  77200. PhysicsJoint.UniversalJoint = 6;
  77201. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  77202. //Cannon
  77203. //Similar to a Ball-Joint. Different in params
  77204. PhysicsJoint.PointToPointJoint = 8;
  77205. //Cannon only at the moment
  77206. PhysicsJoint.SpringJoint = 9;
  77207. PhysicsJoint.LockJoint = 10;
  77208. return PhysicsJoint;
  77209. }());
  77210. BABYLON.PhysicsJoint = PhysicsJoint;
  77211. /**
  77212. * A class representing a physics distance joint.
  77213. */
  77214. var DistanceJoint = /** @class */ (function (_super) {
  77215. __extends(DistanceJoint, _super);
  77216. function DistanceJoint(jointData) {
  77217. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  77218. }
  77219. /**
  77220. * Update the predefined distance.
  77221. */
  77222. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  77223. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  77224. };
  77225. return DistanceJoint;
  77226. }(PhysicsJoint));
  77227. BABYLON.DistanceJoint = DistanceJoint;
  77228. var MotorEnabledJoint = /** @class */ (function (_super) {
  77229. __extends(MotorEnabledJoint, _super);
  77230. function MotorEnabledJoint(type, jointData) {
  77231. return _super.call(this, type, jointData) || this;
  77232. }
  77233. /**
  77234. * Set the motor values.
  77235. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77236. * @param {number} force the force to apply
  77237. * @param {number} maxForce max force for this motor.
  77238. */
  77239. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  77240. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77241. };
  77242. /**
  77243. * Set the motor's limits.
  77244. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77245. */
  77246. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77247. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77248. };
  77249. return MotorEnabledJoint;
  77250. }(PhysicsJoint));
  77251. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  77252. /**
  77253. * This class represents a single hinge physics joint
  77254. */
  77255. var HingeJoint = /** @class */ (function (_super) {
  77256. __extends(HingeJoint, _super);
  77257. function HingeJoint(jointData) {
  77258. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  77259. }
  77260. /**
  77261. * Set the motor values.
  77262. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77263. * @param {number} force the force to apply
  77264. * @param {number} maxForce max force for this motor.
  77265. */
  77266. HingeJoint.prototype.setMotor = function (force, maxForce) {
  77267. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77268. };
  77269. /**
  77270. * Set the motor's limits.
  77271. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77272. */
  77273. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77274. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77275. };
  77276. return HingeJoint;
  77277. }(MotorEnabledJoint));
  77278. BABYLON.HingeJoint = HingeJoint;
  77279. /**
  77280. * This class represents a dual hinge physics joint (same as wheel joint)
  77281. */
  77282. var Hinge2Joint = /** @class */ (function (_super) {
  77283. __extends(Hinge2Joint, _super);
  77284. function Hinge2Joint(jointData) {
  77285. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  77286. }
  77287. /**
  77288. * Set the motor values.
  77289. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77290. * @param {number} force the force to apply
  77291. * @param {number} maxForce max force for this motor.
  77292. * @param {motorIndex} the motor's index, 0 or 1.
  77293. */
  77294. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  77295. if (motorIndex === void 0) { motorIndex = 0; }
  77296. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  77297. };
  77298. /**
  77299. * Set the motor limits.
  77300. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77301. * @param {number} upperLimit the upper limit
  77302. * @param {number} lowerLimit lower limit
  77303. * @param {motorIndex} the motor's index, 0 or 1.
  77304. */
  77305. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  77306. if (motorIndex === void 0) { motorIndex = 0; }
  77307. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  77308. };
  77309. return Hinge2Joint;
  77310. }(MotorEnabledJoint));
  77311. BABYLON.Hinge2Joint = Hinge2Joint;
  77312. })(BABYLON || (BABYLON = {}));
  77313. //# sourceMappingURL=babylon.physicsJoint.js.map
  77314. "use strict";
  77315. var BABYLON;
  77316. (function (BABYLON) {
  77317. var PhysicsImpostor = /** @class */ (function () {
  77318. function PhysicsImpostor(object, type, _options, _scene) {
  77319. if (_options === void 0) { _options = { mass: 0 }; }
  77320. var _this = this;
  77321. this.object = object;
  77322. this.type = type;
  77323. this._options = _options;
  77324. this._scene = _scene;
  77325. this._bodyUpdateRequired = false;
  77326. this._onBeforePhysicsStepCallbacks = new Array();
  77327. this._onAfterPhysicsStepCallbacks = new Array();
  77328. this._onPhysicsCollideCallbacks = [];
  77329. this._deltaPosition = BABYLON.Vector3.Zero();
  77330. this._isDisposed = false;
  77331. //temp variables for parent rotation calculations
  77332. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  77333. this._tmpQuat = new BABYLON.Quaternion();
  77334. this._tmpQuat2 = new BABYLON.Quaternion();
  77335. /**
  77336. * this function is executed by the physics engine.
  77337. */
  77338. this.beforeStep = function () {
  77339. if (!_this._physicsEngine) {
  77340. return;
  77341. }
  77342. _this.object.translate(_this._deltaPosition, -1);
  77343. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  77344. _this.object.computeWorldMatrix(false);
  77345. if (_this.object.parent && _this.object.rotationQuaternion) {
  77346. _this.getParentsRotation();
  77347. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  77348. }
  77349. else {
  77350. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  77351. }
  77352. if (!_this._options.disableBidirectionalTransformation) {
  77353. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  77354. }
  77355. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  77356. func(_this);
  77357. });
  77358. };
  77359. /**
  77360. * this function is executed by the physics engine.
  77361. */
  77362. this.afterStep = function () {
  77363. if (!_this._physicsEngine) {
  77364. return;
  77365. }
  77366. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77367. func(_this);
  77368. });
  77369. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77370. // object has now its world rotation. needs to be converted to local.
  77371. if (_this.object.parent && _this.object.rotationQuaternion) {
  77372. _this.getParentsRotation();
  77373. _this._tmpQuat.conjugateInPlace();
  77374. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77375. }
  77376. // take the position set and make it the absolute position of this object.
  77377. _this.object.setAbsolutePosition(_this.object.position);
  77378. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77379. _this.object.translate(_this._deltaPosition, 1);
  77380. };
  77381. /**
  77382. * Legacy collision detection event support
  77383. */
  77384. this.onCollideEvent = null;
  77385. //event and body object due to cannon's event-based architecture.
  77386. this.onCollide = function (e) {
  77387. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77388. return;
  77389. }
  77390. if (!_this._physicsEngine) {
  77391. return;
  77392. }
  77393. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77394. if (otherImpostor) {
  77395. // Legacy collision detection event support
  77396. if (_this.onCollideEvent) {
  77397. _this.onCollideEvent(_this, otherImpostor);
  77398. }
  77399. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77400. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77401. }).forEach(function (obj) {
  77402. obj.callback(_this, otherImpostor);
  77403. });
  77404. }
  77405. };
  77406. //sanity check!
  77407. if (!this.object) {
  77408. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77409. return;
  77410. }
  77411. //legacy support for old syntax.
  77412. if (!this._scene && object.getScene) {
  77413. this._scene = object.getScene();
  77414. }
  77415. if (!this._scene) {
  77416. return;
  77417. }
  77418. this._physicsEngine = this._scene.getPhysicsEngine();
  77419. if (!this._physicsEngine) {
  77420. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77421. }
  77422. else {
  77423. //set the object's quaternion, if not set
  77424. if (!this.object.rotationQuaternion) {
  77425. if (this.object.rotation) {
  77426. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77427. }
  77428. else {
  77429. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77430. }
  77431. }
  77432. //default options params
  77433. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77434. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77435. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77436. this._joints = [];
  77437. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77438. if (!this.object.parent || this._options.ignoreParent) {
  77439. this._init();
  77440. }
  77441. else if (this.object.parent.physicsImpostor) {
  77442. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77443. }
  77444. }
  77445. }
  77446. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77447. get: function () {
  77448. return this._isDisposed;
  77449. },
  77450. enumerable: true,
  77451. configurable: true
  77452. });
  77453. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77454. get: function () {
  77455. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77456. },
  77457. set: function (value) {
  77458. this.setMass(value);
  77459. },
  77460. enumerable: true,
  77461. configurable: true
  77462. });
  77463. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77464. get: function () {
  77465. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77466. },
  77467. set: function (value) {
  77468. if (!this._physicsEngine) {
  77469. return;
  77470. }
  77471. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77472. },
  77473. enumerable: true,
  77474. configurable: true
  77475. });
  77476. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77477. get: function () {
  77478. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77479. },
  77480. set: function (value) {
  77481. if (!this._physicsEngine) {
  77482. return;
  77483. }
  77484. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77485. },
  77486. enumerable: true,
  77487. configurable: true
  77488. });
  77489. /**
  77490. * This function will completly initialize this impostor.
  77491. * It will create a new body - but only if this mesh has no parent.
  77492. * If it has, this impostor will not be used other than to define the impostor
  77493. * of the child mesh.
  77494. */
  77495. PhysicsImpostor.prototype._init = function () {
  77496. if (!this._physicsEngine) {
  77497. return;
  77498. }
  77499. this._physicsEngine.removeImpostor(this);
  77500. this.physicsBody = null;
  77501. this._parent = this._parent || this._getPhysicsParent();
  77502. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77503. this._physicsEngine.addImpostor(this);
  77504. }
  77505. };
  77506. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77507. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77508. var parentMesh = this.object.parent;
  77509. return parentMesh.physicsImpostor;
  77510. }
  77511. return null;
  77512. };
  77513. /**
  77514. * Should a new body be generated.
  77515. */
  77516. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77517. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77518. };
  77519. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77520. this.forceUpdate();
  77521. };
  77522. /**
  77523. * Force a regeneration of this or the parent's impostor's body.
  77524. * Use under cautious - This will remove all joints already implemented.
  77525. */
  77526. PhysicsImpostor.prototype.forceUpdate = function () {
  77527. this._init();
  77528. if (this.parent && !this._options.ignoreParent) {
  77529. this.parent.forceUpdate();
  77530. }
  77531. };
  77532. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77533. /*public get mesh(): AbstractMesh {
  77534. return this._mesh;
  77535. }*/
  77536. /**
  77537. * Gets the body that holds this impostor. Either its own, or its parent.
  77538. */
  77539. get: function () {
  77540. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77541. },
  77542. /**
  77543. * Set the physics body. Used mainly by the physics engine/plugin
  77544. */
  77545. set: function (physicsBody) {
  77546. if (this._physicsBody && this._physicsEngine) {
  77547. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77548. }
  77549. this._physicsBody = physicsBody;
  77550. this.resetUpdateFlags();
  77551. },
  77552. enumerable: true,
  77553. configurable: true
  77554. });
  77555. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77556. get: function () {
  77557. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77558. },
  77559. set: function (value) {
  77560. this._parent = value;
  77561. },
  77562. enumerable: true,
  77563. configurable: true
  77564. });
  77565. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77566. this._bodyUpdateRequired = false;
  77567. };
  77568. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77569. if (this.object.getBoundingInfo) {
  77570. var q = this.object.rotationQuaternion;
  77571. //reset rotation
  77572. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77573. //calculate the world matrix with no rotation
  77574. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77575. var boundingInfo = this.object.getBoundingInfo();
  77576. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77577. //bring back the rotation
  77578. this.object.rotationQuaternion = q;
  77579. //calculate the world matrix with the new rotation
  77580. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77581. return size;
  77582. }
  77583. else {
  77584. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77585. }
  77586. };
  77587. PhysicsImpostor.prototype.getObjectCenter = function () {
  77588. if (this.object.getBoundingInfo) {
  77589. var boundingInfo = this.object.getBoundingInfo();
  77590. return boundingInfo.boundingBox.centerWorld;
  77591. }
  77592. else {
  77593. return this.object.position;
  77594. }
  77595. };
  77596. /**
  77597. * Get a specific parametes from the options parameter.
  77598. */
  77599. PhysicsImpostor.prototype.getParam = function (paramName) {
  77600. return this._options[paramName];
  77601. };
  77602. /**
  77603. * Sets a specific parameter in the options given to the physics plugin
  77604. */
  77605. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77606. this._options[paramName] = value;
  77607. this._bodyUpdateRequired = true;
  77608. };
  77609. /**
  77610. * Specifically change the body's mass option. Won't recreate the physics body object
  77611. */
  77612. PhysicsImpostor.prototype.setMass = function (mass) {
  77613. if (this.getParam("mass") !== mass) {
  77614. this.setParam("mass", mass);
  77615. }
  77616. if (this._physicsEngine) {
  77617. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77618. }
  77619. };
  77620. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77621. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77622. };
  77623. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77624. if (this._physicsEngine) {
  77625. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77626. }
  77627. };
  77628. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77629. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77630. };
  77631. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77632. if (this._physicsEngine) {
  77633. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77634. }
  77635. };
  77636. /**
  77637. * Execute a function with the physics plugin native code.
  77638. * Provide a function the will have two variables - the world object and the physics body object.
  77639. */
  77640. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77641. if (this._physicsEngine) {
  77642. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77643. }
  77644. };
  77645. /**
  77646. * Register a function that will be executed before the physics world is stepping forward.
  77647. */
  77648. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77649. this._onBeforePhysicsStepCallbacks.push(func);
  77650. };
  77651. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77652. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77653. if (index > -1) {
  77654. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77655. }
  77656. else {
  77657. BABYLON.Tools.Warn("Function to remove was not found");
  77658. }
  77659. };
  77660. /**
  77661. * Register a function that will be executed after the physics step
  77662. */
  77663. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77664. this._onAfterPhysicsStepCallbacks.push(func);
  77665. };
  77666. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77667. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77668. if (index > -1) {
  77669. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77670. }
  77671. else {
  77672. BABYLON.Tools.Warn("Function to remove was not found");
  77673. }
  77674. };
  77675. /**
  77676. * register a function that will be executed when this impostor collides against a different body.
  77677. */
  77678. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77679. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77680. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77681. };
  77682. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77683. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77684. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77685. if (index > -1) {
  77686. this._onPhysicsCollideCallbacks.splice(index, 1);
  77687. }
  77688. else {
  77689. BABYLON.Tools.Warn("Function to remove was not found");
  77690. }
  77691. };
  77692. PhysicsImpostor.prototype.getParentsRotation = function () {
  77693. var parent = this.object.parent;
  77694. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77695. while (parent) {
  77696. if (parent.rotationQuaternion) {
  77697. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77698. }
  77699. else {
  77700. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77701. }
  77702. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77703. parent = parent.parent;
  77704. }
  77705. return this._tmpQuat;
  77706. };
  77707. /**
  77708. * Apply a force
  77709. */
  77710. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77711. if (this._physicsEngine) {
  77712. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77713. }
  77714. return this;
  77715. };
  77716. /**
  77717. * Apply an impulse
  77718. */
  77719. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77720. if (this._physicsEngine) {
  77721. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77722. }
  77723. return this;
  77724. };
  77725. /**
  77726. * A help function to create a joint.
  77727. */
  77728. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77729. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77730. this.addJoint(otherImpostor, joint);
  77731. return this;
  77732. };
  77733. /**
  77734. * Add a joint to this impostor with a different impostor.
  77735. */
  77736. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77737. this._joints.push({
  77738. otherImpostor: otherImpostor,
  77739. joint: joint
  77740. });
  77741. if (this._physicsEngine) {
  77742. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77743. }
  77744. return this;
  77745. };
  77746. /**
  77747. * Will keep this body still, in a sleep mode.
  77748. */
  77749. PhysicsImpostor.prototype.sleep = function () {
  77750. if (this._physicsEngine) {
  77751. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77752. }
  77753. return this;
  77754. };
  77755. /**
  77756. * Wake the body up.
  77757. */
  77758. PhysicsImpostor.prototype.wakeUp = function () {
  77759. if (this._physicsEngine) {
  77760. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77761. }
  77762. return this;
  77763. };
  77764. PhysicsImpostor.prototype.clone = function (newObject) {
  77765. if (!newObject)
  77766. return null;
  77767. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77768. };
  77769. PhysicsImpostor.prototype.dispose = function () {
  77770. var _this = this;
  77771. //no dispose if no physics engine is available.
  77772. if (!this._physicsEngine) {
  77773. return;
  77774. }
  77775. this._joints.forEach(function (j) {
  77776. if (_this._physicsEngine) {
  77777. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77778. }
  77779. });
  77780. //dispose the physics body
  77781. this._physicsEngine.removeImpostor(this);
  77782. if (this.parent) {
  77783. this.parent.forceUpdate();
  77784. }
  77785. else {
  77786. /*this._object.getChildMeshes().forEach(function(mesh) {
  77787. if (mesh.physicsImpostor) {
  77788. if (disposeChildren) {
  77789. mesh.physicsImpostor.dispose();
  77790. mesh.physicsImpostor = null;
  77791. }
  77792. }
  77793. })*/
  77794. }
  77795. this._isDisposed = true;
  77796. };
  77797. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77798. this._deltaPosition.copyFrom(position);
  77799. };
  77800. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77801. if (!this._deltaRotation) {
  77802. this._deltaRotation = new BABYLON.Quaternion();
  77803. }
  77804. this._deltaRotation.copyFrom(rotation);
  77805. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77806. };
  77807. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77808. if (this._physicsEngine) {
  77809. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77810. }
  77811. return this;
  77812. };
  77813. PhysicsImpostor.prototype.getRadius = function () {
  77814. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77815. };
  77816. /**
  77817. * Sync a bone with this impostor
  77818. * @param bone The bone to sync to the impostor.
  77819. * @param boneMesh The mesh that the bone is influencing.
  77820. * @param jointPivot The pivot of the joint / bone in local space.
  77821. * @param distToJoint Optional distance from the impostor to the joint.
  77822. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77823. */
  77824. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77825. var tempVec = PhysicsImpostor._tmpVecs[0];
  77826. var mesh = this.object;
  77827. if (mesh.rotationQuaternion) {
  77828. if (adjustRotation) {
  77829. var tempQuat = PhysicsImpostor._tmpQuat;
  77830. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77831. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77832. }
  77833. else {
  77834. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  77835. }
  77836. }
  77837. tempVec.x = 0;
  77838. tempVec.y = 0;
  77839. tempVec.z = 0;
  77840. if (jointPivot) {
  77841. tempVec.x = jointPivot.x;
  77842. tempVec.y = jointPivot.y;
  77843. tempVec.z = jointPivot.z;
  77844. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  77845. if (distToJoint === undefined || distToJoint === null) {
  77846. distToJoint = jointPivot.length();
  77847. }
  77848. tempVec.x *= distToJoint;
  77849. tempVec.y *= distToJoint;
  77850. tempVec.z *= distToJoint;
  77851. }
  77852. if (bone.getParent()) {
  77853. tempVec.addInPlace(mesh.getAbsolutePosition());
  77854. bone.setAbsolutePosition(tempVec, boneMesh);
  77855. }
  77856. else {
  77857. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  77858. boneMesh.position.x -= tempVec.x;
  77859. boneMesh.position.y -= tempVec.y;
  77860. boneMesh.position.z -= tempVec.z;
  77861. }
  77862. };
  77863. /**
  77864. * Sync impostor to a bone
  77865. * @param bone The bone that the impostor will be synced to.
  77866. * @param boneMesh The mesh that the bone is influencing.
  77867. * @param jointPivot The pivot of the joint / bone in local space.
  77868. * @param distToJoint Optional distance from the impostor to the joint.
  77869. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77870. * @param boneAxis Optional vector3 axis the bone is aligned with
  77871. */
  77872. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  77873. var mesh = this.object;
  77874. if (mesh.rotationQuaternion) {
  77875. if (adjustRotation) {
  77876. var tempQuat = PhysicsImpostor._tmpQuat;
  77877. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  77878. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  77879. }
  77880. else {
  77881. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  77882. }
  77883. }
  77884. var pos = PhysicsImpostor._tmpVecs[0];
  77885. var boneDir = PhysicsImpostor._tmpVecs[1];
  77886. if (!boneAxis) {
  77887. boneAxis = PhysicsImpostor._tmpVecs[2];
  77888. boneAxis.x = 0;
  77889. boneAxis.y = 1;
  77890. boneAxis.z = 0;
  77891. }
  77892. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  77893. bone.getAbsolutePositionToRef(boneMesh, pos);
  77894. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  77895. distToJoint = jointPivot.length();
  77896. }
  77897. if (distToJoint !== undefined && distToJoint !== null) {
  77898. pos.x += boneDir.x * distToJoint;
  77899. pos.y += boneDir.y * distToJoint;
  77900. pos.z += boneDir.z * distToJoint;
  77901. }
  77902. mesh.setAbsolutePosition(pos);
  77903. };
  77904. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  77905. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  77906. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77907. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  77908. //Impostor types
  77909. PhysicsImpostor.NoImpostor = 0;
  77910. PhysicsImpostor.SphereImpostor = 1;
  77911. PhysicsImpostor.BoxImpostor = 2;
  77912. PhysicsImpostor.PlaneImpostor = 3;
  77913. PhysicsImpostor.MeshImpostor = 4;
  77914. PhysicsImpostor.CylinderImpostor = 7;
  77915. PhysicsImpostor.ParticleImpostor = 8;
  77916. PhysicsImpostor.HeightmapImpostor = 9;
  77917. return PhysicsImpostor;
  77918. }());
  77919. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77920. })(BABYLON || (BABYLON = {}));
  77921. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77922. "use strict";
  77923. var BABYLON;
  77924. (function (BABYLON) {
  77925. var PhysicsEngine = /** @class */ (function () {
  77926. function PhysicsEngine(gravity, _physicsPlugin) {
  77927. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77928. this._physicsPlugin = _physicsPlugin;
  77929. //new methods and parameters
  77930. this._impostors = [];
  77931. this._joints = [];
  77932. if (!this._physicsPlugin.isSupported()) {
  77933. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  77934. + "Please make sure it is included.");
  77935. }
  77936. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  77937. this.setGravity(gravity);
  77938. this.setTimeStep();
  77939. }
  77940. PhysicsEngine.prototype.setGravity = function (gravity) {
  77941. this.gravity = gravity;
  77942. this._physicsPlugin.setGravity(this.gravity);
  77943. };
  77944. /**
  77945. * Set the time step of the physics engine.
  77946. * default is 1/60.
  77947. * To slow it down, enter 1/600 for example.
  77948. * To speed it up, 1/30
  77949. * @param {number} newTimeStep the new timestep to apply to this world.
  77950. */
  77951. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  77952. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  77953. this._physicsPlugin.setTimeStep(newTimeStep);
  77954. };
  77955. /**
  77956. * Get the time step of the physics engine.
  77957. */
  77958. PhysicsEngine.prototype.getTimeStep = function () {
  77959. return this._physicsPlugin.getTimeStep();
  77960. };
  77961. PhysicsEngine.prototype.dispose = function () {
  77962. this._impostors.forEach(function (impostor) {
  77963. impostor.dispose();
  77964. });
  77965. this._physicsPlugin.dispose();
  77966. };
  77967. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  77968. return this._physicsPlugin.name;
  77969. };
  77970. /**
  77971. * Adding a new impostor for the impostor tracking.
  77972. * This will be done by the impostor itself.
  77973. * @param {PhysicsImpostor} impostor the impostor to add
  77974. */
  77975. PhysicsEngine.prototype.addImpostor = function (impostor) {
  77976. impostor.uniqueId = this._impostors.push(impostor);
  77977. //if no parent, generate the body
  77978. if (!impostor.parent) {
  77979. this._physicsPlugin.generatePhysicsBody(impostor);
  77980. }
  77981. };
  77982. /**
  77983. * Remove an impostor from the engine.
  77984. * This impostor and its mesh will not longer be updated by the physics engine.
  77985. * @param {PhysicsImpostor} impostor the impostor to remove
  77986. */
  77987. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  77988. var index = this._impostors.indexOf(impostor);
  77989. if (index > -1) {
  77990. var removed = this._impostors.splice(index, 1);
  77991. //Is it needed?
  77992. if (removed.length) {
  77993. //this will also remove it from the world.
  77994. removed[0].physicsBody = null;
  77995. }
  77996. }
  77997. };
  77998. /**
  77999. * Add a joint to the physics engine
  78000. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  78001. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  78002. * @param {PhysicsJoint} the joint that will connect both impostors.
  78003. */
  78004. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  78005. var impostorJoint = {
  78006. mainImpostor: mainImpostor,
  78007. connectedImpostor: connectedImpostor,
  78008. joint: joint
  78009. };
  78010. joint.physicsPlugin = this._physicsPlugin;
  78011. this._joints.push(impostorJoint);
  78012. this._physicsPlugin.generateJoint(impostorJoint);
  78013. };
  78014. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  78015. var matchingJoints = this._joints.filter(function (impostorJoint) {
  78016. return (impostorJoint.connectedImpostor === connectedImpostor
  78017. && impostorJoint.joint === joint
  78018. && impostorJoint.mainImpostor === mainImpostor);
  78019. });
  78020. if (matchingJoints.length) {
  78021. this._physicsPlugin.removeJoint(matchingJoints[0]);
  78022. //TODO remove it from the list as well
  78023. }
  78024. };
  78025. /**
  78026. * Called by the scene. no need to call it.
  78027. */
  78028. PhysicsEngine.prototype._step = function (delta) {
  78029. var _this = this;
  78030. //check if any mesh has no body / requires an update
  78031. this._impostors.forEach(function (impostor) {
  78032. if (impostor.isBodyInitRequired()) {
  78033. _this._physicsPlugin.generatePhysicsBody(impostor);
  78034. }
  78035. });
  78036. if (delta > 0.1) {
  78037. delta = 0.1;
  78038. }
  78039. else if (delta <= 0) {
  78040. delta = 1.0 / 60.0;
  78041. }
  78042. this._physicsPlugin.executeStep(delta, this._impostors);
  78043. };
  78044. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  78045. return this._physicsPlugin;
  78046. };
  78047. PhysicsEngine.prototype.getImpostors = function () {
  78048. return this._impostors;
  78049. };
  78050. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  78051. for (var i = 0; i < this._impostors.length; ++i) {
  78052. if (this._impostors[i].object === object) {
  78053. return this._impostors[i];
  78054. }
  78055. }
  78056. return null;
  78057. };
  78058. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  78059. for (var i = 0; i < this._impostors.length; ++i) {
  78060. if (this._impostors[i].physicsBody === body) {
  78061. return this._impostors[i];
  78062. }
  78063. }
  78064. return null;
  78065. };
  78066. // Statics
  78067. PhysicsEngine.Epsilon = 0.001;
  78068. return PhysicsEngine;
  78069. }());
  78070. BABYLON.PhysicsEngine = PhysicsEngine;
  78071. })(BABYLON || (BABYLON = {}));
  78072. //# sourceMappingURL=babylon.physicsEngine.js.map
  78073. "use strict";
  78074. var BABYLON;
  78075. (function (BABYLON) {
  78076. var PhysicsHelper = /** @class */ (function () {
  78077. function PhysicsHelper(scene) {
  78078. this._scene = scene;
  78079. this._physicsEngine = this._scene.getPhysicsEngine();
  78080. if (!this._physicsEngine) {
  78081. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  78082. }
  78083. }
  78084. /**
  78085. * @param {Vector3} origin the origin of the explosion
  78086. * @param {number} radius the explosion radius
  78087. * @param {number} strength the explosion strength
  78088. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78089. */
  78090. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  78091. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78092. if (!this._physicsEngine) {
  78093. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  78094. return null;
  78095. }
  78096. var impostors = this._physicsEngine.getImpostors();
  78097. if (impostors.length === 0) {
  78098. return null;
  78099. }
  78100. var event = new PhysicsRadialExplosionEvent(this._scene);
  78101. impostors.forEach(function (impostor) {
  78102. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78103. if (!impostorForceAndContactPoint) {
  78104. return;
  78105. }
  78106. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78107. });
  78108. event.dispose(false);
  78109. return event;
  78110. };
  78111. /**
  78112. * @param {Vector3} origin the origin of the explosion
  78113. * @param {number} radius the explosion radius
  78114. * @param {number} strength the explosion strength
  78115. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78116. */
  78117. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  78118. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78119. if (!this._physicsEngine) {
  78120. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78121. return null;
  78122. }
  78123. var impostors = this._physicsEngine.getImpostors();
  78124. if (impostors.length === 0) {
  78125. return null;
  78126. }
  78127. var event = new PhysicsRadialExplosionEvent(this._scene);
  78128. impostors.forEach(function (impostor) {
  78129. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78130. if (!impostorForceAndContactPoint) {
  78131. return;
  78132. }
  78133. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78134. });
  78135. event.dispose(false);
  78136. return event;
  78137. };
  78138. /**
  78139. * @param {Vector3} origin the origin of the explosion
  78140. * @param {number} radius the explosion radius
  78141. * @param {number} strength the explosion strength
  78142. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78143. */
  78144. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  78145. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78146. if (!this._physicsEngine) {
  78147. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78148. return null;
  78149. }
  78150. var impostors = this._physicsEngine.getImpostors();
  78151. if (impostors.length === 0) {
  78152. return null;
  78153. }
  78154. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  78155. event.dispose(false);
  78156. return event;
  78157. };
  78158. /**
  78159. * @param {Vector3} origin the origin of the updraft
  78160. * @param {number} radius the radius of the updraft
  78161. * @param {number} strength the strength of the updraft
  78162. * @param {number} height the height of the updraft
  78163. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  78164. */
  78165. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  78166. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  78167. if (!this._physicsEngine) {
  78168. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78169. return null;
  78170. }
  78171. if (this._physicsEngine.getImpostors().length === 0) {
  78172. return null;
  78173. }
  78174. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  78175. event.dispose(false);
  78176. return event;
  78177. };
  78178. /**
  78179. * @param {Vector3} origin the of the vortex
  78180. * @param {number} radius the radius of the vortex
  78181. * @param {number} strength the strength of the vortex
  78182. * @param {number} height the height of the vortex
  78183. */
  78184. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  78185. if (!this._physicsEngine) {
  78186. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78187. return null;
  78188. }
  78189. if (this._physicsEngine.getImpostors().length === 0) {
  78190. return null;
  78191. }
  78192. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  78193. event.dispose(false);
  78194. return event;
  78195. };
  78196. return PhysicsHelper;
  78197. }());
  78198. BABYLON.PhysicsHelper = PhysicsHelper;
  78199. /***** Radial explosion *****/
  78200. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  78201. function PhysicsRadialExplosionEvent(scene) {
  78202. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  78203. this._rays = [];
  78204. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  78205. this._scene = scene;
  78206. }
  78207. /**
  78208. * Returns the data related to the radial explosion event (sphere & rays).
  78209. * @returns {PhysicsRadialExplosionEventData}
  78210. */
  78211. PhysicsRadialExplosionEvent.prototype.getData = function () {
  78212. this._dataFetched = true;
  78213. return {
  78214. sphere: this._sphere,
  78215. rays: this._rays,
  78216. };
  78217. };
  78218. /**
  78219. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  78220. * @param impostor
  78221. * @param {Vector3} origin the origin of the explosion
  78222. * @param {number} radius the explosion radius
  78223. * @param {number} strength the explosion strength
  78224. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  78225. * @returns {Nullable<PhysicsForceAndContactPoint>}
  78226. */
  78227. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  78228. if (impostor.mass === 0) {
  78229. return null;
  78230. }
  78231. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  78232. return null;
  78233. }
  78234. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78235. return null;
  78236. }
  78237. var impostorObjectCenter = impostor.getObjectCenter();
  78238. var direction = impostorObjectCenter.subtract(origin);
  78239. var ray = new BABYLON.Ray(origin, direction, radius);
  78240. this._rays.push(ray);
  78241. var hit = ray.intersectsMesh(impostor.object);
  78242. var contactPoint = hit.pickedPoint;
  78243. if (!contactPoint) {
  78244. return null;
  78245. }
  78246. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  78247. if (distanceFromOrigin > radius) {
  78248. return null;
  78249. }
  78250. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  78251. ? strength
  78252. : strength * (1 - (distanceFromOrigin / radius));
  78253. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78254. return { force: force, contactPoint: contactPoint };
  78255. };
  78256. /**
  78257. * Disposes the sphere.
  78258. * @param {bolean} force
  78259. */
  78260. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  78261. var _this = this;
  78262. if (force === void 0) { force = true; }
  78263. if (force) {
  78264. this._sphere.dispose();
  78265. }
  78266. else {
  78267. setTimeout(function () {
  78268. if (!_this._dataFetched) {
  78269. _this._sphere.dispose();
  78270. }
  78271. }, 0);
  78272. }
  78273. };
  78274. /*** Helpers ***/
  78275. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  78276. if (!this._sphere) {
  78277. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  78278. this._sphere.isVisible = false;
  78279. }
  78280. };
  78281. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  78282. var impostorObject = impostor.object;
  78283. this._prepareSphere();
  78284. this._sphere.position = origin;
  78285. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  78286. this._sphere._updateBoundingInfo();
  78287. this._sphere.computeWorldMatrix(true);
  78288. return this._sphere.intersectsMesh(impostorObject, true);
  78289. };
  78290. return PhysicsRadialExplosionEvent;
  78291. }());
  78292. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  78293. /***** Gravitational Field *****/
  78294. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  78295. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  78296. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78297. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78298. this._physicsHelper = physicsHelper;
  78299. this._scene = scene;
  78300. this._origin = origin;
  78301. this._radius = radius;
  78302. this._strength = strength;
  78303. this._falloff = falloff;
  78304. this._tickCallback = this._tick.bind(this);
  78305. }
  78306. /**
  78307. * Returns the data related to the gravitational field event (sphere).
  78308. * @returns {PhysicsGravitationalFieldEventData}
  78309. */
  78310. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  78311. this._dataFetched = true;
  78312. return {
  78313. sphere: this._sphere,
  78314. };
  78315. };
  78316. /**
  78317. * Enables the gravitational field.
  78318. */
  78319. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  78320. this._tickCallback.call(this);
  78321. this._scene.registerBeforeRender(this._tickCallback);
  78322. };
  78323. /**
  78324. * Disables the gravitational field.
  78325. */
  78326. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  78327. this._scene.unregisterBeforeRender(this._tickCallback);
  78328. };
  78329. /**
  78330. * Disposes the sphere.
  78331. * @param {bolean} force
  78332. */
  78333. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  78334. var _this = this;
  78335. if (force === void 0) { force = true; }
  78336. if (force) {
  78337. this._sphere.dispose();
  78338. }
  78339. else {
  78340. setTimeout(function () {
  78341. if (!_this._dataFetched) {
  78342. _this._sphere.dispose();
  78343. }
  78344. }, 0);
  78345. }
  78346. };
  78347. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  78348. // Since the params won't change, we fetch the event only once
  78349. if (this._sphere) {
  78350. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78351. }
  78352. else {
  78353. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78354. if (radialExplosionEvent) {
  78355. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  78356. }
  78357. }
  78358. };
  78359. return PhysicsGravitationalFieldEvent;
  78360. }());
  78361. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  78362. /***** Updraft *****/
  78363. var PhysicsUpdraftEvent = /** @class */ (function () {
  78364. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78365. this._scene = _scene;
  78366. this._origin = _origin;
  78367. this._radius = _radius;
  78368. this._strength = _strength;
  78369. this._height = _height;
  78370. this._updraftMode = _updraftMode;
  78371. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78372. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78373. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78374. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78375. this._physicsEngine = this._scene.getPhysicsEngine();
  78376. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78377. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78378. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78379. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78380. }
  78381. this._tickCallback = this._tick.bind(this);
  78382. }
  78383. /**
  78384. * Returns the data related to the updraft event (cylinder).
  78385. * @returns {PhysicsUpdraftEventData}
  78386. */
  78387. PhysicsUpdraftEvent.prototype.getData = function () {
  78388. this._dataFetched = true;
  78389. return {
  78390. cylinder: this._cylinder,
  78391. };
  78392. };
  78393. /**
  78394. * Enables the updraft.
  78395. */
  78396. PhysicsUpdraftEvent.prototype.enable = function () {
  78397. this._tickCallback.call(this);
  78398. this._scene.registerBeforeRender(this._tickCallback);
  78399. };
  78400. /**
  78401. * Disables the cortex.
  78402. */
  78403. PhysicsUpdraftEvent.prototype.disable = function () {
  78404. this._scene.unregisterBeforeRender(this._tickCallback);
  78405. };
  78406. /**
  78407. * Disposes the sphere.
  78408. * @param {bolean} force
  78409. */
  78410. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78411. var _this = this;
  78412. if (force === void 0) { force = true; }
  78413. if (force) {
  78414. this._cylinder.dispose();
  78415. }
  78416. else {
  78417. setTimeout(function () {
  78418. if (!_this._dataFetched) {
  78419. _this._cylinder.dispose();
  78420. }
  78421. }, 0);
  78422. }
  78423. };
  78424. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78425. if (impostor.mass === 0) {
  78426. return null;
  78427. }
  78428. if (!this._intersectsWithCylinder(impostor)) {
  78429. return null;
  78430. }
  78431. var impostorObjectCenter = impostor.getObjectCenter();
  78432. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78433. var direction = this._originDirection;
  78434. }
  78435. else {
  78436. var direction = impostorObjectCenter.subtract(this._originTop);
  78437. }
  78438. var multiplier = this._strength * -1;
  78439. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78440. return { force: force, contactPoint: impostorObjectCenter };
  78441. };
  78442. PhysicsUpdraftEvent.prototype._tick = function () {
  78443. var _this = this;
  78444. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78445. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78446. if (!impostorForceAndContactPoint) {
  78447. return;
  78448. }
  78449. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78450. });
  78451. };
  78452. /*** Helpers ***/
  78453. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78454. if (!this._cylinder) {
  78455. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78456. height: this._height,
  78457. diameter: this._radius * 2,
  78458. }, this._scene);
  78459. this._cylinder.isVisible = false;
  78460. }
  78461. };
  78462. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78463. var impostorObject = impostor.object;
  78464. this._prepareCylinder();
  78465. this._cylinder.position = this._cylinderPosition;
  78466. return this._cylinder.intersectsMesh(impostorObject, true);
  78467. };
  78468. return PhysicsUpdraftEvent;
  78469. }());
  78470. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78471. /***** Vortex *****/
  78472. var PhysicsVortexEvent = /** @class */ (function () {
  78473. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78474. this._scene = _scene;
  78475. this._origin = _origin;
  78476. this._radius = _radius;
  78477. this._strength = _strength;
  78478. this._height = _height;
  78479. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78480. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78481. this._updraftMultiplier = 0.02;
  78482. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78483. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78484. this._physicsEngine = this._scene.getPhysicsEngine();
  78485. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78486. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78487. this._tickCallback = this._tick.bind(this);
  78488. }
  78489. /**
  78490. * Returns the data related to the vortex event (cylinder).
  78491. * @returns {PhysicsVortexEventData}
  78492. */
  78493. PhysicsVortexEvent.prototype.getData = function () {
  78494. this._dataFetched = true;
  78495. return {
  78496. cylinder: this._cylinder,
  78497. };
  78498. };
  78499. /**
  78500. * Enables the vortex.
  78501. */
  78502. PhysicsVortexEvent.prototype.enable = function () {
  78503. this._tickCallback.call(this);
  78504. this._scene.registerBeforeRender(this._tickCallback);
  78505. };
  78506. /**
  78507. * Disables the cortex.
  78508. */
  78509. PhysicsVortexEvent.prototype.disable = function () {
  78510. this._scene.unregisterBeforeRender(this._tickCallback);
  78511. };
  78512. /**
  78513. * Disposes the sphere.
  78514. * @param {bolean} force
  78515. */
  78516. PhysicsVortexEvent.prototype.dispose = function (force) {
  78517. var _this = this;
  78518. if (force === void 0) { force = true; }
  78519. if (force) {
  78520. this._cylinder.dispose();
  78521. }
  78522. else {
  78523. setTimeout(function () {
  78524. if (!_this._dataFetched) {
  78525. _this._cylinder.dispose();
  78526. }
  78527. }, 0);
  78528. }
  78529. };
  78530. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78531. if (impostor.mass === 0) {
  78532. return null;
  78533. }
  78534. if (!this._intersectsWithCylinder(impostor)) {
  78535. return null;
  78536. }
  78537. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78538. return null;
  78539. }
  78540. var impostorObjectCenter = impostor.getObjectCenter();
  78541. 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)
  78542. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78543. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78544. var hit = ray.intersectsMesh(impostor.object);
  78545. var contactPoint = hit.pickedPoint;
  78546. if (!contactPoint) {
  78547. return null;
  78548. }
  78549. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78550. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78551. var directionToOrigin = contactPoint.normalize();
  78552. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78553. directionToOrigin = directionToOrigin.negate();
  78554. }
  78555. // TODO: find a more physically based solution
  78556. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78557. var forceX = directionToOrigin.x * this._strength / 8;
  78558. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78559. var forceZ = directionToOrigin.z * this._strength / 8;
  78560. }
  78561. else {
  78562. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78563. var forceY = this._originTop.y * this._updraftMultiplier;
  78564. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78565. }
  78566. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78567. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78568. return { force: force, contactPoint: impostorObjectCenter };
  78569. };
  78570. PhysicsVortexEvent.prototype._tick = function () {
  78571. var _this = this;
  78572. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78573. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78574. if (!impostorForceAndContactPoint) {
  78575. return;
  78576. }
  78577. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78578. });
  78579. };
  78580. /*** Helpers ***/
  78581. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78582. if (!this._cylinder) {
  78583. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78584. height: this._height,
  78585. diameter: this._radius * 2,
  78586. }, this._scene);
  78587. this._cylinder.isVisible = false;
  78588. }
  78589. };
  78590. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78591. var impostorObject = impostor.object;
  78592. this._prepareCylinder();
  78593. this._cylinder.position = this._cylinderPosition;
  78594. return this._cylinder.intersectsMesh(impostorObject, true);
  78595. };
  78596. return PhysicsVortexEvent;
  78597. }());
  78598. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78599. /***** Enums *****/
  78600. /**
  78601. * The strenght of the force in correspondence to the distance of the affected object
  78602. */
  78603. var PhysicsRadialImpulseFalloff;
  78604. (function (PhysicsRadialImpulseFalloff) {
  78605. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78606. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78607. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78608. /**
  78609. * The strenght of the force in correspondence to the distance of the affected object
  78610. */
  78611. var PhysicsUpdraftMode;
  78612. (function (PhysicsUpdraftMode) {
  78613. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78614. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78615. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78616. })(BABYLON || (BABYLON = {}));
  78617. //# sourceMappingURL=babylon.physicsHelper.js.map
  78618. "use strict";
  78619. var BABYLON;
  78620. (function (BABYLON) {
  78621. var CannonJSPlugin = /** @class */ (function () {
  78622. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78623. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78624. if (iterations === void 0) { iterations = 10; }
  78625. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78626. this.name = "CannonJSPlugin";
  78627. this._physicsMaterials = new Array();
  78628. this._fixedTimeStep = 1 / 60;
  78629. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78630. this.BJSCANNON = CANNON;
  78631. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78632. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78633. this._tmpPosition = BABYLON.Vector3.Zero();
  78634. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78635. this._tmpUnityRotation = new BABYLON.Quaternion();
  78636. if (!this.isSupported()) {
  78637. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78638. return;
  78639. }
  78640. this._extendNamespace();
  78641. this.world = new this.BJSCANNON.World();
  78642. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78643. this.world.solver.iterations = iterations;
  78644. }
  78645. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78646. this.world.gravity.copy(gravity);
  78647. };
  78648. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78649. this._fixedTimeStep = timeStep;
  78650. };
  78651. CannonJSPlugin.prototype.getTimeStep = function () {
  78652. return this._fixedTimeStep;
  78653. };
  78654. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78655. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78656. };
  78657. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78658. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78659. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78660. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78661. };
  78662. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78663. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78664. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78665. impostor.physicsBody.applyForce(impulse, worldPoint);
  78666. };
  78667. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78668. //parent-child relationship. Does this impostor has a parent impostor?
  78669. if (impostor.parent) {
  78670. if (impostor.physicsBody) {
  78671. this.removePhysicsBody(impostor);
  78672. //TODO is that needed?
  78673. impostor.forceUpdate();
  78674. }
  78675. return;
  78676. }
  78677. //should a new body be created for this impostor?
  78678. if (impostor.isBodyInitRequired()) {
  78679. var shape = this._createShape(impostor);
  78680. //unregister events, if body is being changed
  78681. var oldBody = impostor.physicsBody;
  78682. if (oldBody) {
  78683. this.removePhysicsBody(impostor);
  78684. }
  78685. //create the body and material
  78686. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78687. var bodyCreationObject = {
  78688. mass: impostor.getParam("mass"),
  78689. material: material
  78690. };
  78691. // A simple extend, in case native options were used.
  78692. var nativeOptions = impostor.getParam("nativeOptions");
  78693. for (var key in nativeOptions) {
  78694. if (nativeOptions.hasOwnProperty(key)) {
  78695. bodyCreationObject[key] = nativeOptions[key];
  78696. }
  78697. }
  78698. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78699. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78700. this.world.addEventListener("preStep", impostor.beforeStep);
  78701. this.world.addEventListener("postStep", impostor.afterStep);
  78702. impostor.physicsBody.addShape(shape);
  78703. this.world.add(impostor.physicsBody);
  78704. //try to keep the body moving in the right direction by taking old properties.
  78705. //Should be tested!
  78706. if (oldBody) {
  78707. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78708. impostor.physicsBody[param].copy(oldBody[param]);
  78709. });
  78710. }
  78711. this._processChildMeshes(impostor);
  78712. }
  78713. //now update the body's transformation
  78714. this._updatePhysicsBodyTransformation(impostor);
  78715. };
  78716. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78717. var _this = this;
  78718. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78719. var currentRotation = mainImpostor.object.rotationQuaternion;
  78720. if (meshChildren.length) {
  78721. var processMesh = function (localPosition, mesh) {
  78722. if (!currentRotation || !mesh.rotationQuaternion) {
  78723. return;
  78724. }
  78725. var childImpostor = mesh.getPhysicsImpostor();
  78726. if (childImpostor) {
  78727. var parent = childImpostor.parent;
  78728. if (parent !== mainImpostor) {
  78729. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78730. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78731. if (childImpostor.physicsBody) {
  78732. _this.removePhysicsBody(childImpostor);
  78733. childImpostor.physicsBody = null;
  78734. }
  78735. childImpostor.parent = mainImpostor;
  78736. childImpostor.resetUpdateFlags();
  78737. 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));
  78738. //Add the mass of the children.
  78739. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78740. }
  78741. }
  78742. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78743. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78744. };
  78745. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78746. }
  78747. };
  78748. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78749. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78750. this.world.removeEventListener("preStep", impostor.beforeStep);
  78751. this.world.removeEventListener("postStep", impostor.afterStep);
  78752. this.world.remove(impostor.physicsBody);
  78753. };
  78754. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78755. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78756. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78757. if (!mainBody || !connectedBody) {
  78758. return;
  78759. }
  78760. var constraint;
  78761. var jointData = impostorJoint.joint.jointData;
  78762. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78763. var constraintData = {
  78764. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78765. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78766. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78767. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78768. maxForce: jointData.nativeParams.maxForce,
  78769. collideConnected: !!jointData.collision
  78770. };
  78771. switch (impostorJoint.joint.type) {
  78772. case BABYLON.PhysicsJoint.HingeJoint:
  78773. case BABYLON.PhysicsJoint.Hinge2Joint:
  78774. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78775. break;
  78776. case BABYLON.PhysicsJoint.DistanceJoint:
  78777. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78778. break;
  78779. case BABYLON.PhysicsJoint.SpringJoint:
  78780. var springData = jointData;
  78781. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78782. restLength: springData.length,
  78783. stiffness: springData.stiffness,
  78784. damping: springData.damping,
  78785. localAnchorA: constraintData.pivotA,
  78786. localAnchorB: constraintData.pivotB
  78787. });
  78788. break;
  78789. case BABYLON.PhysicsJoint.LockJoint:
  78790. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78791. break;
  78792. case BABYLON.PhysicsJoint.PointToPointJoint:
  78793. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78794. default:
  78795. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78796. break;
  78797. }
  78798. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78799. constraint.collideConnected = !!jointData.collision;
  78800. impostorJoint.joint.physicsJoint = constraint;
  78801. //don't add spring as constraint, as it is not one.
  78802. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78803. this.world.addConstraint(constraint);
  78804. }
  78805. else {
  78806. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78807. constraint.applyForce();
  78808. });
  78809. }
  78810. };
  78811. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78812. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78813. };
  78814. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78815. var index;
  78816. var mat;
  78817. for (index = 0; index < this._physicsMaterials.length; index++) {
  78818. mat = this._physicsMaterials[index];
  78819. if (mat.friction === friction && mat.restitution === restitution) {
  78820. return mat;
  78821. }
  78822. }
  78823. var currentMat = new this.BJSCANNON.Material(name);
  78824. currentMat.friction = friction;
  78825. currentMat.restitution = restitution;
  78826. this._physicsMaterials.push(currentMat);
  78827. return currentMat;
  78828. };
  78829. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78830. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78831. };
  78832. CannonJSPlugin.prototype._createShape = function (impostor) {
  78833. var object = impostor.object;
  78834. var returnValue;
  78835. var extendSize = impostor.getObjectExtendSize();
  78836. switch (impostor.type) {
  78837. case BABYLON.PhysicsImpostor.SphereImpostor:
  78838. var radiusX = extendSize.x;
  78839. var radiusY = extendSize.y;
  78840. var radiusZ = extendSize.z;
  78841. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  78842. break;
  78843. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  78844. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78845. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  78846. break;
  78847. case BABYLON.PhysicsImpostor.BoxImpostor:
  78848. var box = extendSize.scale(0.5);
  78849. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  78850. break;
  78851. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78852. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  78853. returnValue = new this.BJSCANNON.Plane();
  78854. break;
  78855. case BABYLON.PhysicsImpostor.MeshImpostor:
  78856. // should transform the vertex data to world coordinates!!
  78857. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  78858. var rawFaces = object.getIndices ? object.getIndices() : [];
  78859. if (!rawVerts)
  78860. return;
  78861. // get only scale! so the object could transform correctly.
  78862. var oldPosition = object.position.clone();
  78863. var oldRotation = object.rotation && object.rotation.clone();
  78864. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  78865. object.position.copyFromFloats(0, 0, 0);
  78866. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78867. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78868. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78869. var transform = object.computeWorldMatrix(true);
  78870. // convert rawVerts to object space
  78871. var temp = new Array();
  78872. var index;
  78873. for (index = 0; index < rawVerts.length; index += 3) {
  78874. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  78875. }
  78876. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  78877. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  78878. //now set back the transformation!
  78879. object.position.copyFrom(oldPosition);
  78880. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  78881. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  78882. break;
  78883. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  78884. var oldPosition2 = object.position.clone();
  78885. var oldRotation2 = object.rotation && object.rotation.clone();
  78886. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  78887. object.position.copyFromFloats(0, 0, 0);
  78888. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78889. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78890. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78891. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  78892. returnValue = this._createHeightmap(object);
  78893. object.position.copyFrom(oldPosition2);
  78894. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  78895. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  78896. object.computeWorldMatrix(true);
  78897. break;
  78898. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78899. returnValue = new this.BJSCANNON.Particle();
  78900. break;
  78901. }
  78902. return returnValue;
  78903. };
  78904. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  78905. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78906. var transform = object.computeWorldMatrix(true);
  78907. // convert rawVerts to object space
  78908. var temp = new Array();
  78909. var index;
  78910. for (index = 0; index < pos.length; index += 3) {
  78911. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  78912. }
  78913. pos = temp;
  78914. var matrix = new Array();
  78915. //For now pointDepth will not be used and will be automatically calculated.
  78916. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  78917. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  78918. var boundingInfo = object.getBoundingInfo();
  78919. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78920. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78921. var elementSize = dim * 2 / arraySize;
  78922. for (var i = 0; i < pos.length; i = i + 3) {
  78923. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78924. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78925. var y = -pos[i + 2] + minY;
  78926. if (!matrix[x]) {
  78927. matrix[x] = [];
  78928. }
  78929. if (!matrix[x][z]) {
  78930. matrix[x][z] = y;
  78931. }
  78932. matrix[x][z] = Math.max(y, matrix[x][z]);
  78933. }
  78934. for (var x = 0; x <= arraySize; ++x) {
  78935. if (!matrix[x]) {
  78936. var loc = 1;
  78937. while (!matrix[(x + loc) % arraySize]) {
  78938. loc++;
  78939. }
  78940. matrix[x] = matrix[(x + loc) % arraySize].slice();
  78941. //console.log("missing x", x);
  78942. }
  78943. for (var z = 0; z <= arraySize; ++z) {
  78944. if (!matrix[x][z]) {
  78945. var loc = 1;
  78946. var newValue;
  78947. while (newValue === undefined) {
  78948. newValue = matrix[x][(z + loc++) % arraySize];
  78949. }
  78950. matrix[x][z] = newValue;
  78951. }
  78952. }
  78953. }
  78954. var shape = new this.BJSCANNON.Heightfield(matrix, {
  78955. elementSize: elementSize
  78956. });
  78957. //For future reference, needed for body transformation
  78958. shape.minY = minY;
  78959. return shape;
  78960. };
  78961. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  78962. var object = impostor.object;
  78963. //make sure it is updated...
  78964. object.computeWorldMatrix && object.computeWorldMatrix(true);
  78965. // The delta between the mesh position and the mesh bounding box center
  78966. var bInfo = object.getBoundingInfo();
  78967. if (!bInfo)
  78968. return;
  78969. var center = impostor.getObjectCenter();
  78970. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  78971. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  78972. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  78973. this._tmpPosition.copyFrom(center);
  78974. var quaternion = object.rotationQuaternion;
  78975. if (!quaternion) {
  78976. return;
  78977. }
  78978. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  78979. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  78980. //-90 DEG in X, precalculated
  78981. quaternion = quaternion.multiply(this._minus90X);
  78982. //Invert! (Precalculated, 90 deg in X)
  78983. //No need to clone. this will never change.
  78984. impostor.setDeltaRotation(this._plus90X);
  78985. }
  78986. //If it is a heightfield, if should be centered.
  78987. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  78988. var mesh = object;
  78989. var boundingInfo = mesh.getBoundingInfo();
  78990. //calculate the correct body position:
  78991. var rotationQuaternion = mesh.rotationQuaternion;
  78992. mesh.rotationQuaternion = this._tmpUnityRotation;
  78993. mesh.computeWorldMatrix(true);
  78994. //get original center with no rotation
  78995. var c = center.clone();
  78996. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  78997. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  78998. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  78999. mesh.setPreTransformMatrix(p);
  79000. mesh.computeWorldMatrix(true);
  79001. //calculate the translation
  79002. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  79003. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  79004. //add it inverted to the delta
  79005. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  79006. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  79007. //rotation is back
  79008. mesh.rotationQuaternion = rotationQuaternion;
  79009. mesh.setPreTransformMatrix(oldPivot);
  79010. mesh.computeWorldMatrix(true);
  79011. }
  79012. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  79013. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  79014. //this._tmpPosition.copyFrom(object.position);
  79015. }
  79016. impostor.setDeltaPosition(this._tmpDeltaPosition);
  79017. //Now update the impostor object
  79018. impostor.physicsBody.position.copy(this._tmpPosition);
  79019. impostor.physicsBody.quaternion.copy(quaternion);
  79020. };
  79021. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79022. impostor.object.position.copyFrom(impostor.physicsBody.position);
  79023. if (impostor.object.rotationQuaternion) {
  79024. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  79025. }
  79026. };
  79027. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79028. impostor.physicsBody.position.copy(newPosition);
  79029. impostor.physicsBody.quaternion.copy(newRotation);
  79030. };
  79031. CannonJSPlugin.prototype.isSupported = function () {
  79032. return this.BJSCANNON !== undefined;
  79033. };
  79034. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79035. impostor.physicsBody.velocity.copy(velocity);
  79036. };
  79037. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79038. impostor.physicsBody.angularVelocity.copy(velocity);
  79039. };
  79040. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79041. var v = impostor.physicsBody.velocity;
  79042. if (!v) {
  79043. return null;
  79044. }
  79045. return new BABYLON.Vector3(v.x, v.y, v.z);
  79046. };
  79047. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79048. var v = impostor.physicsBody.angularVelocity;
  79049. if (!v) {
  79050. return null;
  79051. }
  79052. return new BABYLON.Vector3(v.x, v.y, v.z);
  79053. };
  79054. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79055. impostor.physicsBody.mass = mass;
  79056. impostor.physicsBody.updateMassProperties();
  79057. };
  79058. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  79059. return impostor.physicsBody.mass;
  79060. };
  79061. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  79062. return impostor.physicsBody.material.friction;
  79063. };
  79064. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79065. impostor.physicsBody.material.friction = friction;
  79066. };
  79067. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79068. return impostor.physicsBody.material.restitution;
  79069. };
  79070. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79071. impostor.physicsBody.material.restitution = restitution;
  79072. };
  79073. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  79074. impostor.physicsBody.sleep();
  79075. };
  79076. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  79077. impostor.physicsBody.wakeUp();
  79078. };
  79079. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79080. joint.physicsJoint.distance = maxDistance;
  79081. };
  79082. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79083. // if (!motorIndex) {
  79084. // joint.physicsJoint.enableMotor();
  79085. // }
  79086. // }
  79087. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79088. // if (!motorIndex) {
  79089. // joint.physicsJoint.disableMotor();
  79090. // }
  79091. // }
  79092. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79093. if (!motorIndex) {
  79094. joint.physicsJoint.enableMotor();
  79095. joint.physicsJoint.setMotorSpeed(speed);
  79096. if (maxForce) {
  79097. this.setLimit(joint, maxForce);
  79098. }
  79099. }
  79100. };
  79101. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  79102. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  79103. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  79104. };
  79105. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79106. var body = impostor.physicsBody;
  79107. mesh.position.x = body.position.x;
  79108. mesh.position.y = body.position.y;
  79109. mesh.position.z = body.position.z;
  79110. if (mesh.rotationQuaternion) {
  79111. mesh.rotationQuaternion.x = body.quaternion.x;
  79112. mesh.rotationQuaternion.y = body.quaternion.y;
  79113. mesh.rotationQuaternion.z = body.quaternion.z;
  79114. mesh.rotationQuaternion.w = body.quaternion.w;
  79115. }
  79116. };
  79117. CannonJSPlugin.prototype.getRadius = function (impostor) {
  79118. var shape = impostor.physicsBody.shapes[0];
  79119. return shape.boundingSphereRadius;
  79120. };
  79121. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79122. var shape = impostor.physicsBody.shapes[0];
  79123. result.x = shape.halfExtents.x * 2;
  79124. result.y = shape.halfExtents.y * 2;
  79125. result.z = shape.halfExtents.z * 2;
  79126. };
  79127. CannonJSPlugin.prototype.dispose = function () {
  79128. };
  79129. CannonJSPlugin.prototype._extendNamespace = function () {
  79130. //this will force cannon to execute at least one step when using interpolation
  79131. var step_tmp1 = new this.BJSCANNON.Vec3();
  79132. var Engine = this.BJSCANNON;
  79133. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  79134. maxSubSteps = maxSubSteps || 10;
  79135. timeSinceLastCalled = timeSinceLastCalled || 0;
  79136. if (timeSinceLastCalled === 0) {
  79137. this.internalStep(dt);
  79138. this.time += dt;
  79139. }
  79140. else {
  79141. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  79142. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  79143. var t0 = performance.now();
  79144. for (var i = 0; i !== internalSteps; i++) {
  79145. this.internalStep(dt);
  79146. if (performance.now() - t0 > dt * 1000) {
  79147. break;
  79148. }
  79149. }
  79150. this.time += timeSinceLastCalled;
  79151. var h = this.time % dt;
  79152. var h_div_dt = h / dt;
  79153. var interpvelo = step_tmp1;
  79154. var bodies = this.bodies;
  79155. for (var j = 0; j !== bodies.length; j++) {
  79156. var b = bodies[j];
  79157. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  79158. b.position.vsub(b.previousPosition, interpvelo);
  79159. interpvelo.scale(h_div_dt, interpvelo);
  79160. b.position.vadd(interpvelo, b.interpolatedPosition);
  79161. }
  79162. else {
  79163. b.interpolatedPosition.copy(b.position);
  79164. b.interpolatedQuaternion.copy(b.quaternion);
  79165. }
  79166. }
  79167. }
  79168. };
  79169. };
  79170. return CannonJSPlugin;
  79171. }());
  79172. BABYLON.CannonJSPlugin = CannonJSPlugin;
  79173. })(BABYLON || (BABYLON = {}));
  79174. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  79175. "use strict";
  79176. var BABYLON;
  79177. (function (BABYLON) {
  79178. var OimoJSPlugin = /** @class */ (function () {
  79179. function OimoJSPlugin(iterations) {
  79180. this.name = "OimoJSPlugin";
  79181. this._tmpImpostorsArray = [];
  79182. this._tmpPositionVector = BABYLON.Vector3.Zero();
  79183. this.BJSOIMO = OIMO;
  79184. this.world = new this.BJSOIMO.World({
  79185. iterations: iterations
  79186. });
  79187. this.world.clear();
  79188. }
  79189. OimoJSPlugin.prototype.setGravity = function (gravity) {
  79190. this.world.gravity.copy(gravity);
  79191. };
  79192. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  79193. this.world.timeStep = timeStep;
  79194. };
  79195. OimoJSPlugin.prototype.getTimeStep = function () {
  79196. return this.world.timeStep;
  79197. };
  79198. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  79199. var _this = this;
  79200. impostors.forEach(function (impostor) {
  79201. impostor.beforeStep();
  79202. });
  79203. this.world.step();
  79204. impostors.forEach(function (impostor) {
  79205. impostor.afterStep();
  79206. //update the ordered impostors array
  79207. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  79208. });
  79209. //check for collisions
  79210. var contact = this.world.contacts;
  79211. while (contact !== null) {
  79212. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  79213. contact = contact.next;
  79214. continue;
  79215. }
  79216. //is this body colliding with any other? get the impostor
  79217. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  79218. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  79219. if (!mainImpostor || !collidingImpostor) {
  79220. contact = contact.next;
  79221. continue;
  79222. }
  79223. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  79224. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  79225. contact = contact.next;
  79226. }
  79227. };
  79228. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  79229. var mass = impostor.physicsBody.mass;
  79230. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  79231. };
  79232. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  79233. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  79234. this.applyImpulse(impostor, force, contactPoint);
  79235. };
  79236. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  79237. var _this = this;
  79238. //parent-child relationship. Does this impostor has a parent impostor?
  79239. if (impostor.parent) {
  79240. if (impostor.physicsBody) {
  79241. this.removePhysicsBody(impostor);
  79242. //TODO is that needed?
  79243. impostor.forceUpdate();
  79244. }
  79245. return;
  79246. }
  79247. if (impostor.isBodyInitRequired()) {
  79248. var bodyConfig = {
  79249. name: impostor.uniqueId,
  79250. //Oimo must have mass, also for static objects.
  79251. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  79252. size: [],
  79253. type: [],
  79254. pos: [],
  79255. posShape: [],
  79256. rot: [],
  79257. rotShape: [],
  79258. move: impostor.getParam("mass") !== 0,
  79259. density: impostor.getParam("mass"),
  79260. friction: impostor.getParam("friction"),
  79261. restitution: impostor.getParam("restitution"),
  79262. //Supporting older versions of Oimo
  79263. world: this.world
  79264. };
  79265. var impostors = [impostor];
  79266. var addToArray = function (parent) {
  79267. if (!parent.getChildMeshes)
  79268. return;
  79269. parent.getChildMeshes().forEach(function (m) {
  79270. if (m.physicsImpostor) {
  79271. impostors.push(m.physicsImpostor);
  79272. //m.physicsImpostor._init();
  79273. }
  79274. });
  79275. };
  79276. addToArray(impostor.object);
  79277. var checkWithEpsilon_1 = function (value) {
  79278. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  79279. };
  79280. impostors.forEach(function (i) {
  79281. if (!i.object.rotationQuaternion) {
  79282. return;
  79283. }
  79284. //get the correct bounding box
  79285. var oldQuaternion = i.object.rotationQuaternion;
  79286. var rot = oldQuaternion.toEulerAngles();
  79287. var extendSize = i.getObjectExtendSize();
  79288. var radToDeg = 57.295779513082320876;
  79289. if (i === impostor) {
  79290. var center = impostor.getObjectCenter();
  79291. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  79292. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  79293. //Can also use Array.prototype.push.apply
  79294. bodyConfig.pos.push(center.x);
  79295. bodyConfig.pos.push(center.y);
  79296. bodyConfig.pos.push(center.z);
  79297. bodyConfig.posShape.push(0, 0, 0);
  79298. //tmp solution
  79299. bodyConfig.rot.push(rot.x * radToDeg);
  79300. bodyConfig.rot.push(rot.y * radToDeg);
  79301. bodyConfig.rot.push(rot.z * radToDeg);
  79302. bodyConfig.rotShape.push(0, 0, 0);
  79303. }
  79304. else {
  79305. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  79306. bodyConfig.posShape.push(localPosition.x);
  79307. bodyConfig.posShape.push(localPosition.y);
  79308. bodyConfig.posShape.push(localPosition.z);
  79309. bodyConfig.pos.push(0, 0, 0);
  79310. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  79311. bodyConfig.rot.push(0);
  79312. bodyConfig.rot.push(0);
  79313. bodyConfig.rot.push(0);
  79314. bodyConfig.rotShape.push(rot.x * radToDeg);
  79315. bodyConfig.rotShape.push(rot.y * radToDeg);
  79316. bodyConfig.rotShape.push(rot.z * radToDeg);
  79317. }
  79318. // register mesh
  79319. switch (i.type) {
  79320. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79321. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  79322. case BABYLON.PhysicsImpostor.SphereImpostor:
  79323. var radiusX = extendSize.x;
  79324. var radiusY = extendSize.y;
  79325. var radiusZ = extendSize.z;
  79326. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  79327. bodyConfig.type.push('sphere');
  79328. //due to the way oimo works with compounds, add 3 times
  79329. bodyConfig.size.push(size);
  79330. bodyConfig.size.push(size);
  79331. bodyConfig.size.push(size);
  79332. break;
  79333. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79334. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  79335. var sizeY = checkWithEpsilon_1(extendSize.y);
  79336. bodyConfig.type.push('cylinder');
  79337. bodyConfig.size.push(sizeX);
  79338. bodyConfig.size.push(sizeY);
  79339. //due to the way oimo works with compounds, add one more value.
  79340. bodyConfig.size.push(sizeY);
  79341. break;
  79342. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79343. case BABYLON.PhysicsImpostor.BoxImpostor:
  79344. default:
  79345. var sizeX = checkWithEpsilon_1(extendSize.x);
  79346. var sizeY = checkWithEpsilon_1(extendSize.y);
  79347. var sizeZ = checkWithEpsilon_1(extendSize.z);
  79348. bodyConfig.type.push('box');
  79349. //if (i === impostor) {
  79350. bodyConfig.size.push(sizeX);
  79351. bodyConfig.size.push(sizeY);
  79352. bodyConfig.size.push(sizeZ);
  79353. //} else {
  79354. // bodyConfig.size.push(0,0,0);
  79355. //}
  79356. break;
  79357. }
  79358. //actually not needed, but hey...
  79359. i.object.rotationQuaternion = oldQuaternion;
  79360. });
  79361. impostor.physicsBody = this.world.add(bodyConfig);
  79362. }
  79363. else {
  79364. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  79365. }
  79366. impostor.setDeltaPosition(this._tmpPositionVector);
  79367. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  79368. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  79369. };
  79370. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79371. //impostor.physicsBody.dispose();
  79372. //Same as : (older oimo versions)
  79373. this.world.removeRigidBody(impostor.physicsBody);
  79374. };
  79375. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79376. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79377. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79378. if (!mainBody || !connectedBody) {
  79379. return;
  79380. }
  79381. var jointData = impostorJoint.joint.jointData;
  79382. var options = jointData.nativeParams || {};
  79383. var type;
  79384. var nativeJointData = {
  79385. body1: mainBody,
  79386. body2: connectedBody,
  79387. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79388. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79389. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79390. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79391. min: options.min,
  79392. max: options.max,
  79393. collision: options.collision || jointData.collision,
  79394. spring: options.spring,
  79395. //supporting older version of Oimo
  79396. world: this.world
  79397. };
  79398. switch (impostorJoint.joint.type) {
  79399. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79400. type = "jointBall";
  79401. break;
  79402. case BABYLON.PhysicsJoint.SpringJoint:
  79403. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79404. var springData = jointData;
  79405. nativeJointData.min = springData.length || nativeJointData.min;
  79406. //Max should also be set, just make sure it is at least min
  79407. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79408. case BABYLON.PhysicsJoint.DistanceJoint:
  79409. type = "jointDistance";
  79410. nativeJointData.max = jointData.maxDistance;
  79411. break;
  79412. case BABYLON.PhysicsJoint.PrismaticJoint:
  79413. type = "jointPrisme";
  79414. break;
  79415. case BABYLON.PhysicsJoint.SliderJoint:
  79416. type = "jointSlide";
  79417. break;
  79418. case BABYLON.PhysicsJoint.WheelJoint:
  79419. type = "jointWheel";
  79420. break;
  79421. case BABYLON.PhysicsJoint.HingeJoint:
  79422. default:
  79423. type = "jointHinge";
  79424. break;
  79425. }
  79426. nativeJointData.type = type;
  79427. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  79428. };
  79429. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79430. //Bug in Oimo prevents us from disposing a joint in the playground
  79431. //joint.joint.physicsJoint.dispose();
  79432. //So we will bruteforce it!
  79433. try {
  79434. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79435. }
  79436. catch (e) {
  79437. BABYLON.Tools.Warn(e);
  79438. }
  79439. };
  79440. OimoJSPlugin.prototype.isSupported = function () {
  79441. return this.BJSOIMO !== undefined;
  79442. };
  79443. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79444. if (!impostor.physicsBody.sleeping) {
  79445. //TODO check that
  79446. /*if (impostor.physicsBody.shapes.next) {
  79447. var parentShape = this._getLastShape(impostor.physicsBody);
  79448. impostor.object.position.copyFrom(parentShape.position);
  79449. console.log(parentShape.position);
  79450. } else {*/
  79451. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79452. //}
  79453. if (impostor.object.rotationQuaternion) {
  79454. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79455. }
  79456. }
  79457. };
  79458. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79459. var body = impostor.physicsBody;
  79460. body.position.copy(newPosition);
  79461. body.orientation.copy(newRotation);
  79462. body.syncShapes();
  79463. body.awake();
  79464. };
  79465. /*private _getLastShape(body: any): any {
  79466. var lastShape = body.shapes;
  79467. while (lastShape.next) {
  79468. lastShape = lastShape.next;
  79469. }
  79470. return lastShape;
  79471. }*/
  79472. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79473. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79474. };
  79475. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79476. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79477. };
  79478. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79479. var v = impostor.physicsBody.linearVelocity;
  79480. if (!v) {
  79481. return null;
  79482. }
  79483. return new BABYLON.Vector3(v.x, v.y, v.z);
  79484. };
  79485. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79486. var v = impostor.physicsBody.angularVelocity;
  79487. if (!v) {
  79488. return null;
  79489. }
  79490. return new BABYLON.Vector3(v.x, v.y, v.z);
  79491. };
  79492. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79493. var staticBody = mass === 0;
  79494. //this will actually set the body's density and not its mass.
  79495. //But this is how oimo treats the mass variable.
  79496. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79497. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79498. };
  79499. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79500. return impostor.physicsBody.shapes.density;
  79501. };
  79502. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79503. return impostor.physicsBody.shapes.friction;
  79504. };
  79505. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79506. impostor.physicsBody.shapes.friction = friction;
  79507. };
  79508. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79509. return impostor.physicsBody.shapes.restitution;
  79510. };
  79511. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79512. impostor.physicsBody.shapes.restitution = restitution;
  79513. };
  79514. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79515. impostor.physicsBody.sleep();
  79516. };
  79517. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79518. impostor.physicsBody.awake();
  79519. };
  79520. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79521. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79522. if (minDistance !== void 0) {
  79523. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79524. }
  79525. };
  79526. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79527. //TODO separate rotational and transational motors.
  79528. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79529. if (motor) {
  79530. motor.setMotor(speed, maxForce);
  79531. }
  79532. };
  79533. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79534. //TODO separate rotational and transational motors.
  79535. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79536. if (motor) {
  79537. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79538. }
  79539. };
  79540. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79541. var body = impostor.physicsBody;
  79542. mesh.position.x = body.position.x;
  79543. mesh.position.y = body.position.y;
  79544. mesh.position.z = body.position.z;
  79545. if (mesh.rotationQuaternion) {
  79546. mesh.rotationQuaternion.x = body.orientation.x;
  79547. mesh.rotationQuaternion.y = body.orientation.y;
  79548. mesh.rotationQuaternion.z = body.orientation.z;
  79549. mesh.rotationQuaternion.w = body.orientation.s;
  79550. }
  79551. };
  79552. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79553. return impostor.physicsBody.shapes.radius;
  79554. };
  79555. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79556. var shape = impostor.physicsBody.shapes;
  79557. result.x = shape.halfWidth * 2;
  79558. result.y = shape.halfHeight * 2;
  79559. result.z = shape.halfDepth * 2;
  79560. };
  79561. OimoJSPlugin.prototype.dispose = function () {
  79562. this.world.clear();
  79563. };
  79564. return OimoJSPlugin;
  79565. }());
  79566. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79567. })(BABYLON || (BABYLON = {}));
  79568. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79569. "use strict";
  79570. var BABYLON;
  79571. (function (BABYLON) {
  79572. /*
  79573. * Based on jsTGALoader - Javascript loader for TGA file
  79574. * By Vincent Thibault
  79575. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79576. */
  79577. var TGATools = /** @class */ (function () {
  79578. function TGATools() {
  79579. }
  79580. TGATools.GetTGAHeader = function (data) {
  79581. var offset = 0;
  79582. var header = {
  79583. id_length: data[offset++],
  79584. colormap_type: data[offset++],
  79585. image_type: data[offset++],
  79586. colormap_index: data[offset++] | data[offset++] << 8,
  79587. colormap_length: data[offset++] | data[offset++] << 8,
  79588. colormap_size: data[offset++],
  79589. origin: [
  79590. data[offset++] | data[offset++] << 8,
  79591. data[offset++] | data[offset++] << 8
  79592. ],
  79593. width: data[offset++] | data[offset++] << 8,
  79594. height: data[offset++] | data[offset++] << 8,
  79595. pixel_size: data[offset++],
  79596. flags: data[offset++]
  79597. };
  79598. return header;
  79599. };
  79600. TGATools.UploadContent = function (gl, data) {
  79601. // Not enough data to contain header ?
  79602. if (data.length < 19) {
  79603. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79604. return;
  79605. }
  79606. // Read Header
  79607. var offset = 18;
  79608. var header = TGATools.GetTGAHeader(data);
  79609. // Assume it's a valid Targa file.
  79610. if (header.id_length + offset > data.length) {
  79611. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79612. return;
  79613. }
  79614. // Skip not needed data
  79615. offset += header.id_length;
  79616. var use_rle = false;
  79617. var use_pal = false;
  79618. var use_grey = false;
  79619. // Get some informations.
  79620. switch (header.image_type) {
  79621. case TGATools._TYPE_RLE_INDEXED:
  79622. use_rle = true;
  79623. case TGATools._TYPE_INDEXED:
  79624. use_pal = true;
  79625. break;
  79626. case TGATools._TYPE_RLE_RGB:
  79627. use_rle = true;
  79628. case TGATools._TYPE_RGB:
  79629. // use_rgb = true;
  79630. break;
  79631. case TGATools._TYPE_RLE_GREY:
  79632. use_rle = true;
  79633. case TGATools._TYPE_GREY:
  79634. use_grey = true;
  79635. break;
  79636. }
  79637. var pixel_data;
  79638. // var numAlphaBits = header.flags & 0xf;
  79639. var pixel_size = header.pixel_size >> 3;
  79640. var pixel_total = header.width * header.height * pixel_size;
  79641. // Read palettes
  79642. var palettes;
  79643. if (use_pal) {
  79644. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79645. }
  79646. // Read LRE
  79647. if (use_rle) {
  79648. pixel_data = new Uint8Array(pixel_total);
  79649. var c, count, i;
  79650. var localOffset = 0;
  79651. var pixels = new Uint8Array(pixel_size);
  79652. while (offset < pixel_total && localOffset < pixel_total) {
  79653. c = data[offset++];
  79654. count = (c & 0x7f) + 1;
  79655. // RLE pixels
  79656. if (c & 0x80) {
  79657. // Bind pixel tmp array
  79658. for (i = 0; i < pixel_size; ++i) {
  79659. pixels[i] = data[offset++];
  79660. }
  79661. // Copy pixel array
  79662. for (i = 0; i < count; ++i) {
  79663. pixel_data.set(pixels, localOffset + i * pixel_size);
  79664. }
  79665. localOffset += pixel_size * count;
  79666. }
  79667. else {
  79668. count *= pixel_size;
  79669. for (i = 0; i < count; ++i) {
  79670. pixel_data[localOffset + i] = data[offset++];
  79671. }
  79672. localOffset += count;
  79673. }
  79674. }
  79675. }
  79676. else {
  79677. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79678. }
  79679. // Load to texture
  79680. var x_start, y_start, x_step, y_step, y_end, x_end;
  79681. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79682. default:
  79683. case TGATools._ORIGIN_UL:
  79684. x_start = 0;
  79685. x_step = 1;
  79686. x_end = header.width;
  79687. y_start = 0;
  79688. y_step = 1;
  79689. y_end = header.height;
  79690. break;
  79691. case TGATools._ORIGIN_BL:
  79692. x_start = 0;
  79693. x_step = 1;
  79694. x_end = header.width;
  79695. y_start = header.height - 1;
  79696. y_step = -1;
  79697. y_end = -1;
  79698. break;
  79699. case TGATools._ORIGIN_UR:
  79700. x_start = header.width - 1;
  79701. x_step = -1;
  79702. x_end = -1;
  79703. y_start = 0;
  79704. y_step = 1;
  79705. y_end = header.height;
  79706. break;
  79707. case TGATools._ORIGIN_BR:
  79708. x_start = header.width - 1;
  79709. x_step = -1;
  79710. x_end = -1;
  79711. y_start = header.height - 1;
  79712. y_step = -1;
  79713. y_end = -1;
  79714. break;
  79715. }
  79716. // Load the specify method
  79717. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79718. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79719. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79720. };
  79721. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79722. var image = pixel_data, colormap = palettes;
  79723. var width = header.width, height = header.height;
  79724. var color, i = 0, x, y;
  79725. var imageData = new Uint8Array(width * height * 4);
  79726. for (y = y_start; y !== y_end; y += y_step) {
  79727. for (x = x_start; x !== x_end; x += x_step, i++) {
  79728. color = image[i];
  79729. imageData[(x + width * y) * 4 + 3] = 255;
  79730. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79731. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79732. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79733. }
  79734. }
  79735. return imageData;
  79736. };
  79737. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79738. var image = pixel_data;
  79739. var width = header.width, height = header.height;
  79740. var color, i = 0, x, y;
  79741. var imageData = new Uint8Array(width * height * 4);
  79742. for (y = y_start; y !== y_end; y += y_step) {
  79743. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79744. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79745. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79746. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79747. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79748. imageData[(x + width * y) * 4 + 0] = r;
  79749. imageData[(x + width * y) * 4 + 1] = g;
  79750. imageData[(x + width * y) * 4 + 2] = b;
  79751. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79752. }
  79753. }
  79754. return imageData;
  79755. };
  79756. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79757. var image = pixel_data;
  79758. var width = header.width, height = header.height;
  79759. var i = 0, x, y;
  79760. var imageData = new Uint8Array(width * height * 4);
  79761. for (y = y_start; y !== y_end; y += y_step) {
  79762. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79763. imageData[(x + width * y) * 4 + 3] = 255;
  79764. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79765. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79766. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79767. }
  79768. }
  79769. return imageData;
  79770. };
  79771. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79772. var image = pixel_data;
  79773. var width = header.width, height = header.height;
  79774. var i = 0, x, y;
  79775. var imageData = new Uint8Array(width * height * 4);
  79776. for (y = y_start; y !== y_end; y += y_step) {
  79777. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79778. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79779. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79780. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79781. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79782. }
  79783. }
  79784. return imageData;
  79785. };
  79786. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79787. var image = pixel_data;
  79788. var width = header.width, height = header.height;
  79789. var color, i = 0, x, y;
  79790. var imageData = new Uint8Array(width * height * 4);
  79791. for (y = y_start; y !== y_end; y += y_step) {
  79792. for (x = x_start; x !== x_end; x += x_step, i++) {
  79793. color = image[i];
  79794. imageData[(x + width * y) * 4 + 0] = color;
  79795. imageData[(x + width * y) * 4 + 1] = color;
  79796. imageData[(x + width * y) * 4 + 2] = color;
  79797. imageData[(x + width * y) * 4 + 3] = 255;
  79798. }
  79799. }
  79800. return imageData;
  79801. };
  79802. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79803. var image = pixel_data;
  79804. var width = header.width, height = header.height;
  79805. var i = 0, x, y;
  79806. var imageData = new Uint8Array(width * height * 4);
  79807. for (y = y_start; y !== y_end; y += y_step) {
  79808. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79809. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79810. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79811. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79812. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79813. }
  79814. }
  79815. return imageData;
  79816. };
  79817. //private static _TYPE_NO_DATA = 0;
  79818. TGATools._TYPE_INDEXED = 1;
  79819. TGATools._TYPE_RGB = 2;
  79820. TGATools._TYPE_GREY = 3;
  79821. TGATools._TYPE_RLE_INDEXED = 9;
  79822. TGATools._TYPE_RLE_RGB = 10;
  79823. TGATools._TYPE_RLE_GREY = 11;
  79824. TGATools._ORIGIN_MASK = 0x30;
  79825. TGATools._ORIGIN_SHIFT = 0x04;
  79826. TGATools._ORIGIN_BL = 0x00;
  79827. TGATools._ORIGIN_BR = 0x01;
  79828. TGATools._ORIGIN_UL = 0x02;
  79829. TGATools._ORIGIN_UR = 0x03;
  79830. return TGATools;
  79831. }());
  79832. BABYLON.TGATools = TGATools;
  79833. })(BABYLON || (BABYLON = {}));
  79834. //# sourceMappingURL=babylon.tga.js.map
  79835. "use strict";
  79836. var BABYLON;
  79837. (function (BABYLON) {
  79838. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  79839. // All values and structures referenced from:
  79840. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  79841. var DDS_MAGIC = 0x20534444;
  79842. var
  79843. //DDSD_CAPS = 0x1,
  79844. //DDSD_HEIGHT = 0x2,
  79845. //DDSD_WIDTH = 0x4,
  79846. //DDSD_PITCH = 0x8,
  79847. //DDSD_PIXELFORMAT = 0x1000,
  79848. DDSD_MIPMAPCOUNT = 0x20000;
  79849. //DDSD_LINEARSIZE = 0x80000,
  79850. //DDSD_DEPTH = 0x800000;
  79851. // var DDSCAPS_COMPLEX = 0x8,
  79852. // DDSCAPS_MIPMAP = 0x400000,
  79853. // DDSCAPS_TEXTURE = 0x1000;
  79854. var DDSCAPS2_CUBEMAP = 0x200;
  79855. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  79856. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  79857. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  79858. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  79859. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  79860. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  79861. // DDSCAPS2_VOLUME = 0x200000;
  79862. var
  79863. //DDPF_ALPHAPIXELS = 0x1,
  79864. //DDPF_ALPHA = 0x2,
  79865. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  79866. //DDPF_YUV = 0x200,
  79867. DDPF_LUMINANCE = 0x20000;
  79868. function FourCCToInt32(value) {
  79869. return value.charCodeAt(0) +
  79870. (value.charCodeAt(1) << 8) +
  79871. (value.charCodeAt(2) << 16) +
  79872. (value.charCodeAt(3) << 24);
  79873. }
  79874. function Int32ToFourCC(value) {
  79875. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  79876. }
  79877. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  79878. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  79879. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  79880. var FOURCC_DX10 = FourCCToInt32("DX10");
  79881. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  79882. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  79883. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  79884. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  79885. var headerLengthInt = 31; // The header length in 32 bit ints
  79886. // Offsets into the header array
  79887. var off_magic = 0;
  79888. var off_size = 1;
  79889. var off_flags = 2;
  79890. var off_height = 3;
  79891. var off_width = 4;
  79892. var off_mipmapCount = 7;
  79893. var off_pfFlags = 20;
  79894. var off_pfFourCC = 21;
  79895. var off_RGBbpp = 22;
  79896. var off_RMask = 23;
  79897. var off_GMask = 24;
  79898. var off_BMask = 25;
  79899. var off_AMask = 26;
  79900. // var off_caps1 = 27;
  79901. var off_caps2 = 28;
  79902. // var off_caps3 = 29;
  79903. // var off_caps4 = 30;
  79904. var off_dxgiFormat = 32;
  79905. ;
  79906. var DDSTools = /** @class */ (function () {
  79907. function DDSTools() {
  79908. }
  79909. DDSTools.GetDDSInfo = function (arrayBuffer) {
  79910. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79911. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  79912. var mipmapCount = 1;
  79913. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  79914. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79915. }
  79916. var fourCC = header[off_pfFourCC];
  79917. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  79918. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79919. switch (fourCC) {
  79920. case FOURCC_D3DFMT_R16G16B16A16F:
  79921. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79922. break;
  79923. case FOURCC_D3DFMT_R32G32B32A32F:
  79924. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79925. break;
  79926. case FOURCC_DX10:
  79927. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  79928. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79929. break;
  79930. }
  79931. }
  79932. return {
  79933. width: header[off_width],
  79934. height: header[off_height],
  79935. mipmapCount: mipmapCount,
  79936. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  79937. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  79938. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  79939. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  79940. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  79941. dxgiFormat: dxgiFormat,
  79942. textureType: textureType
  79943. };
  79944. };
  79945. DDSTools._ToHalfFloat = function (value) {
  79946. if (!DDSTools._FloatView) {
  79947. DDSTools._FloatView = new Float32Array(1);
  79948. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  79949. }
  79950. DDSTools._FloatView[0] = value;
  79951. var x = DDSTools._Int32View[0];
  79952. var bits = (x >> 16) & 0x8000; /* Get the sign */
  79953. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  79954. var e = (x >> 23) & 0xff; /* Using int is faster here */
  79955. /* If zero, or denormal, or exponent underflows too much for a denormal
  79956. * half, return signed zero. */
  79957. if (e < 103) {
  79958. return bits;
  79959. }
  79960. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  79961. if (e > 142) {
  79962. bits |= 0x7c00;
  79963. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  79964. * not Inf, so make sure we set one mantissa bit too. */
  79965. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  79966. return bits;
  79967. }
  79968. /* If exponent underflows but not too much, return a denormal */
  79969. if (e < 113) {
  79970. m |= 0x0800;
  79971. /* Extra rounding may overflow and set mantissa to 0 and exponent
  79972. * to 1, which is OK. */
  79973. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  79974. return bits;
  79975. }
  79976. bits |= ((e - 112) << 10) | (m >> 1);
  79977. bits += m & 1;
  79978. return bits;
  79979. };
  79980. DDSTools._FromHalfFloat = function (value) {
  79981. var s = (value & 0x8000) >> 15;
  79982. var e = (value & 0x7C00) >> 10;
  79983. var f = value & 0x03FF;
  79984. if (e === 0) {
  79985. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  79986. }
  79987. else if (e == 0x1F) {
  79988. return f ? NaN : ((s ? -1 : 1) * Infinity);
  79989. }
  79990. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  79991. };
  79992. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79993. var destArray = new Float32Array(dataLength);
  79994. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79995. var index = 0;
  79996. for (var y = 0; y < height; y++) {
  79997. for (var x = 0; x < width; x++) {
  79998. var srcPos = (x + y * width) * 4;
  79999. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  80000. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  80001. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  80002. if (DDSTools.StoreLODInAlphaChannel) {
  80003. destArray[index + 3] = lod;
  80004. }
  80005. else {
  80006. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  80007. }
  80008. index += 4;
  80009. }
  80010. }
  80011. return destArray;
  80012. };
  80013. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80014. if (DDSTools.StoreLODInAlphaChannel) {
  80015. var destArray = new Uint16Array(dataLength);
  80016. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80017. var index = 0;
  80018. for (var y = 0; y < height; y++) {
  80019. for (var x = 0; x < width; x++) {
  80020. var srcPos = (x + y * width) * 4;
  80021. destArray[index] = srcData[srcPos];
  80022. destArray[index + 1] = srcData[srcPos + 1];
  80023. destArray[index + 2] = srcData[srcPos + 2];
  80024. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  80025. index += 4;
  80026. }
  80027. }
  80028. return destArray;
  80029. }
  80030. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  80031. };
  80032. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80033. if (DDSTools.StoreLODInAlphaChannel) {
  80034. var destArray = new Float32Array(dataLength);
  80035. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80036. var index = 0;
  80037. for (var y = 0; y < height; y++) {
  80038. for (var x = 0; x < width; x++) {
  80039. var srcPos = (x + y * width) * 4;
  80040. destArray[index] = srcData[srcPos];
  80041. destArray[index + 1] = srcData[srcPos + 1];
  80042. destArray[index + 2] = srcData[srcPos + 2];
  80043. destArray[index + 3] = lod;
  80044. index += 4;
  80045. }
  80046. }
  80047. return destArray;
  80048. }
  80049. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  80050. };
  80051. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80052. var destArray = new Uint8Array(dataLength);
  80053. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80054. var index = 0;
  80055. for (var y = 0; y < height; y++) {
  80056. for (var x = 0; x < width; x++) {
  80057. var srcPos = (x + y * width) * 4;
  80058. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  80059. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  80060. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  80061. if (DDSTools.StoreLODInAlphaChannel) {
  80062. destArray[index + 3] = lod;
  80063. }
  80064. else {
  80065. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  80066. }
  80067. index += 4;
  80068. }
  80069. }
  80070. return destArray;
  80071. };
  80072. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80073. var destArray = new Uint8Array(dataLength);
  80074. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80075. var index = 0;
  80076. for (var y = 0; y < height; y++) {
  80077. for (var x = 0; x < width; x++) {
  80078. var srcPos = (x + y * width) * 4;
  80079. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  80080. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  80081. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  80082. if (DDSTools.StoreLODInAlphaChannel) {
  80083. destArray[index + 3] = lod;
  80084. }
  80085. else {
  80086. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  80087. }
  80088. index += 4;
  80089. }
  80090. }
  80091. return destArray;
  80092. };
  80093. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  80094. var byteArray = new Uint8Array(dataLength);
  80095. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80096. var index = 0;
  80097. for (var y = 0; y < height; y++) {
  80098. for (var x = 0; x < width; x++) {
  80099. var srcPos = (x + y * width) * 4;
  80100. byteArray[index] = srcData[srcPos + rOffset];
  80101. byteArray[index + 1] = srcData[srcPos + gOffset];
  80102. byteArray[index + 2] = srcData[srcPos + bOffset];
  80103. byteArray[index + 3] = srcData[srcPos + aOffset];
  80104. index += 4;
  80105. }
  80106. }
  80107. return byteArray;
  80108. };
  80109. DDSTools._ExtractLongWordOrder = function (value) {
  80110. if (value === 0 || value === 255 || value === -16777216) {
  80111. return 0;
  80112. }
  80113. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  80114. };
  80115. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  80116. var byteArray = new Uint8Array(dataLength);
  80117. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80118. var index = 0;
  80119. for (var y = 0; y < height; y++) {
  80120. for (var x = 0; x < width; x++) {
  80121. var srcPos = (x + y * width) * 3;
  80122. byteArray[index] = srcData[srcPos + rOffset];
  80123. byteArray[index + 1] = srcData[srcPos + gOffset];
  80124. byteArray[index + 2] = srcData[srcPos + bOffset];
  80125. index += 3;
  80126. }
  80127. }
  80128. return byteArray;
  80129. };
  80130. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  80131. var byteArray = new Uint8Array(dataLength);
  80132. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80133. var index = 0;
  80134. for (var y = 0; y < height; y++) {
  80135. for (var x = 0; x < width; x++) {
  80136. var srcPos = (x + y * width);
  80137. byteArray[index] = srcData[srcPos];
  80138. index++;
  80139. }
  80140. }
  80141. return byteArray;
  80142. };
  80143. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  80144. if (lodIndex === void 0) { lodIndex = -1; }
  80145. var ext = engine.getCaps().s3tc;
  80146. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  80147. var fourCC, width, height, dataLength = 0, dataOffset;
  80148. var byteArray, mipmapCount, mip;
  80149. var internalFormat = 0;
  80150. var format = 0;
  80151. var blockBytes = 1;
  80152. if (header[off_magic] !== DDS_MAGIC) {
  80153. BABYLON.Tools.Error("Invalid magic number in DDS header");
  80154. return;
  80155. }
  80156. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  80157. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  80158. return;
  80159. }
  80160. if (info.isCompressed && !ext) {
  80161. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  80162. return;
  80163. }
  80164. var bpp = header[off_RGBbpp];
  80165. dataOffset = header[off_size] + 4;
  80166. var computeFormats = false;
  80167. if (info.isFourCC) {
  80168. fourCC = header[off_pfFourCC];
  80169. switch (fourCC) {
  80170. case FOURCC_DXT1:
  80171. blockBytes = 8;
  80172. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  80173. break;
  80174. case FOURCC_DXT3:
  80175. blockBytes = 16;
  80176. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  80177. break;
  80178. case FOURCC_DXT5:
  80179. blockBytes = 16;
  80180. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  80181. break;
  80182. case FOURCC_D3DFMT_R16G16B16A16F:
  80183. computeFormats = true;
  80184. break;
  80185. case FOURCC_D3DFMT_R32G32B32A32F:
  80186. computeFormats = true;
  80187. break;
  80188. case FOURCC_DX10:
  80189. // There is an additionnal header so dataOffset need to be changed
  80190. dataOffset += 5 * 4; // 5 uints
  80191. var supported = false;
  80192. switch (info.dxgiFormat) {
  80193. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  80194. computeFormats = true;
  80195. supported = true;
  80196. break;
  80197. case DXGI_FORMAT_B8G8R8X8_UNORM:
  80198. info.isRGB = true;
  80199. info.isFourCC = false;
  80200. bpp = 32;
  80201. supported = true;
  80202. break;
  80203. }
  80204. if (supported) {
  80205. break;
  80206. }
  80207. default:
  80208. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  80209. return;
  80210. }
  80211. }
  80212. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  80213. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  80214. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  80215. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  80216. if (computeFormats) {
  80217. format = engine._getWebGLTextureType(info.textureType);
  80218. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80219. }
  80220. mipmapCount = 1;
  80221. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  80222. mipmapCount = Math.max(1, header[off_mipmapCount]);
  80223. }
  80224. for (var face = 0; face < faces; face++) {
  80225. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  80226. width = header[off_width];
  80227. height = header[off_height];
  80228. for (mip = 0; mip < mipmapCount; ++mip) {
  80229. if (lodIndex === -1 || lodIndex === mip) {
  80230. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  80231. var i = (lodIndex === -1) ? mip : 0;
  80232. if (!info.isCompressed && info.isFourCC) {
  80233. dataLength = width * height * 4;
  80234. var floatArray = null;
  80235. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  80236. if (bpp === 128) {
  80237. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80238. }
  80239. else if (bpp === 64) {
  80240. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80241. }
  80242. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80243. format = engine._getWebGLTextureType(info.textureType);
  80244. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80245. }
  80246. else {
  80247. if (bpp === 128) {
  80248. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80249. }
  80250. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  80251. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80252. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80253. format = engine._getWebGLTextureType(info.textureType);
  80254. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80255. }
  80256. else {
  80257. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80258. }
  80259. }
  80260. if (floatArray) {
  80261. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  80262. }
  80263. }
  80264. else if (info.isRGB) {
  80265. if (bpp === 24) {
  80266. dataLength = width * height * 3;
  80267. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  80268. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  80269. }
  80270. else {
  80271. dataLength = width * height * 4;
  80272. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  80273. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  80274. }
  80275. }
  80276. else if (info.isLuminance) {
  80277. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  80278. var unpaddedRowSize = width;
  80279. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  80280. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  80281. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  80282. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  80283. }
  80284. else {
  80285. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  80286. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  80287. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  80288. }
  80289. }
  80290. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  80291. width *= 0.5;
  80292. height *= 0.5;
  80293. width = Math.max(1.0, width);
  80294. height = Math.max(1.0, height);
  80295. }
  80296. if (currentFace !== undefined) {
  80297. // Loading a single face
  80298. break;
  80299. }
  80300. }
  80301. };
  80302. DDSTools.StoreLODInAlphaChannel = false;
  80303. return DDSTools;
  80304. }());
  80305. BABYLON.DDSTools = DDSTools;
  80306. })(BABYLON || (BABYLON = {}));
  80307. //# sourceMappingURL=babylon.dds.js.map
  80308. "use strict";
  80309. var BABYLON;
  80310. (function (BABYLON) {
  80311. /**
  80312. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  80313. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  80314. */
  80315. var KhronosTextureContainer = /** @class */ (function () {
  80316. /**
  80317. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  80318. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  80319. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  80320. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  80321. */
  80322. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  80323. this.arrayBuffer = arrayBuffer;
  80324. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  80325. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  80326. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  80327. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  80328. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  80329. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  80330. BABYLON.Tools.Error("texture missing KTX identifier");
  80331. return;
  80332. }
  80333. // load the reset of the header in native 32 bit int
  80334. var header = new Int32Array(this.arrayBuffer, 12, 13);
  80335. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  80336. var oppositeEndianess = header[0] === 0x01020304;
  80337. // read all the header elements in order they exist in the file, without modification (sans endainness)
  80338. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  80339. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  80340. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  80341. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  80342. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  80343. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  80344. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  80345. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  80346. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  80347. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  80348. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  80349. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  80350. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  80351. if (this.glType !== 0) {
  80352. BABYLON.Tools.Error("only compressed formats currently supported");
  80353. return;
  80354. }
  80355. else {
  80356. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  80357. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  80358. }
  80359. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  80360. BABYLON.Tools.Error("only 2D textures currently supported");
  80361. return;
  80362. }
  80363. if (this.numberOfArrayElements !== 0) {
  80364. BABYLON.Tools.Error("texture arrays not currently supported");
  80365. return;
  80366. }
  80367. if (this.numberOfFaces !== facesExpected) {
  80368. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  80369. return;
  80370. }
  80371. // we now have a completely validated file, so could use existence of loadType as success
  80372. // would need to make this more elaborate & adjust checks above to support more than one load type
  80373. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80374. }
  80375. // not as fast hardware based, but will probably never need to use
  80376. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80377. return ((val & 0xFF) << 24)
  80378. | ((val & 0xFF00) << 8)
  80379. | ((val >> 8) & 0xFF00)
  80380. | ((val >> 24) & 0xFF);
  80381. };
  80382. /**
  80383. * It is assumed that the texture has already been created & is currently bound
  80384. */
  80385. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80386. switch (this.loadType) {
  80387. case KhronosTextureContainer.COMPRESSED_2D:
  80388. this._upload2DCompressedLevels(gl, loadMipmaps);
  80389. break;
  80390. case KhronosTextureContainer.TEX_2D:
  80391. case KhronosTextureContainer.COMPRESSED_3D:
  80392. case KhronosTextureContainer.TEX_3D:
  80393. }
  80394. };
  80395. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80396. // initialize width & height for level 1
  80397. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80398. var width = this.pixelWidth;
  80399. var height = this.pixelHeight;
  80400. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80401. for (var level = 0; level < mipmapCount; level++) {
  80402. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80403. for (var face = 0; face < this.numberOfFaces; face++) {
  80404. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80405. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80406. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80407. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80408. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80409. }
  80410. width = Math.max(1.0, width * 0.5);
  80411. height = Math.max(1.0, height * 0.5);
  80412. }
  80413. };
  80414. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80415. // load types
  80416. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80417. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80418. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80419. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80420. return KhronosTextureContainer;
  80421. }());
  80422. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80423. })(BABYLON || (BABYLON = {}));
  80424. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80425. "use strict";
  80426. var BABYLON;
  80427. (function (BABYLON) {
  80428. var Debug = /** @class */ (function () {
  80429. function Debug() {
  80430. }
  80431. Debug.AxesViewer = /** @class */ (function () {
  80432. function AxesViewer(scene, scaleLines) {
  80433. if (scaleLines === void 0) { scaleLines = 1; }
  80434. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80435. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80436. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80437. this.scaleLines = 1;
  80438. this.scaleLines = scaleLines;
  80439. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80440. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80441. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80442. this._xmesh.renderingGroupId = 2;
  80443. this._ymesh.renderingGroupId = 2;
  80444. this._zmesh.renderingGroupId = 2;
  80445. this._xmesh.material.checkReadyOnlyOnce = true;
  80446. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80447. this._ymesh.material.checkReadyOnlyOnce = true;
  80448. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80449. this._zmesh.material.checkReadyOnlyOnce = true;
  80450. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80451. this.scene = scene;
  80452. }
  80453. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80454. var scaleLines = this.scaleLines;
  80455. if (this._xmesh) {
  80456. this._xmesh.position.copyFrom(position);
  80457. }
  80458. if (this._ymesh) {
  80459. this._ymesh.position.copyFrom(position);
  80460. }
  80461. if (this._zmesh) {
  80462. this._zmesh.position.copyFrom(position);
  80463. }
  80464. var point2 = this._xline[1];
  80465. point2.x = xaxis.x * scaleLines;
  80466. point2.y = xaxis.y * scaleLines;
  80467. point2.z = xaxis.z * scaleLines;
  80468. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80469. point2 = this._yline[1];
  80470. point2.x = yaxis.x * scaleLines;
  80471. point2.y = yaxis.y * scaleLines;
  80472. point2.z = yaxis.z * scaleLines;
  80473. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80474. point2 = this._zline[1];
  80475. point2.x = zaxis.x * scaleLines;
  80476. point2.y = zaxis.y * scaleLines;
  80477. point2.z = zaxis.z * scaleLines;
  80478. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80479. };
  80480. AxesViewer.prototype.dispose = function () {
  80481. if (this._xmesh) {
  80482. this._xmesh.dispose();
  80483. }
  80484. if (this._ymesh) {
  80485. this._ymesh.dispose();
  80486. }
  80487. if (this._zmesh) {
  80488. this._zmesh.dispose();
  80489. }
  80490. this._xmesh = null;
  80491. this._ymesh = null;
  80492. this._zmesh = null;
  80493. this.scene = null;
  80494. };
  80495. return AxesViewer;
  80496. }());
  80497. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80498. __extends(BoneAxesViewer, _super);
  80499. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80500. if (scaleLines === void 0) { scaleLines = 1; }
  80501. var _this = _super.call(this, scene, scaleLines) || this;
  80502. _this.pos = BABYLON.Vector3.Zero();
  80503. _this.xaxis = BABYLON.Vector3.Zero();
  80504. _this.yaxis = BABYLON.Vector3.Zero();
  80505. _this.zaxis = BABYLON.Vector3.Zero();
  80506. _this.mesh = mesh;
  80507. _this.bone = bone;
  80508. return _this;
  80509. }
  80510. BoneAxesViewer.prototype.update = function () {
  80511. if (!this.mesh || !this.bone) {
  80512. return;
  80513. }
  80514. var bone = this.bone;
  80515. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80516. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80517. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80518. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80519. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80520. };
  80521. BoneAxesViewer.prototype.dispose = function () {
  80522. if (this.mesh) {
  80523. this.mesh = null;
  80524. this.bone = null;
  80525. _super.prototype.dispose.call(this);
  80526. }
  80527. };
  80528. return BoneAxesViewer;
  80529. }(Debug.AxesViewer));
  80530. Debug.PhysicsViewer = /** @class */ (function () {
  80531. function PhysicsViewer(scene) {
  80532. this._impostors = [];
  80533. this._meshes = [];
  80534. this._numMeshes = 0;
  80535. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80536. var physicEngine = this._scene.getPhysicsEngine();
  80537. if (physicEngine) {
  80538. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80539. }
  80540. }
  80541. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80542. var plugin = this._physicsEnginePlugin;
  80543. for (var i = 0; i < this._numMeshes; i++) {
  80544. var impostor = this._impostors[i];
  80545. if (!impostor) {
  80546. continue;
  80547. }
  80548. if (impostor.isDisposed) {
  80549. this.hideImpostor(this._impostors[i--]);
  80550. }
  80551. else {
  80552. var mesh = this._meshes[i];
  80553. if (mesh && plugin) {
  80554. plugin.syncMeshWithImpostor(mesh, impostor);
  80555. }
  80556. }
  80557. }
  80558. };
  80559. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80560. if (!this._scene) {
  80561. return;
  80562. }
  80563. for (var i = 0; i < this._numMeshes; i++) {
  80564. if (this._impostors[i] == impostor) {
  80565. return;
  80566. }
  80567. }
  80568. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80569. if (debugMesh) {
  80570. this._impostors[this._numMeshes] = impostor;
  80571. this._meshes[this._numMeshes] = debugMesh;
  80572. if (this._numMeshes === 0) {
  80573. this._renderFunction = this._updateDebugMeshes.bind(this);
  80574. this._scene.registerBeforeRender(this._renderFunction);
  80575. }
  80576. this._numMeshes++;
  80577. }
  80578. };
  80579. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80580. if (!impostor || !this._scene) {
  80581. return;
  80582. }
  80583. var removed = false;
  80584. for (var i = 0; i < this._numMeshes; i++) {
  80585. if (this._impostors[i] == impostor) {
  80586. var mesh = this._meshes[i];
  80587. if (!mesh) {
  80588. continue;
  80589. }
  80590. this._scene.removeMesh(mesh);
  80591. mesh.dispose();
  80592. this._numMeshes--;
  80593. if (this._numMeshes > 0) {
  80594. this._meshes[i] = this._meshes[this._numMeshes];
  80595. this._impostors[i] = this._impostors[this._numMeshes];
  80596. this._meshes[this._numMeshes] = null;
  80597. this._impostors[this._numMeshes] = null;
  80598. }
  80599. else {
  80600. this._meshes[0] = null;
  80601. this._impostors[0] = null;
  80602. }
  80603. removed = true;
  80604. break;
  80605. }
  80606. }
  80607. if (removed && this._numMeshes === 0) {
  80608. this._scene.unregisterBeforeRender(this._renderFunction);
  80609. }
  80610. };
  80611. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80612. if (!this._debugMaterial) {
  80613. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80614. this._debugMaterial.wireframe = true;
  80615. }
  80616. return this._debugMaterial;
  80617. };
  80618. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80619. if (!this._debugBoxMesh) {
  80620. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80621. this._debugBoxMesh.renderingGroupId = 1;
  80622. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80623. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80624. scene.removeMesh(this._debugBoxMesh);
  80625. }
  80626. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80627. };
  80628. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80629. if (!this._debugSphereMesh) {
  80630. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80631. this._debugSphereMesh.renderingGroupId = 1;
  80632. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80633. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80634. scene.removeMesh(this._debugSphereMesh);
  80635. }
  80636. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80637. };
  80638. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80639. var mesh = null;
  80640. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80641. mesh = this._getDebugBoxMesh(scene);
  80642. impostor.getBoxSizeToRef(mesh.scaling);
  80643. }
  80644. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80645. mesh = this._getDebugSphereMesh(scene);
  80646. var radius = impostor.getRadius();
  80647. mesh.scaling.x = radius * 2;
  80648. mesh.scaling.y = radius * 2;
  80649. mesh.scaling.z = radius * 2;
  80650. }
  80651. return mesh;
  80652. };
  80653. PhysicsViewer.prototype.dispose = function () {
  80654. for (var i = 0; i < this._numMeshes; i++) {
  80655. this.hideImpostor(this._impostors[i]);
  80656. }
  80657. if (this._debugBoxMesh) {
  80658. this._debugBoxMesh.dispose();
  80659. }
  80660. if (this._debugSphereMesh) {
  80661. this._debugSphereMesh.dispose();
  80662. }
  80663. if (this._debugMaterial) {
  80664. this._debugMaterial.dispose();
  80665. }
  80666. this._impostors.length = 0;
  80667. this._scene = null;
  80668. this._physicsEnginePlugin = null;
  80669. };
  80670. return PhysicsViewer;
  80671. }());
  80672. Debug.SkeletonViewer = /** @class */ (function () {
  80673. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80674. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80675. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80676. this.skeleton = skeleton;
  80677. this.mesh = mesh;
  80678. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80679. this.renderingGroupId = renderingGroupId;
  80680. this.color = BABYLON.Color3.White();
  80681. this._debugLines = new Array();
  80682. this._isEnabled = false;
  80683. this._scene = scene;
  80684. this.update();
  80685. this._renderFunction = this.update.bind(this);
  80686. }
  80687. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80688. get: function () {
  80689. return this._isEnabled;
  80690. },
  80691. set: function (value) {
  80692. if (this._isEnabled === value) {
  80693. return;
  80694. }
  80695. this._isEnabled = value;
  80696. if (value) {
  80697. this._scene.registerBeforeRender(this._renderFunction);
  80698. }
  80699. else {
  80700. this._scene.unregisterBeforeRender(this._renderFunction);
  80701. }
  80702. },
  80703. enumerable: true,
  80704. configurable: true
  80705. });
  80706. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80707. if (x === void 0) { x = 0; }
  80708. if (y === void 0) { y = 0; }
  80709. if (z === void 0) { z = 0; }
  80710. var tmat = BABYLON.Tmp.Matrix[0];
  80711. var parentBone = bone.getParent();
  80712. tmat.copyFrom(bone.getLocalMatrix());
  80713. if (x !== 0 || y !== 0 || z !== 0) {
  80714. var tmat2 = BABYLON.Tmp.Matrix[1];
  80715. BABYLON.Matrix.IdentityToRef(tmat2);
  80716. tmat2.m[12] = x;
  80717. tmat2.m[13] = y;
  80718. tmat2.m[14] = z;
  80719. tmat2.multiplyToRef(tmat, tmat);
  80720. }
  80721. if (parentBone) {
  80722. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80723. }
  80724. tmat.multiplyToRef(meshMat, tmat);
  80725. position.x = tmat.m[12];
  80726. position.y = tmat.m[13];
  80727. position.z = tmat.m[14];
  80728. };
  80729. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80730. var len = bones.length;
  80731. var meshPos = this.mesh.position;
  80732. for (var i = 0; i < len; i++) {
  80733. var bone = bones[i];
  80734. var points = this._debugLines[i];
  80735. if (!points) {
  80736. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80737. this._debugLines[i] = points;
  80738. }
  80739. this._getBonePosition(points[0], bone, meshMat);
  80740. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80741. points[0].subtractInPlace(meshPos);
  80742. points[1].subtractInPlace(meshPos);
  80743. }
  80744. };
  80745. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80746. var len = bones.length;
  80747. var boneNum = 0;
  80748. var meshPos = this.mesh.position;
  80749. for (var i = len - 1; i >= 0; i--) {
  80750. var childBone = bones[i];
  80751. var parentBone = childBone.getParent();
  80752. if (!parentBone) {
  80753. continue;
  80754. }
  80755. var points = this._debugLines[boneNum];
  80756. if (!points) {
  80757. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80758. this._debugLines[boneNum] = points;
  80759. }
  80760. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80761. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80762. points[0].subtractInPlace(meshPos);
  80763. points[1].subtractInPlace(meshPos);
  80764. boneNum++;
  80765. }
  80766. };
  80767. SkeletonViewer.prototype.update = function () {
  80768. if (this.autoUpdateBonesMatrices) {
  80769. this.skeleton.computeAbsoluteTransforms();
  80770. }
  80771. if (this.skeleton.bones[0].length === undefined) {
  80772. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80773. }
  80774. else {
  80775. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80776. }
  80777. if (!this._debugMesh) {
  80778. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80779. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80780. }
  80781. else {
  80782. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80783. }
  80784. this._debugMesh.position.copyFrom(this.mesh.position);
  80785. this._debugMesh.color = this.color;
  80786. };
  80787. SkeletonViewer.prototype.dispose = function () {
  80788. if (this._debugMesh) {
  80789. this.isEnabled = false;
  80790. this._debugMesh.dispose();
  80791. this._debugMesh = null;
  80792. }
  80793. };
  80794. return SkeletonViewer;
  80795. }());
  80796. return Debug;
  80797. }());
  80798. BABYLON.Debug = Debug;
  80799. })(BABYLON || (BABYLON = {}));
  80800. //# sourceMappingURL=babylon.debugModules.js.map
  80801. "use strict";
  80802. var BABYLON;
  80803. (function (BABYLON) {
  80804. var RayHelper = /** @class */ (function () {
  80805. function RayHelper(ray) {
  80806. this.ray = ray;
  80807. }
  80808. RayHelper.CreateAndShow = function (ray, scene, color) {
  80809. var helper = new RayHelper(ray);
  80810. helper.show(scene, color);
  80811. return helper;
  80812. };
  80813. RayHelper.prototype.show = function (scene, color) {
  80814. if (!this._renderFunction && this.ray) {
  80815. var ray = this.ray;
  80816. this._renderFunction = this._render.bind(this);
  80817. this._scene = scene;
  80818. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80819. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80820. if (this._renderFunction) {
  80821. this._scene.registerBeforeRender(this._renderFunction);
  80822. }
  80823. }
  80824. if (color && this._renderLine) {
  80825. this._renderLine.color.copyFrom(color);
  80826. }
  80827. };
  80828. RayHelper.prototype.hide = function () {
  80829. if (this._renderFunction && this._scene) {
  80830. this._scene.unregisterBeforeRender(this._renderFunction);
  80831. this._scene = null;
  80832. this._renderFunction = null;
  80833. if (this._renderLine) {
  80834. this._renderLine.dispose();
  80835. this._renderLine = null;
  80836. }
  80837. this._renderPoints = [];
  80838. }
  80839. };
  80840. RayHelper.prototype._render = function () {
  80841. var ray = this.ray;
  80842. if (!ray) {
  80843. return;
  80844. }
  80845. var point = this._renderPoints[1];
  80846. var len = Math.min(ray.length, 1000000);
  80847. point.copyFrom(ray.direction);
  80848. point.scaleInPlace(len);
  80849. point.addInPlace(ray.origin);
  80850. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  80851. };
  80852. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  80853. this._attachedToMesh = mesh;
  80854. var ray = this.ray;
  80855. if (!ray) {
  80856. return;
  80857. }
  80858. if (!ray.direction) {
  80859. ray.direction = BABYLON.Vector3.Zero();
  80860. }
  80861. if (!ray.origin) {
  80862. ray.origin = BABYLON.Vector3.Zero();
  80863. }
  80864. if (length) {
  80865. ray.length = length;
  80866. }
  80867. if (!meshSpaceOrigin) {
  80868. meshSpaceOrigin = BABYLON.Vector3.Zero();
  80869. }
  80870. if (!meshSpaceDirection) {
  80871. // -1 so that this will work with Mesh.lookAt
  80872. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  80873. }
  80874. if (!this._meshSpaceDirection) {
  80875. this._meshSpaceDirection = meshSpaceDirection.clone();
  80876. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  80877. }
  80878. else {
  80879. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  80880. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  80881. }
  80882. if (!this._updateToMeshFunction) {
  80883. this._updateToMeshFunction = this._updateToMesh.bind(this);
  80884. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  80885. }
  80886. this._updateToMesh();
  80887. };
  80888. RayHelper.prototype.detachFromMesh = function () {
  80889. if (this._attachedToMesh) {
  80890. if (this._updateToMeshFunction) {
  80891. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  80892. }
  80893. this._attachedToMesh = null;
  80894. this._updateToMeshFunction = null;
  80895. }
  80896. };
  80897. RayHelper.prototype._updateToMesh = function () {
  80898. var ray = this.ray;
  80899. if (!this._attachedToMesh || !ray) {
  80900. return;
  80901. }
  80902. if (this._attachedToMesh._isDisposed) {
  80903. this.detachFromMesh();
  80904. return;
  80905. }
  80906. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  80907. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  80908. };
  80909. RayHelper.prototype.dispose = function () {
  80910. this.hide();
  80911. this.detachFromMesh();
  80912. this.ray = null;
  80913. };
  80914. return RayHelper;
  80915. }());
  80916. BABYLON.RayHelper = RayHelper;
  80917. })(BABYLON || (BABYLON = {}));
  80918. //# sourceMappingURL=babylon.rayHelper.js.map
  80919. "use strict";
  80920. var BABYLON;
  80921. (function (BABYLON) {
  80922. // load the inspector using require, if not present in the global namespace.
  80923. var DebugLayer = /** @class */ (function () {
  80924. function DebugLayer(scene) {
  80925. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80926. this._scene = scene;
  80927. // load inspector using require, if it doesn't exist on the global namespace.
  80928. }
  80929. /** Creates the inspector window. */
  80930. DebugLayer.prototype._createInspector = function (config) {
  80931. if (config === void 0) { config = {}; }
  80932. var popup = config.popup || false;
  80933. var initialTab = config.initialTab || 0;
  80934. var parentElement = config.parentElement || null;
  80935. if (!this._inspector) {
  80936. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80937. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  80938. } // else nothing to do,; instance is already existing
  80939. };
  80940. DebugLayer.prototype.isVisible = function () {
  80941. if (!this._inspector) {
  80942. return false;
  80943. }
  80944. return true;
  80945. };
  80946. DebugLayer.prototype.hide = function () {
  80947. if (this._inspector) {
  80948. try {
  80949. this._inspector.dispose();
  80950. }
  80951. catch (e) {
  80952. // If the inspector has been removed directly from the inspector tool
  80953. }
  80954. this._inspector = null;
  80955. }
  80956. };
  80957. DebugLayer.prototype.show = function (config) {
  80958. if (config === void 0) { config = {}; }
  80959. if (typeof this.BJSINSPECTOR == 'undefined') {
  80960. // Load inspector and add it to the DOM
  80961. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  80962. }
  80963. else {
  80964. // Otherwise creates the inspector
  80965. this._createInspector(config);
  80966. }
  80967. };
  80968. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  80969. return DebugLayer;
  80970. }());
  80971. BABYLON.DebugLayer = DebugLayer;
  80972. })(BABYLON || (BABYLON = {}));
  80973. //# sourceMappingURL=babylon.debugLayer.js.map
  80974. "use strict";
  80975. var BABYLON;
  80976. (function (BABYLON) {
  80977. var BoundingBoxRenderer = /** @class */ (function () {
  80978. function BoundingBoxRenderer(scene) {
  80979. this.frontColor = new BABYLON.Color3(1, 1, 1);
  80980. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  80981. this.showBackLines = true;
  80982. this.renderList = new BABYLON.SmartArray(32);
  80983. this._vertexBuffers = {};
  80984. this._scene = scene;
  80985. }
  80986. BoundingBoxRenderer.prototype._prepareRessources = function () {
  80987. if (this._colorShader) {
  80988. return;
  80989. }
  80990. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  80991. attributes: [BABYLON.VertexBuffer.PositionKind],
  80992. uniforms: ["world", "viewProjection", "color"]
  80993. });
  80994. var engine = this._scene.getEngine();
  80995. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  80996. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  80997. this._createIndexBuffer();
  80998. };
  80999. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  81000. var engine = this._scene.getEngine();
  81001. 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]);
  81002. };
  81003. BoundingBoxRenderer.prototype._rebuild = function () {
  81004. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81005. if (vb) {
  81006. vb._rebuild();
  81007. }
  81008. this._createIndexBuffer();
  81009. };
  81010. BoundingBoxRenderer.prototype.reset = function () {
  81011. this.renderList.reset();
  81012. };
  81013. BoundingBoxRenderer.prototype.render = function () {
  81014. if (this.renderList.length === 0) {
  81015. return;
  81016. }
  81017. this._prepareRessources();
  81018. if (!this._colorShader.isReady()) {
  81019. return;
  81020. }
  81021. var engine = this._scene.getEngine();
  81022. engine.setDepthWrite(false);
  81023. this._colorShader._preBind();
  81024. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  81025. var boundingBox = this.renderList.data[boundingBoxIndex];
  81026. var min = boundingBox.minimum;
  81027. var max = boundingBox.maximum;
  81028. var diff = max.subtract(min);
  81029. var median = min.add(diff.scale(0.5));
  81030. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81031. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81032. .multiply(boundingBox.getWorldMatrix());
  81033. // VBOs
  81034. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81035. if (this.showBackLines) {
  81036. // Back
  81037. engine.setDepthFunctionToGreaterOrEqual();
  81038. this._scene.resetCachedMaterial();
  81039. this._colorShader.setColor4("color", this.backColor.toColor4());
  81040. this._colorShader.bind(worldMatrix);
  81041. // Draw order
  81042. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81043. }
  81044. // Front
  81045. engine.setDepthFunctionToLess();
  81046. this._scene.resetCachedMaterial();
  81047. this._colorShader.setColor4("color", this.frontColor.toColor4());
  81048. this._colorShader.bind(worldMatrix);
  81049. // Draw order
  81050. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81051. }
  81052. this._colorShader.unbind();
  81053. engine.setDepthFunctionToLessOrEqual();
  81054. engine.setDepthWrite(true);
  81055. };
  81056. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  81057. this._prepareRessources();
  81058. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  81059. return;
  81060. }
  81061. var engine = this._scene.getEngine();
  81062. engine.setDepthWrite(false);
  81063. engine.setColorWrite(false);
  81064. this._colorShader._preBind();
  81065. var boundingBox = mesh._boundingInfo.boundingBox;
  81066. var min = boundingBox.minimum;
  81067. var max = boundingBox.maximum;
  81068. var diff = max.subtract(min);
  81069. var median = min.add(diff.scale(0.5));
  81070. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81071. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81072. .multiply(boundingBox.getWorldMatrix());
  81073. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81074. engine.setDepthFunctionToLess();
  81075. this._scene.resetCachedMaterial();
  81076. this._colorShader.bind(worldMatrix);
  81077. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81078. this._colorShader.unbind();
  81079. engine.setDepthFunctionToLessOrEqual();
  81080. engine.setDepthWrite(true);
  81081. engine.setColorWrite(true);
  81082. };
  81083. BoundingBoxRenderer.prototype.dispose = function () {
  81084. if (!this._colorShader) {
  81085. return;
  81086. }
  81087. this.renderList.dispose();
  81088. this._colorShader.dispose();
  81089. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81090. if (buffer) {
  81091. buffer.dispose();
  81092. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81093. }
  81094. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81095. };
  81096. return BoundingBoxRenderer;
  81097. }());
  81098. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  81099. })(BABYLON || (BABYLON = {}));
  81100. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  81101. "use strict";
  81102. var BABYLON;
  81103. (function (BABYLON) {
  81104. var MorphTarget = /** @class */ (function () {
  81105. function MorphTarget(name, influence) {
  81106. if (influence === void 0) { influence = 0; }
  81107. this.name = name;
  81108. this.animations = new Array();
  81109. this._positions = null;
  81110. this._normals = null;
  81111. this._tangents = null;
  81112. this.onInfluenceChanged = new BABYLON.Observable();
  81113. this.influence = influence;
  81114. }
  81115. Object.defineProperty(MorphTarget.prototype, "influence", {
  81116. get: function () {
  81117. return this._influence;
  81118. },
  81119. set: function (influence) {
  81120. if (this._influence === influence) {
  81121. return;
  81122. }
  81123. var previous = this._influence;
  81124. this._influence = influence;
  81125. if (this.onInfluenceChanged.hasObservers) {
  81126. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  81127. }
  81128. },
  81129. enumerable: true,
  81130. configurable: true
  81131. });
  81132. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  81133. get: function () {
  81134. return !!this._positions;
  81135. },
  81136. enumerable: true,
  81137. configurable: true
  81138. });
  81139. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  81140. get: function () {
  81141. return !!this._normals;
  81142. },
  81143. enumerable: true,
  81144. configurable: true
  81145. });
  81146. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  81147. get: function () {
  81148. return !!this._tangents;
  81149. },
  81150. enumerable: true,
  81151. configurable: true
  81152. });
  81153. MorphTarget.prototype.setPositions = function (data) {
  81154. this._positions = data;
  81155. };
  81156. MorphTarget.prototype.getPositions = function () {
  81157. return this._positions;
  81158. };
  81159. MorphTarget.prototype.setNormals = function (data) {
  81160. this._normals = data;
  81161. };
  81162. MorphTarget.prototype.getNormals = function () {
  81163. return this._normals;
  81164. };
  81165. MorphTarget.prototype.setTangents = function (data) {
  81166. this._tangents = data;
  81167. };
  81168. MorphTarget.prototype.getTangents = function () {
  81169. return this._tangents;
  81170. };
  81171. /**
  81172. * Serializes the current target into a Serialization object.
  81173. * Returns the serialized object.
  81174. */
  81175. MorphTarget.prototype.serialize = function () {
  81176. var serializationObject = {};
  81177. serializationObject.name = this.name;
  81178. serializationObject.influence = this.influence;
  81179. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  81180. if (this.hasNormals) {
  81181. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  81182. }
  81183. if (this.hasTangents) {
  81184. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  81185. }
  81186. // Animations
  81187. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  81188. return serializationObject;
  81189. };
  81190. // Statics
  81191. MorphTarget.Parse = function (serializationObject) {
  81192. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  81193. result.setPositions(serializationObject.positions);
  81194. if (serializationObject.normals) {
  81195. result.setNormals(serializationObject.normals);
  81196. }
  81197. if (serializationObject.tangents) {
  81198. result.setTangents(serializationObject.tangents);
  81199. }
  81200. // Animations
  81201. if (serializationObject.animations) {
  81202. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  81203. var parsedAnimation = serializationObject.animations[animationIndex];
  81204. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  81205. }
  81206. }
  81207. return result;
  81208. };
  81209. MorphTarget.FromMesh = function (mesh, name, influence) {
  81210. if (!name) {
  81211. name = mesh.name;
  81212. }
  81213. var result = new MorphTarget(name, influence);
  81214. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81215. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  81216. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  81217. }
  81218. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  81219. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  81220. }
  81221. return result;
  81222. };
  81223. return MorphTarget;
  81224. }());
  81225. BABYLON.MorphTarget = MorphTarget;
  81226. })(BABYLON || (BABYLON = {}));
  81227. //# sourceMappingURL=babylon.morphTarget.js.map
  81228. "use strict";
  81229. var BABYLON;
  81230. (function (BABYLON) {
  81231. var MorphTargetManager = /** @class */ (function () {
  81232. function MorphTargetManager(scene) {
  81233. if (scene === void 0) { scene = null; }
  81234. this._targets = new Array();
  81235. this._targetObservable = new Array();
  81236. this._activeTargets = new BABYLON.SmartArray(16);
  81237. this._supportsNormals = false;
  81238. this._supportsTangents = false;
  81239. this._vertexCount = 0;
  81240. this._uniqueId = 0;
  81241. this._tempInfluences = new Array();
  81242. if (!scene) {
  81243. scene = BABYLON.Engine.LastCreatedScene;
  81244. }
  81245. this._scene = scene;
  81246. if (this._scene) {
  81247. this._scene.morphTargetManagers.push(this);
  81248. this._uniqueId = this._scene.getUniqueId();
  81249. }
  81250. }
  81251. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  81252. get: function () {
  81253. return this._uniqueId;
  81254. },
  81255. enumerable: true,
  81256. configurable: true
  81257. });
  81258. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  81259. get: function () {
  81260. return this._vertexCount;
  81261. },
  81262. enumerable: true,
  81263. configurable: true
  81264. });
  81265. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  81266. get: function () {
  81267. return this._supportsNormals;
  81268. },
  81269. enumerable: true,
  81270. configurable: true
  81271. });
  81272. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  81273. get: function () {
  81274. return this._supportsTangents;
  81275. },
  81276. enumerable: true,
  81277. configurable: true
  81278. });
  81279. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  81280. get: function () {
  81281. return this._targets.length;
  81282. },
  81283. enumerable: true,
  81284. configurable: true
  81285. });
  81286. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  81287. get: function () {
  81288. return this._activeTargets.length;
  81289. },
  81290. enumerable: true,
  81291. configurable: true
  81292. });
  81293. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  81294. get: function () {
  81295. return this._influences;
  81296. },
  81297. enumerable: true,
  81298. configurable: true
  81299. });
  81300. MorphTargetManager.prototype.getActiveTarget = function (index) {
  81301. return this._activeTargets.data[index];
  81302. };
  81303. MorphTargetManager.prototype.getTarget = function (index) {
  81304. return this._targets[index];
  81305. };
  81306. MorphTargetManager.prototype.addTarget = function (target) {
  81307. var _this = this;
  81308. this._targets.push(target);
  81309. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  81310. _this._syncActiveTargets(needUpdate);
  81311. }));
  81312. this._syncActiveTargets(true);
  81313. };
  81314. MorphTargetManager.prototype.removeTarget = function (target) {
  81315. var index = this._targets.indexOf(target);
  81316. if (index >= 0) {
  81317. this._targets.splice(index, 1);
  81318. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  81319. this._syncActiveTargets(true);
  81320. }
  81321. };
  81322. /**
  81323. * Serializes the current manager into a Serialization object.
  81324. * Returns the serialized object.
  81325. */
  81326. MorphTargetManager.prototype.serialize = function () {
  81327. var serializationObject = {};
  81328. serializationObject.id = this.uniqueId;
  81329. serializationObject.targets = [];
  81330. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81331. var target = _a[_i];
  81332. serializationObject.targets.push(target.serialize());
  81333. }
  81334. return serializationObject;
  81335. };
  81336. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  81337. var influenceCount = 0;
  81338. this._activeTargets.reset();
  81339. this._supportsNormals = true;
  81340. this._supportsTangents = true;
  81341. this._vertexCount = 0;
  81342. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81343. var target = _a[_i];
  81344. this._activeTargets.push(target);
  81345. this._tempInfluences[influenceCount++] = target.influence;
  81346. var positions = target.getPositions();
  81347. if (positions) {
  81348. this._supportsNormals = this._supportsNormals && target.hasNormals;
  81349. this._supportsTangents = this._supportsTangents && target.hasTangents;
  81350. var vertexCount = positions.length / 3;
  81351. if (this._vertexCount === 0) {
  81352. this._vertexCount = vertexCount;
  81353. }
  81354. else if (this._vertexCount !== vertexCount) {
  81355. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  81356. return;
  81357. }
  81358. }
  81359. }
  81360. if (!this._influences || this._influences.length !== influenceCount) {
  81361. this._influences = new Float32Array(influenceCount);
  81362. }
  81363. for (var index = 0; index < influenceCount; index++) {
  81364. this._influences[index] = this._tempInfluences[index];
  81365. }
  81366. if (needUpdate && this._scene) {
  81367. // Flag meshes as dirty to resync with the active targets
  81368. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  81369. var mesh = _c[_b];
  81370. if (mesh.morphTargetManager === this) {
  81371. mesh._syncGeometryWithMorphTargetManager();
  81372. }
  81373. }
  81374. }
  81375. };
  81376. // Statics
  81377. MorphTargetManager.Parse = function (serializationObject, scene) {
  81378. var result = new MorphTargetManager(scene);
  81379. result._uniqueId = serializationObject.id;
  81380. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81381. var targetData = _a[_i];
  81382. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81383. }
  81384. return result;
  81385. };
  81386. return MorphTargetManager;
  81387. }());
  81388. BABYLON.MorphTargetManager = MorphTargetManager;
  81389. })(BABYLON || (BABYLON = {}));
  81390. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81391. "use strict";
  81392. var BABYLON;
  81393. (function (BABYLON) {
  81394. var Octree = /** @class */ (function () {
  81395. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81396. if (maxDepth === void 0) { maxDepth = 2; }
  81397. this.maxDepth = maxDepth;
  81398. this.dynamicContent = new Array();
  81399. this._maxBlockCapacity = maxBlockCapacity || 64;
  81400. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81401. this._creationFunc = creationFunc;
  81402. }
  81403. // Methods
  81404. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81405. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81406. };
  81407. Octree.prototype.addMesh = function (entry) {
  81408. for (var index = 0; index < this.blocks.length; index++) {
  81409. var block = this.blocks[index];
  81410. block.addEntry(entry);
  81411. }
  81412. };
  81413. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81414. this._selectionContent.reset();
  81415. for (var index = 0; index < this.blocks.length; index++) {
  81416. var block = this.blocks[index];
  81417. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81418. }
  81419. if (allowDuplicate) {
  81420. this._selectionContent.concat(this.dynamicContent);
  81421. }
  81422. else {
  81423. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81424. }
  81425. return this._selectionContent;
  81426. };
  81427. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81428. this._selectionContent.reset();
  81429. for (var index = 0; index < this.blocks.length; index++) {
  81430. var block = this.blocks[index];
  81431. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81432. }
  81433. if (allowDuplicate) {
  81434. this._selectionContent.concat(this.dynamicContent);
  81435. }
  81436. else {
  81437. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81438. }
  81439. return this._selectionContent;
  81440. };
  81441. Octree.prototype.intersectsRay = function (ray) {
  81442. this._selectionContent.reset();
  81443. for (var index = 0; index < this.blocks.length; index++) {
  81444. var block = this.blocks[index];
  81445. block.intersectsRay(ray, this._selectionContent);
  81446. }
  81447. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81448. return this._selectionContent;
  81449. };
  81450. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81451. target.blocks = new Array();
  81452. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81453. // Segmenting space
  81454. for (var x = 0; x < 2; x++) {
  81455. for (var y = 0; y < 2; y++) {
  81456. for (var z = 0; z < 2; z++) {
  81457. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81458. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81459. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81460. block.addEntries(entries);
  81461. target.blocks.push(block);
  81462. }
  81463. }
  81464. }
  81465. };
  81466. Octree.CreationFuncForMeshes = function (entry, block) {
  81467. var boundingInfo = entry.getBoundingInfo();
  81468. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81469. block.entries.push(entry);
  81470. }
  81471. };
  81472. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81473. var boundingInfo = entry.getBoundingInfo();
  81474. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81475. block.entries.push(entry);
  81476. }
  81477. };
  81478. return Octree;
  81479. }());
  81480. BABYLON.Octree = Octree;
  81481. })(BABYLON || (BABYLON = {}));
  81482. //# sourceMappingURL=babylon.octree.js.map
  81483. "use strict";
  81484. var BABYLON;
  81485. (function (BABYLON) {
  81486. var OctreeBlock = /** @class */ (function () {
  81487. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81488. this.entries = new Array();
  81489. this._boundingVectors = new Array();
  81490. this._capacity = capacity;
  81491. this._depth = depth;
  81492. this._maxDepth = maxDepth;
  81493. this._creationFunc = creationFunc;
  81494. this._minPoint = minPoint;
  81495. this._maxPoint = maxPoint;
  81496. this._boundingVectors.push(minPoint.clone());
  81497. this._boundingVectors.push(maxPoint.clone());
  81498. this._boundingVectors.push(minPoint.clone());
  81499. this._boundingVectors[2].x = maxPoint.x;
  81500. this._boundingVectors.push(minPoint.clone());
  81501. this._boundingVectors[3].y = maxPoint.y;
  81502. this._boundingVectors.push(minPoint.clone());
  81503. this._boundingVectors[4].z = maxPoint.z;
  81504. this._boundingVectors.push(maxPoint.clone());
  81505. this._boundingVectors[5].z = minPoint.z;
  81506. this._boundingVectors.push(maxPoint.clone());
  81507. this._boundingVectors[6].x = minPoint.x;
  81508. this._boundingVectors.push(maxPoint.clone());
  81509. this._boundingVectors[7].y = minPoint.y;
  81510. }
  81511. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81512. // Property
  81513. get: function () {
  81514. return this._capacity;
  81515. },
  81516. enumerable: true,
  81517. configurable: true
  81518. });
  81519. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81520. get: function () {
  81521. return this._minPoint;
  81522. },
  81523. enumerable: true,
  81524. configurable: true
  81525. });
  81526. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81527. get: function () {
  81528. return this._maxPoint;
  81529. },
  81530. enumerable: true,
  81531. configurable: true
  81532. });
  81533. // Methods
  81534. OctreeBlock.prototype.addEntry = function (entry) {
  81535. if (this.blocks) {
  81536. for (var index = 0; index < this.blocks.length; index++) {
  81537. var block = this.blocks[index];
  81538. block.addEntry(entry);
  81539. }
  81540. return;
  81541. }
  81542. this._creationFunc(entry, this);
  81543. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81544. this.createInnerBlocks();
  81545. }
  81546. };
  81547. OctreeBlock.prototype.addEntries = function (entries) {
  81548. for (var index = 0; index < entries.length; index++) {
  81549. var mesh = entries[index];
  81550. this.addEntry(mesh);
  81551. }
  81552. };
  81553. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81554. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81555. if (this.blocks) {
  81556. for (var index = 0; index < this.blocks.length; index++) {
  81557. var block = this.blocks[index];
  81558. block.select(frustumPlanes, selection, allowDuplicate);
  81559. }
  81560. return;
  81561. }
  81562. if (allowDuplicate) {
  81563. selection.concat(this.entries);
  81564. }
  81565. else {
  81566. selection.concatWithNoDuplicate(this.entries);
  81567. }
  81568. }
  81569. };
  81570. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81571. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81572. if (this.blocks) {
  81573. for (var index = 0; index < this.blocks.length; index++) {
  81574. var block = this.blocks[index];
  81575. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81576. }
  81577. return;
  81578. }
  81579. if (allowDuplicate) {
  81580. selection.concat(this.entries);
  81581. }
  81582. else {
  81583. selection.concatWithNoDuplicate(this.entries);
  81584. }
  81585. }
  81586. };
  81587. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81588. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81589. if (this.blocks) {
  81590. for (var index = 0; index < this.blocks.length; index++) {
  81591. var block = this.blocks[index];
  81592. block.intersectsRay(ray, selection);
  81593. }
  81594. return;
  81595. }
  81596. selection.concatWithNoDuplicate(this.entries);
  81597. }
  81598. };
  81599. OctreeBlock.prototype.createInnerBlocks = function () {
  81600. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81601. };
  81602. return OctreeBlock;
  81603. }());
  81604. BABYLON.OctreeBlock = OctreeBlock;
  81605. })(BABYLON || (BABYLON = {}));
  81606. //# sourceMappingURL=babylon.octreeBlock.js.map
  81607. "use strict";
  81608. var BABYLON;
  81609. (function (BABYLON) {
  81610. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81611. __extends(VRDistortionCorrectionPostProcess, _super);
  81612. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81613. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81614. 'LensCenter',
  81615. 'Scale',
  81616. 'ScaleIn',
  81617. 'HmdWarpParam'
  81618. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81619. _this._isRightEye = isRightEye;
  81620. _this._distortionFactors = vrMetrics.distortionK;
  81621. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81622. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81623. _this.adaptScaleToCurrentViewport = true;
  81624. _this.onSizeChangedObservable.add(function () {
  81625. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81626. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81627. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81628. });
  81629. _this.onApplyObservable.add(function (effect) {
  81630. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81631. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81632. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81633. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81634. });
  81635. return _this;
  81636. }
  81637. return VRDistortionCorrectionPostProcess;
  81638. }(BABYLON.PostProcess));
  81639. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81640. })(BABYLON || (BABYLON = {}));
  81641. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81642. "use strict";
  81643. var BABYLON;
  81644. (function (BABYLON) {
  81645. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81646. __extends(AnaglyphPostProcess, _super);
  81647. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81648. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81649. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81650. _this.onApplyObservable.add(function (effect) {
  81651. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81652. });
  81653. return _this;
  81654. }
  81655. return AnaglyphPostProcess;
  81656. }(BABYLON.PostProcess));
  81657. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81658. })(BABYLON || (BABYLON = {}));
  81659. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81660. "use strict";
  81661. var BABYLON;
  81662. (function (BABYLON) {
  81663. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81664. __extends(StereoscopicInterlacePostProcess, _super);
  81665. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81666. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81667. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81668. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81669. _this.onSizeChangedObservable.add(function () {
  81670. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81671. });
  81672. _this.onApplyObservable.add(function (effect) {
  81673. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81674. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81675. });
  81676. return _this;
  81677. }
  81678. return StereoscopicInterlacePostProcess;
  81679. }(BABYLON.PostProcess));
  81680. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81681. })(BABYLON || (BABYLON = {}));
  81682. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81683. "use strict";
  81684. var BABYLON;
  81685. (function (BABYLON) {
  81686. /**
  81687. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81688. * Screen rotation is taken into account.
  81689. */
  81690. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81691. function FreeCameraDeviceOrientationInput() {
  81692. var _this = this;
  81693. this._screenOrientationAngle = 0;
  81694. this._screenQuaternion = new BABYLON.Quaternion();
  81695. this._alpha = 0;
  81696. this._beta = 0;
  81697. this._gamma = 0;
  81698. this._orientationChanged = function () {
  81699. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81700. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81701. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81702. };
  81703. this._deviceOrientation = function (evt) {
  81704. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81705. _this._beta = evt.beta !== null ? evt.beta : 0;
  81706. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81707. };
  81708. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81709. this._orientationChanged();
  81710. }
  81711. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81712. get: function () {
  81713. return this._camera;
  81714. },
  81715. set: function (camera) {
  81716. this._camera = camera;
  81717. if (this._camera != null && !this._camera.rotationQuaternion) {
  81718. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81719. }
  81720. },
  81721. enumerable: true,
  81722. configurable: true
  81723. });
  81724. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81725. window.addEventListener("orientationchange", this._orientationChanged);
  81726. window.addEventListener("deviceorientation", this._deviceOrientation);
  81727. //In certain cases, the attach control is called AFTER orientation was changed,
  81728. //So this is needed.
  81729. this._orientationChanged();
  81730. };
  81731. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81732. window.removeEventListener("orientationchange", this._orientationChanged);
  81733. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81734. };
  81735. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81736. //if no device orientation provided, don't update the rotation.
  81737. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81738. if (!this._alpha)
  81739. return;
  81740. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81741. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81742. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81743. //Mirror on XY Plane
  81744. this._camera.rotationQuaternion.z *= -1;
  81745. this._camera.rotationQuaternion.w *= -1;
  81746. };
  81747. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81748. return "FreeCameraDeviceOrientationInput";
  81749. };
  81750. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81751. return "deviceOrientation";
  81752. };
  81753. return FreeCameraDeviceOrientationInput;
  81754. }());
  81755. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81756. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81757. })(BABYLON || (BABYLON = {}));
  81758. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81759. "use strict";
  81760. var BABYLON;
  81761. (function (BABYLON) {
  81762. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81763. function ArcRotateCameraVRDeviceOrientationInput() {
  81764. this.alphaCorrection = 1;
  81765. this.betaCorrection = 1;
  81766. this.gammaCorrection = 1;
  81767. this._alpha = 0;
  81768. this._gamma = 0;
  81769. this._dirty = false;
  81770. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81771. }
  81772. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81773. this.camera.attachControl(element, noPreventDefault);
  81774. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81775. };
  81776. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81777. if (evt.alpha !== null) {
  81778. this._alpha = +evt.alpha | 0;
  81779. }
  81780. if (evt.gamma !== null) {
  81781. this._gamma = +evt.gamma | 0;
  81782. }
  81783. this._dirty = true;
  81784. };
  81785. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81786. if (this._dirty) {
  81787. this._dirty = false;
  81788. if (this._gamma < 0) {
  81789. this._gamma = 180 + this._gamma;
  81790. }
  81791. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81792. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81793. }
  81794. };
  81795. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81796. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81797. };
  81798. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81799. return "ArcRotateCameraVRDeviceOrientationInput";
  81800. };
  81801. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81802. return "VRDeviceOrientation";
  81803. };
  81804. return ArcRotateCameraVRDeviceOrientationInput;
  81805. }());
  81806. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81807. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81808. })(BABYLON || (BABYLON = {}));
  81809. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81810. "use strict";
  81811. var BABYLON;
  81812. (function (BABYLON) {
  81813. var VRCameraMetrics = /** @class */ (function () {
  81814. function VRCameraMetrics() {
  81815. this.compensateDistortion = true;
  81816. }
  81817. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81818. get: function () {
  81819. return this.hResolution / (2 * this.vResolution);
  81820. },
  81821. enumerable: true,
  81822. configurable: true
  81823. });
  81824. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81825. get: function () {
  81826. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81827. },
  81828. enumerable: true,
  81829. configurable: true
  81830. });
  81831. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81832. get: function () {
  81833. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81834. var h = (4 * meters) / this.hScreenSize;
  81835. return BABYLON.Matrix.Translation(h, 0, 0);
  81836. },
  81837. enumerable: true,
  81838. configurable: true
  81839. });
  81840. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  81841. get: function () {
  81842. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81843. var h = (4 * meters) / this.hScreenSize;
  81844. return BABYLON.Matrix.Translation(-h, 0, 0);
  81845. },
  81846. enumerable: true,
  81847. configurable: true
  81848. });
  81849. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  81850. get: function () {
  81851. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  81852. },
  81853. enumerable: true,
  81854. configurable: true
  81855. });
  81856. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  81857. get: function () {
  81858. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  81859. },
  81860. enumerable: true,
  81861. configurable: true
  81862. });
  81863. VRCameraMetrics.GetDefault = function () {
  81864. var result = new VRCameraMetrics();
  81865. result.hResolution = 1280;
  81866. result.vResolution = 800;
  81867. result.hScreenSize = 0.149759993;
  81868. result.vScreenSize = 0.0935999975;
  81869. result.vScreenCenter = 0.0467999987;
  81870. result.eyeToScreenDistance = 0.0410000011;
  81871. result.lensSeparationDistance = 0.0635000020;
  81872. result.interpupillaryDistance = 0.0640000030;
  81873. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  81874. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  81875. result.postProcessScaleFactor = 1.714605507808412;
  81876. result.lensCenterOffset = 0.151976421;
  81877. return result;
  81878. };
  81879. return VRCameraMetrics;
  81880. }());
  81881. BABYLON.VRCameraMetrics = VRCameraMetrics;
  81882. })(BABYLON || (BABYLON = {}));
  81883. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  81884. "use strict";
  81885. var BABYLON;
  81886. (function (BABYLON) {
  81887. /**
  81888. * This represents a WebVR camera.
  81889. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  81890. * @example http://doc.babylonjs.com/how_to/webvr_camera
  81891. */
  81892. var WebVRFreeCamera = /** @class */ (function (_super) {
  81893. __extends(WebVRFreeCamera, _super);
  81894. /**
  81895. * Instantiates a WebVRFreeCamera.
  81896. * @param name The name of the WebVRFreeCamera
  81897. * @param position The starting anchor position for the camera
  81898. * @param scene The scene the camera belongs to
  81899. * @param webVROptions a set of customizable options for the webVRCamera
  81900. */
  81901. function WebVRFreeCamera(name, position, scene, webVROptions) {
  81902. if (webVROptions === void 0) { webVROptions = {}; }
  81903. var _this = _super.call(this, name, position, scene) || this;
  81904. _this.webVROptions = webVROptions;
  81905. /**
  81906. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  81907. */
  81908. _this._vrDevice = null;
  81909. /**
  81910. * The rawPose of the vrDevice.
  81911. */
  81912. _this.rawPose = null;
  81913. _this._specsVersion = "1.1";
  81914. _this._attached = false;
  81915. _this._descendants = [];
  81916. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81917. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81918. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  81919. _this._standingMatrix = null;
  81920. /**
  81921. * Represents device position in babylon space.
  81922. */
  81923. _this.devicePosition = BABYLON.Vector3.Zero();
  81924. /**
  81925. * Represents device rotation in babylon space.
  81926. */
  81927. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  81928. /**
  81929. * The scale of the device to be used when translating from device space to babylon space.
  81930. */
  81931. _this.deviceScaleFactor = 1;
  81932. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81933. _this._worldToDevice = BABYLON.Matrix.Identity();
  81934. /**
  81935. * References to the webVR controllers for the vrDevice.
  81936. */
  81937. _this.controllers = [];
  81938. /**
  81939. * Emits an event when a controller is attached.
  81940. */
  81941. _this.onControllersAttachedObservable = new BABYLON.Observable();
  81942. /**
  81943. * Emits an event when a controller's mesh has been loaded;
  81944. */
  81945. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81946. /**
  81947. * If the rig cameras be used as parent instead of this camera.
  81948. */
  81949. _this.rigParenting = true;
  81950. _this._defaultHeight = undefined;
  81951. _this._workingVector = BABYLON.Vector3.Zero();
  81952. _this._oneVector = BABYLON.Vector3.One();
  81953. _this._workingMatrix = BABYLON.Matrix.Identity();
  81954. _this._cache.position = BABYLON.Vector3.Zero();
  81955. if (webVROptions.defaultHeight) {
  81956. _this._defaultHeight = webVROptions.defaultHeight;
  81957. _this.position.y = _this._defaultHeight;
  81958. }
  81959. _this.minZ = 0.1;
  81960. //legacy support - the compensation boolean was removed.
  81961. if (arguments.length === 5) {
  81962. _this.webVROptions = arguments[4];
  81963. }
  81964. // default webVR options
  81965. if (_this.webVROptions.trackPosition == undefined) {
  81966. _this.webVROptions.trackPosition = true;
  81967. }
  81968. if (_this.webVROptions.controllerMeshes == undefined) {
  81969. _this.webVROptions.controllerMeshes = true;
  81970. }
  81971. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  81972. _this.webVROptions.defaultLightingOnControllers = true;
  81973. }
  81974. _this.rotationQuaternion = new BABYLON.Quaternion();
  81975. if (_this.webVROptions && _this.webVROptions.positionScale) {
  81976. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  81977. }
  81978. //enable VR
  81979. var engine = _this.getEngine();
  81980. _this._onVREnabled = function (success) { if (success) {
  81981. _this.initControllers();
  81982. } };
  81983. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  81984. engine.initWebVR().add(function (event) {
  81985. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  81986. return;
  81987. }
  81988. _this._vrDevice = event.vrDisplay;
  81989. //reset the rig parameters.
  81990. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  81991. if (_this._attached) {
  81992. _this.getEngine().enableVR();
  81993. }
  81994. });
  81995. if (typeof (VRFrameData) !== "undefined")
  81996. _this._frameData = new VRFrameData();
  81997. /**
  81998. * The idea behind the following lines:
  81999. * objects that have the camera as parent should actually have the rig cameras as a parent.
  82000. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  82001. * the second will not show it correctly.
  82002. *
  82003. * To solve this - each object that has the camera as parent will be added to a protected array.
  82004. * When the rig camera renders, it will take this array and set all of those to be its children.
  82005. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  82006. * Amazing!
  82007. */
  82008. scene.onBeforeCameraRenderObservable.add(function (camera) {
  82009. if (camera.parent === _this && _this.rigParenting) {
  82010. _this._descendants = _this.getDescendants(true, function (n) {
  82011. // don't take the cameras or the controllers!
  82012. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  82013. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  82014. return !isController && !isRigCamera;
  82015. });
  82016. _this._descendants.forEach(function (node) {
  82017. node.parent = camera;
  82018. });
  82019. }
  82020. });
  82021. scene.onAfterCameraRenderObservable.add(function (camera) {
  82022. if (camera.parent === _this && _this.rigParenting) {
  82023. _this._descendants.forEach(function (node) {
  82024. node.parent = _this;
  82025. });
  82026. }
  82027. });
  82028. return _this;
  82029. }
  82030. /**
  82031. * Gets the device distance from the ground in meters.
  82032. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  82033. */
  82034. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  82035. if (this._standingMatrix) {
  82036. // Add standing matrix offset to get real offset from ground in room
  82037. this._standingMatrix.getTranslationToRef(this._workingVector);
  82038. return this._deviceRoomPosition.y + this._workingVector.y;
  82039. }
  82040. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  82041. return this._defaultHeight || 0;
  82042. };
  82043. /**
  82044. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82045. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  82046. */
  82047. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  82048. var _this = this;
  82049. if (callback === void 0) { callback = function (bool) { }; }
  82050. // Use standing matrix if available
  82051. this.getEngine().initWebVRAsync().then(function (result) {
  82052. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  82053. callback(false);
  82054. }
  82055. else {
  82056. _this._standingMatrix = new BABYLON.Matrix();
  82057. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  82058. if (!_this.getScene().useRightHandedSystem) {
  82059. [2, 6, 8, 9, 14].forEach(function (num) {
  82060. if (_this._standingMatrix) {
  82061. _this._standingMatrix.m[num] *= -1;
  82062. }
  82063. });
  82064. }
  82065. callback(true);
  82066. }
  82067. });
  82068. };
  82069. /**
  82070. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82071. * @returns A promise with a boolean set to if the standing matrix is supported.
  82072. */
  82073. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  82074. var _this = this;
  82075. return new Promise(function (res, rej) {
  82076. _this.useStandingMatrix(function (supported) {
  82077. res(supported);
  82078. });
  82079. });
  82080. };
  82081. /**
  82082. * Disposes the camera
  82083. */
  82084. WebVRFreeCamera.prototype.dispose = function () {
  82085. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  82086. _super.prototype.dispose.call(this);
  82087. };
  82088. /**
  82089. * Gets a vrController by name.
  82090. * @param name The name of the controller to retreive
  82091. * @returns the controller matching the name specified or null if not found
  82092. */
  82093. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  82094. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  82095. var gp = _a[_i];
  82096. if (gp.hand === name) {
  82097. return gp;
  82098. }
  82099. }
  82100. return null;
  82101. };
  82102. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  82103. /**
  82104. * The controller corrisponding to the users left hand.
  82105. */
  82106. get: function () {
  82107. if (!this._leftController) {
  82108. this._leftController = this.getControllerByName("left");
  82109. }
  82110. return this._leftController;
  82111. },
  82112. enumerable: true,
  82113. configurable: true
  82114. });
  82115. ;
  82116. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  82117. /**
  82118. * The controller corrisponding to the users right hand.
  82119. */
  82120. get: function () {
  82121. if (!this._rightController) {
  82122. this._rightController = this.getControllerByName("right");
  82123. }
  82124. return this._rightController;
  82125. },
  82126. enumerable: true,
  82127. configurable: true
  82128. });
  82129. ;
  82130. /**
  82131. * Casts a ray forward from the vrCamera's gaze.
  82132. * @param length Length of the ray (default: 100)
  82133. * @returns the ray corrisponding to the gaze
  82134. */
  82135. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  82136. if (length === void 0) { length = 100; }
  82137. if (this.leftCamera) {
  82138. // Use left eye to avoid computation to compute center on every call
  82139. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  82140. }
  82141. else {
  82142. return _super.prototype.getForwardRay.call(this, length);
  82143. }
  82144. };
  82145. /**
  82146. * Updates the camera based on device's frame data
  82147. */
  82148. WebVRFreeCamera.prototype._checkInputs = function () {
  82149. if (this._vrDevice && this._vrDevice.isPresenting) {
  82150. this._vrDevice.getFrameData(this._frameData);
  82151. this.updateFromDevice(this._frameData.pose);
  82152. }
  82153. _super.prototype._checkInputs.call(this);
  82154. };
  82155. /**
  82156. * Updates the poseControlled values based on the input device pose.
  82157. * @param poseData Pose coming from the device
  82158. */
  82159. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  82160. if (poseData && poseData.orientation) {
  82161. this.rawPose = poseData;
  82162. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  82163. if (this.getScene().useRightHandedSystem) {
  82164. this._deviceRoomRotationQuaternion.z *= -1;
  82165. this._deviceRoomRotationQuaternion.w *= -1;
  82166. }
  82167. if (this.webVROptions.trackPosition && this.rawPose.position) {
  82168. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  82169. if (this.getScene().useRightHandedSystem) {
  82170. this._deviceRoomPosition.z *= -1;
  82171. }
  82172. }
  82173. }
  82174. };
  82175. /**
  82176. * WebVR's attach control will start broadcasting frames to the device.
  82177. * Note that in certain browsers (chrome for example) this function must be called
  82178. * within a user-interaction callback. Example:
  82179. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  82180. *
  82181. * @param element html element to attach the vrDevice to
  82182. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  82183. */
  82184. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  82185. _super.prototype.attachControl.call(this, element, noPreventDefault);
  82186. this._attached = true;
  82187. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  82188. if (this._vrDevice) {
  82189. this.getEngine().enableVR();
  82190. }
  82191. };
  82192. /**
  82193. * Detaches the camera from the html element and disables VR
  82194. *
  82195. * @param element html element to detach from
  82196. */
  82197. WebVRFreeCamera.prototype.detachControl = function (element) {
  82198. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  82199. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  82200. _super.prototype.detachControl.call(this, element);
  82201. this._attached = false;
  82202. this.getEngine().disableVR();
  82203. };
  82204. /**
  82205. * @returns the name of this class
  82206. */
  82207. WebVRFreeCamera.prototype.getClassName = function () {
  82208. return "WebVRFreeCamera";
  82209. };
  82210. /**
  82211. * Calls resetPose on the vrDisplay
  82212. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  82213. */
  82214. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  82215. //uses the vrDisplay's "resetPose()".
  82216. //pitch and roll won't be affected.
  82217. this._vrDevice.resetPose();
  82218. };
  82219. /**
  82220. * Updates the rig cameras (left and right eye)
  82221. */
  82222. WebVRFreeCamera.prototype._updateRigCameras = function () {
  82223. var camLeft = this._rigCameras[0];
  82224. var camRight = this._rigCameras[1];
  82225. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82226. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82227. camLeft.position.copyFrom(this._deviceRoomPosition);
  82228. camRight.position.copyFrom(this._deviceRoomPosition);
  82229. };
  82230. /**
  82231. * Updates the cached values of the camera
  82232. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  82233. */
  82234. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  82235. var _this = this;
  82236. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  82237. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  82238. if (!this.updateCacheCalled) {
  82239. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  82240. this.updateCacheCalled = true;
  82241. this.update();
  82242. }
  82243. // Set working vector to the device position in room space rotated by the new rotation
  82244. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  82245. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  82246. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  82247. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  82248. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  82249. // Add translation from anchor position
  82250. this._deviceToWorld.getTranslationToRef(this._workingVector);
  82251. this._workingVector.addInPlace(this.position);
  82252. this._workingVector.subtractInPlace(this._cache.position);
  82253. this._deviceToWorld.setTranslation(this._workingVector);
  82254. // Set an inverted matrix to be used when updating the camera
  82255. this._deviceToWorld.invertToRef(this._worldToDevice);
  82256. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  82257. this.controllers.forEach(function (controller) {
  82258. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  82259. controller.update();
  82260. });
  82261. }
  82262. if (!ignoreParentClass) {
  82263. _super.prototype._updateCache.call(this);
  82264. }
  82265. this.updateCacheCalled = false;
  82266. };
  82267. /**
  82268. * Updates the current device position and rotation in the babylon world
  82269. */
  82270. WebVRFreeCamera.prototype.update = function () {
  82271. // Get current device position in babylon world
  82272. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  82273. // Get current device rotation in babylon world
  82274. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  82275. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  82276. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82277. _super.prototype.update.call(this);
  82278. };
  82279. /**
  82280. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  82281. * @returns an identity matrix
  82282. */
  82283. WebVRFreeCamera.prototype._getViewMatrix = function () {
  82284. return BABYLON.Matrix.Identity();
  82285. };
  82286. /**
  82287. * This function is called by the two RIG cameras.
  82288. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  82289. */
  82290. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  82291. var _this = this;
  82292. // Update the parent camera prior to using a child camera to avoid desynchronization
  82293. var parentCamera = this._cameraRigParams["parentCamera"];
  82294. parentCamera._updateCache();
  82295. //WebVR 1.1
  82296. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  82297. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  82298. if (!this.getScene().useRightHandedSystem) {
  82299. [2, 6, 8, 9, 14].forEach(function (num) {
  82300. _this._webvrViewMatrix.m[num] *= -1;
  82301. });
  82302. }
  82303. // update the camera rotation matrix
  82304. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  82305. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  82306. // Computing target and final matrix
  82307. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  82308. // should the view matrix be updated with scale and position offset?
  82309. if (parentCamera.deviceScaleFactor !== 1) {
  82310. this._webvrViewMatrix.invert();
  82311. // scale the position, if set
  82312. if (parentCamera.deviceScaleFactor) {
  82313. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  82314. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  82315. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  82316. }
  82317. this._webvrViewMatrix.invert();
  82318. }
  82319. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  82320. return this._webvrViewMatrix;
  82321. };
  82322. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  82323. var _this = this;
  82324. var parentCamera = this.parent;
  82325. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  82326. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  82327. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  82328. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  82329. //babylon compatible matrix
  82330. if (!this.getScene().useRightHandedSystem) {
  82331. [8, 9, 10, 11].forEach(function (num) {
  82332. _this._projectionMatrix.m[num] *= -1;
  82333. });
  82334. }
  82335. return this._projectionMatrix;
  82336. };
  82337. /**
  82338. * Initializes the controllers and their meshes
  82339. */
  82340. WebVRFreeCamera.prototype.initControllers = function () {
  82341. var _this = this;
  82342. this.controllers = [];
  82343. var manager = this.getScene().gamepadManager;
  82344. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82345. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82346. var webVrController = gamepad;
  82347. if (webVrController.defaultModel) {
  82348. webVrController.defaultModel.setEnabled(false);
  82349. }
  82350. if (webVrController.hand === "right") {
  82351. _this._rightController = null;
  82352. }
  82353. if (webVrController.hand === "left") {
  82354. _this._leftController = null;
  82355. }
  82356. var controllerIndex = _this.controllers.indexOf(webVrController);
  82357. if (controllerIndex !== -1) {
  82358. _this.controllers.splice(controllerIndex, 1);
  82359. }
  82360. }
  82361. });
  82362. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82363. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82364. var webVrController_1 = gamepad;
  82365. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  82366. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  82367. if (_this.webVROptions.controllerMeshes) {
  82368. if (webVrController_1.defaultModel) {
  82369. webVrController_1.defaultModel.setEnabled(true);
  82370. }
  82371. else {
  82372. // Load the meshes
  82373. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82374. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82375. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82376. if (_this.webVROptions.defaultLightingOnControllers) {
  82377. if (!_this._lightOnControllers) {
  82378. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82379. }
  82380. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82381. var children = mesh.getChildren();
  82382. if (children.length !== 0) {
  82383. children.forEach(function (mesh) {
  82384. light.includedOnlyMeshes.push(mesh);
  82385. activateLightOnSubMeshes_1(mesh, light);
  82386. });
  82387. }
  82388. };
  82389. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82390. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82391. }
  82392. });
  82393. }
  82394. }
  82395. webVrController_1.attachToPoseControlledCamera(_this);
  82396. // since this is async - sanity check. Is the controller already stored?
  82397. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82398. //add to the controllers array
  82399. _this.controllers.push(webVrController_1);
  82400. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82401. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82402. // So we're overriding setting left & right manually to be sure
  82403. var firstViveWandDetected = false;
  82404. for (var i = 0; i < _this.controllers.length; i++) {
  82405. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82406. if (!firstViveWandDetected) {
  82407. firstViveWandDetected = true;
  82408. _this.controllers[i].hand = "left";
  82409. }
  82410. else {
  82411. _this.controllers[i].hand = "right";
  82412. }
  82413. }
  82414. }
  82415. //did we find enough controllers? Great! let the developer know.
  82416. if (_this.controllers.length >= 2) {
  82417. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82418. }
  82419. }
  82420. }
  82421. });
  82422. };
  82423. return WebVRFreeCamera;
  82424. }(BABYLON.FreeCamera));
  82425. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82426. })(BABYLON || (BABYLON = {}));
  82427. //# sourceMappingURL=babylon.webVRCamera.js.map
  82428. "use strict";
  82429. var BABYLON;
  82430. (function (BABYLON) {
  82431. // We're mainly based on the logic defined into the FreeCamera code
  82432. /**
  82433. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82434. * being tilted forward or back and left or right.
  82435. */
  82436. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82437. __extends(DeviceOrientationCamera, _super);
  82438. /**
  82439. * Creates a new device orientation camera. @see DeviceOrientationCamera
  82440. * @param name The name of the camera
  82441. * @param position The start position camera
  82442. * @param scene The scene the camera belongs to
  82443. */
  82444. function DeviceOrientationCamera(name, position, scene) {
  82445. var _this = _super.call(this, name, position, scene) || this;
  82446. _this._quaternionCache = new BABYLON.Quaternion();
  82447. _this.inputs.addDeviceOrientation();
  82448. return _this;
  82449. }
  82450. /**
  82451. * Gets the current instance class name ("DeviceOrientationCamera").
  82452. * This helps avoiding instanceof at run time.
  82453. * @returns the class name
  82454. */
  82455. DeviceOrientationCamera.prototype.getClassName = function () {
  82456. return "DeviceOrientationCamera";
  82457. };
  82458. /**
  82459. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82460. */
  82461. DeviceOrientationCamera.prototype._checkInputs = function () {
  82462. _super.prototype._checkInputs.call(this);
  82463. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82464. if (this._initialQuaternion) {
  82465. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82466. }
  82467. };
  82468. /**
  82469. * Reset the camera to its default orientation on the specified axis only.
  82470. * @param axis The axis to reset
  82471. */
  82472. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82473. var _this = this;
  82474. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82475. //can only work if this camera has a rotation quaternion already.
  82476. if (!this.rotationQuaternion)
  82477. return;
  82478. if (!this._initialQuaternion) {
  82479. this._initialQuaternion = new BABYLON.Quaternion();
  82480. }
  82481. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82482. ['x', 'y', 'z'].forEach(function (axisName) {
  82483. if (!axis[axisName]) {
  82484. _this._initialQuaternion[axisName] = 0;
  82485. }
  82486. else {
  82487. _this._initialQuaternion[axisName] *= -1;
  82488. }
  82489. });
  82490. this._initialQuaternion.normalize();
  82491. //force rotation update
  82492. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82493. };
  82494. return DeviceOrientationCamera;
  82495. }(BABYLON.FreeCamera));
  82496. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82497. })(BABYLON || (BABYLON = {}));
  82498. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82499. "use strict";
  82500. var BABYLON;
  82501. (function (BABYLON) {
  82502. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82503. __extends(VRDeviceOrientationFreeCamera, _super);
  82504. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82505. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82506. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82507. var _this = _super.call(this, name, position, scene) || this;
  82508. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82509. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82510. return _this;
  82511. }
  82512. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82513. return "VRDeviceOrientationFreeCamera";
  82514. };
  82515. return VRDeviceOrientationFreeCamera;
  82516. }(BABYLON.DeviceOrientationCamera));
  82517. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82518. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82519. __extends(VRDeviceOrientationGamepadCamera, _super);
  82520. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82521. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82522. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82523. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82524. _this.inputs.addGamepad();
  82525. return _this;
  82526. }
  82527. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82528. return "VRDeviceOrientationGamepadCamera";
  82529. };
  82530. return VRDeviceOrientationGamepadCamera;
  82531. }(VRDeviceOrientationFreeCamera));
  82532. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82533. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82534. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82535. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82536. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82537. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82538. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82539. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82540. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82541. _this.inputs.addVRDeviceOrientation();
  82542. return _this;
  82543. }
  82544. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82545. return "VRDeviceOrientationArcRotateCamera";
  82546. };
  82547. return VRDeviceOrientationArcRotateCamera;
  82548. }(BABYLON.ArcRotateCamera));
  82549. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82550. })(BABYLON || (BABYLON = {}));
  82551. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82552. "use strict";
  82553. var BABYLON;
  82554. (function (BABYLON) {
  82555. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82556. __extends(AnaglyphFreeCamera, _super);
  82557. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82558. var _this = _super.call(this, name, position, scene) || this;
  82559. _this.interaxialDistance = interaxialDistance;
  82560. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82561. return _this;
  82562. }
  82563. AnaglyphFreeCamera.prototype.getClassName = function () {
  82564. return "AnaglyphFreeCamera";
  82565. };
  82566. return AnaglyphFreeCamera;
  82567. }(BABYLON.FreeCamera));
  82568. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82569. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82570. __extends(AnaglyphArcRotateCamera, _super);
  82571. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82572. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82573. _this.interaxialDistance = interaxialDistance;
  82574. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82575. return _this;
  82576. }
  82577. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82578. return "AnaglyphArcRotateCamera";
  82579. };
  82580. return AnaglyphArcRotateCamera;
  82581. }(BABYLON.ArcRotateCamera));
  82582. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82583. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82584. __extends(AnaglyphGamepadCamera, _super);
  82585. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82586. var _this = _super.call(this, name, position, scene) || this;
  82587. _this.interaxialDistance = interaxialDistance;
  82588. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82589. return _this;
  82590. }
  82591. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82592. return "AnaglyphGamepadCamera";
  82593. };
  82594. return AnaglyphGamepadCamera;
  82595. }(BABYLON.GamepadCamera));
  82596. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82597. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82598. __extends(AnaglyphUniversalCamera, _super);
  82599. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82600. var _this = _super.call(this, name, position, scene) || this;
  82601. _this.interaxialDistance = interaxialDistance;
  82602. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82603. return _this;
  82604. }
  82605. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82606. return "AnaglyphUniversalCamera";
  82607. };
  82608. return AnaglyphUniversalCamera;
  82609. }(BABYLON.UniversalCamera));
  82610. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82611. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82612. __extends(StereoscopicFreeCamera, _super);
  82613. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82614. var _this = _super.call(this, name, position, scene) || this;
  82615. _this.interaxialDistance = interaxialDistance;
  82616. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82617. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82618. return _this;
  82619. }
  82620. StereoscopicFreeCamera.prototype.getClassName = function () {
  82621. return "StereoscopicFreeCamera";
  82622. };
  82623. return StereoscopicFreeCamera;
  82624. }(BABYLON.FreeCamera));
  82625. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82626. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82627. __extends(StereoscopicArcRotateCamera, _super);
  82628. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82629. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82630. _this.interaxialDistance = interaxialDistance;
  82631. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82632. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82633. return _this;
  82634. }
  82635. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82636. return "StereoscopicArcRotateCamera";
  82637. };
  82638. return StereoscopicArcRotateCamera;
  82639. }(BABYLON.ArcRotateCamera));
  82640. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82641. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82642. __extends(StereoscopicGamepadCamera, _super);
  82643. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82644. var _this = _super.call(this, name, position, scene) || this;
  82645. _this.interaxialDistance = interaxialDistance;
  82646. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82647. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82648. return _this;
  82649. }
  82650. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82651. return "StereoscopicGamepadCamera";
  82652. };
  82653. return StereoscopicGamepadCamera;
  82654. }(BABYLON.GamepadCamera));
  82655. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82656. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82657. __extends(StereoscopicUniversalCamera, _super);
  82658. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82659. var _this = _super.call(this, name, position, scene) || this;
  82660. _this.interaxialDistance = interaxialDistance;
  82661. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82662. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82663. return _this;
  82664. }
  82665. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82666. return "StereoscopicUniversalCamera";
  82667. };
  82668. return StereoscopicUniversalCamera;
  82669. }(BABYLON.UniversalCamera));
  82670. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82671. })(BABYLON || (BABYLON = {}));
  82672. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82673. "use strict";
  82674. var BABYLON;
  82675. (function (BABYLON) {
  82676. var VRExperienceHelperGazer = /** @class */ (function () {
  82677. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82678. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82679. this.scene = scene;
  82680. this._pointerDownOnMeshAsked = false;
  82681. this._isActionableMesh = false;
  82682. this._teleportationRequestInitiated = false;
  82683. this._teleportationBackRequestInitiated = false;
  82684. this._dpadPressed = true;
  82685. this._activePointer = false;
  82686. this._id = VRExperienceHelperGazer._idCounter++;
  82687. // Gaze tracker
  82688. if (!gazeTrackerToClone) {
  82689. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82690. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82691. this._gazeTracker.isPickable = false;
  82692. this._gazeTracker.isVisible = false;
  82693. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82694. targetMat.specularColor = BABYLON.Color3.Black();
  82695. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82696. targetMat.backFaceCulling = false;
  82697. this._gazeTracker.material = targetMat;
  82698. }
  82699. else {
  82700. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82701. }
  82702. }
  82703. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82704. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82705. };
  82706. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82707. this._pointerDownOnMeshAsked = true;
  82708. if (this._currentMeshSelected && this._currentHit) {
  82709. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82710. }
  82711. };
  82712. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82713. if (this._currentMeshSelected && this._currentHit) {
  82714. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82715. }
  82716. this._pointerDownOnMeshAsked = false;
  82717. };
  82718. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82719. this._activePointer = true;
  82720. };
  82721. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82722. this._activePointer = false;
  82723. };
  82724. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82725. };
  82726. VRExperienceHelperGazer.prototype.dispose = function () {
  82727. this._interactionsEnabled = false;
  82728. this._teleportationEnabled = false;
  82729. };
  82730. VRExperienceHelperGazer._idCounter = 0;
  82731. return VRExperienceHelperGazer;
  82732. }());
  82733. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82734. __extends(VRExperienceHelperControllerGazer, _super);
  82735. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82736. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82737. _this.webVRController = webVRController;
  82738. // Laser pointer
  82739. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82740. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82741. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82742. laserPointerMaterial.alpha = 0.6;
  82743. _this._laserPointer.material = laserPointerMaterial;
  82744. _this._laserPointer.rotation.x = Math.PI / 2;
  82745. _this._laserPointer.position.z = -0.5;
  82746. _this._laserPointer.isVisible = false;
  82747. if (!webVRController.mesh) {
  82748. // Create an empty mesh that is used prior to loading the high quality model
  82749. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82750. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82751. preloadPointerPose.rotation.x = -0.7;
  82752. preloadMesh.addChild(preloadPointerPose);
  82753. webVRController.attachToMesh(preloadMesh);
  82754. }
  82755. _this._setLaserPointerParent(webVRController.mesh);
  82756. return _this;
  82757. }
  82758. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82759. return this.webVRController.getForwardRay(length);
  82760. };
  82761. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82762. _super.prototype._activatePointer.call(this);
  82763. this._laserPointer.isVisible = true;
  82764. };
  82765. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82766. _super.prototype._deactivatePointer.call(this);
  82767. this._laserPointer.isVisible = false;
  82768. };
  82769. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82770. this._laserPointer.material.emissiveColor = color;
  82771. };
  82772. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82773. var makeNotPick = function (root) {
  82774. root.name += " laserPointer";
  82775. root.getChildMeshes().forEach(function (c) {
  82776. makeNotPick(c);
  82777. });
  82778. };
  82779. makeNotPick(mesh);
  82780. var childMeshes = mesh.getChildMeshes();
  82781. this.webVRController._pointingPoseNode = null;
  82782. for (var i = 0; i < childMeshes.length; i++) {
  82783. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82784. mesh = childMeshes[i];
  82785. this.webVRController._pointingPoseNode = mesh;
  82786. break;
  82787. }
  82788. }
  82789. this._laserPointer.parent = mesh;
  82790. };
  82791. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82792. this._laserPointer.scaling.y = distance;
  82793. this._laserPointer.position.z = -distance / 2;
  82794. };
  82795. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82796. _super.prototype.dispose.call(this);
  82797. this._laserPointer.dispose();
  82798. };
  82799. return VRExperienceHelperControllerGazer;
  82800. }(VRExperienceHelperGazer));
  82801. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82802. __extends(VRExperienceHelperCameraGazer, _super);
  82803. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82804. var _this = _super.call(this, scene) || this;
  82805. _this.getCamera = getCamera;
  82806. return _this;
  82807. }
  82808. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82809. var camera = this.getCamera();
  82810. if (camera) {
  82811. return camera.getForwardRay(length);
  82812. }
  82813. else {
  82814. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82815. }
  82816. };
  82817. return VRExperienceHelperCameraGazer;
  82818. }(VRExperienceHelperGazer));
  82819. /**
  82820. * Helps to quickly add VR support to an existing scene.
  82821. * See http://doc.babylonjs.com/how_to/webvr_helper
  82822. */
  82823. var VRExperienceHelper = /** @class */ (function () {
  82824. /**
  82825. * Instantiates a VRExperienceHelper.
  82826. * Helps to quickly add VR support to an existing scene.
  82827. * @param scene The scene the VRExperienceHelper belongs to.
  82828. * @param webVROptions Options to modify the vr experience helper's behavior.
  82829. */
  82830. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82831. if (webVROptions === void 0) { webVROptions = {}; }
  82832. var _this = this;
  82833. this.webVROptions = webVROptions;
  82834. // Can the system support WebVR, even if a headset isn't plugged in?
  82835. this._webVRsupported = false;
  82836. // If WebVR is supported, is a headset plugged in and are we ready to present?
  82837. this._webVRready = false;
  82838. // Are we waiting for the requestPresent callback to complete?
  82839. this._webVRrequesting = false;
  82840. // Are we presenting to the headset right now?
  82841. this._webVRpresenting = false;
  82842. // Are we presenting in the fullscreen fallback?
  82843. this._fullscreenVRpresenting = false;
  82844. /**
  82845. * Observable raised when entering VR.
  82846. */
  82847. this.onEnteringVRObservable = new BABYLON.Observable();
  82848. /**
  82849. * Observable raised when exiting VR.
  82850. */
  82851. this.onExitingVRObservable = new BABYLON.Observable();
  82852. /**
  82853. * Observable raised when controller mesh is loaded.
  82854. */
  82855. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82856. this._useCustomVRButton = false;
  82857. this._teleportationRequested = false;
  82858. this._teleportActive = false;
  82859. this._floorMeshesCollection = [];
  82860. this._rotationAllowed = true;
  82861. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  82862. this._rotationRightAsked = false;
  82863. this._rotationLeftAsked = false;
  82864. this._isDefaultTeleportationTarget = true;
  82865. this._teleportationFillColor = "#444444";
  82866. this._teleportationBorderColor = "#FFFFFF";
  82867. this._rotationAngle = 0;
  82868. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  82869. this._padSensibilityUp = 0.65;
  82870. this._padSensibilityDown = 0.35;
  82871. this.leftController = null;
  82872. this.rightController = null;
  82873. /**
  82874. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  82875. */
  82876. this.onNewMeshSelected = new BABYLON.Observable();
  82877. /**
  82878. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  82879. */
  82880. this.onNewMeshPicked = new BABYLON.Observable();
  82881. /**
  82882. * Observable raised before camera teleportation
  82883. */
  82884. this.onBeforeCameraTeleport = new BABYLON.Observable();
  82885. /**
  82886. * Observable raised after camera teleportation
  82887. */
  82888. this.onAfterCameraTeleport = new BABYLON.Observable();
  82889. /**
  82890. * Observable raised when current selected mesh gets unselected
  82891. */
  82892. this.onSelectedMeshUnselected = new BABYLON.Observable();
  82893. /**
  82894. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  82895. */
  82896. this.teleportationEnabled = true;
  82897. this._teleportationInitialized = false;
  82898. this._interactionsEnabled = false;
  82899. this._interactionsRequested = false;
  82900. this._displayGaze = true;
  82901. this._displayLaserPointer = true;
  82902. this._onResize = function () {
  82903. _this.moveButtonToBottomRight();
  82904. if (_this._fullscreenVRpresenting && _this._webVRready) {
  82905. _this.exitVR();
  82906. }
  82907. };
  82908. this._onFullscreenChange = function () {
  82909. if (document.fullscreen !== undefined) {
  82910. _this._fullscreenVRpresenting = document.fullscreen;
  82911. }
  82912. else if (document.mozFullScreen !== undefined) {
  82913. _this._fullscreenVRpresenting = document.mozFullScreen;
  82914. }
  82915. else if (document.webkitIsFullScreen !== undefined) {
  82916. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  82917. }
  82918. else if (document.msIsFullScreen !== undefined) {
  82919. _this._fullscreenVRpresenting = document.msIsFullScreen;
  82920. }
  82921. if (!_this._fullscreenVRpresenting && _this._canvas) {
  82922. _this.exitVR();
  82923. if (!_this._useCustomVRButton) {
  82924. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  82925. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  82926. }
  82927. }
  82928. };
  82929. this.beforeRender = function () {
  82930. if (_this.leftController && _this.leftController._activePointer) {
  82931. _this._castRayAndSelectObject(_this.leftController);
  82932. }
  82933. if (_this.rightController && _this.rightController._activePointer) {
  82934. _this._castRayAndSelectObject(_this.rightController);
  82935. }
  82936. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  82937. _this._castRayAndSelectObject(_this._cameraGazer);
  82938. }
  82939. else {
  82940. _this._cameraGazer._gazeTracker.isVisible = false;
  82941. }
  82942. };
  82943. this._onNewGamepadConnected = function (gamepad) {
  82944. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82945. if (gamepad.leftStick) {
  82946. gamepad.onleftstickchanged(function (stickValues) {
  82947. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  82948. // Listening to classic/xbox gamepad only if no VR controller is active
  82949. if ((!_this.leftController && !_this.rightController) ||
  82950. ((_this.leftController && !_this.leftController._activePointer) &&
  82951. (_this.rightController && !_this.rightController._activePointer))) {
  82952. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  82953. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  82954. }
  82955. }
  82956. });
  82957. }
  82958. if (gamepad.rightStick) {
  82959. gamepad.onrightstickchanged(function (stickValues) {
  82960. if (_this._teleportationInitialized) {
  82961. _this._checkRotate(stickValues, _this._cameraGazer);
  82962. }
  82963. });
  82964. }
  82965. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  82966. gamepad.onbuttondown(function (buttonPressed) {
  82967. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82968. _this._cameraGazer._selectionPointerDown();
  82969. }
  82970. });
  82971. gamepad.onbuttonup(function (buttonPressed) {
  82972. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82973. _this._cameraGazer._selectionPointerUp();
  82974. }
  82975. });
  82976. }
  82977. }
  82978. else {
  82979. var webVRController = gamepad;
  82980. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  82981. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  82982. _this.rightController = controller;
  82983. }
  82984. else {
  82985. _this.leftController = controller;
  82986. }
  82987. _this._tryEnableInteractionOnController(controller);
  82988. }
  82989. };
  82990. // 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
  82991. this._tryEnableInteractionOnController = function (controller) {
  82992. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  82993. _this._enableInteractionOnController(controller);
  82994. }
  82995. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  82996. _this._enableTeleportationOnController(controller);
  82997. }
  82998. };
  82999. this._onNewGamepadDisconnected = function (gamepad) {
  83000. if (gamepad instanceof BABYLON.WebVRController) {
  83001. if (gamepad.hand === "left" && _this.leftController != null) {
  83002. _this.leftController.dispose();
  83003. _this.leftController = null;
  83004. }
  83005. if (gamepad.hand === "right" && _this.rightController != null) {
  83006. _this.rightController.dispose();
  83007. _this.rightController = null;
  83008. }
  83009. }
  83010. };
  83011. this._workingVector = BABYLON.Vector3.Zero();
  83012. this._workingQuaternion = BABYLON.Quaternion.Identity();
  83013. this._workingMatrix = BABYLON.Matrix.Identity();
  83014. this._scene = scene;
  83015. this._canvas = scene.getEngine().getRenderingCanvas();
  83016. // Parse options
  83017. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  83018. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  83019. }
  83020. if (webVROptions.createDeviceOrientationCamera === undefined) {
  83021. webVROptions.createDeviceOrientationCamera = true;
  83022. }
  83023. if (webVROptions.defaultHeight === undefined) {
  83024. webVROptions.defaultHeight = 1.7;
  83025. }
  83026. if (webVROptions.useCustomVRButton) {
  83027. this._useCustomVRButton = true;
  83028. if (webVROptions.customVRButton) {
  83029. this._btnVR = webVROptions.customVRButton;
  83030. }
  83031. }
  83032. if (webVROptions.rayLength) {
  83033. this._rayLength = webVROptions.rayLength;
  83034. }
  83035. this._defaultHeight = webVROptions.defaultHeight;
  83036. if (webVROptions.positionScale) {
  83037. this._rayLength *= webVROptions.positionScale;
  83038. this._defaultHeight *= webVROptions.positionScale;
  83039. }
  83040. // Set position
  83041. if (this._scene.activeCamera) {
  83042. this._position = this._scene.activeCamera.position.clone();
  83043. }
  83044. else {
  83045. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  83046. }
  83047. // Set non-vr camera
  83048. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  83049. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  83050. // Copy data from existing camera
  83051. if (this._scene.activeCamera) {
  83052. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  83053. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  83054. // Set rotation from previous camera
  83055. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  83056. var targetCamera = this._scene.activeCamera;
  83057. if (targetCamera.rotationQuaternion) {
  83058. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  83059. }
  83060. else {
  83061. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  83062. }
  83063. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  83064. }
  83065. }
  83066. this._scene.activeCamera = this._deviceOrientationCamera;
  83067. if (this._canvas) {
  83068. this._scene.activeCamera.attachControl(this._canvas);
  83069. }
  83070. }
  83071. else {
  83072. this._existingCamera = this._scene.activeCamera;
  83073. }
  83074. // Create VR cameras
  83075. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83076. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  83077. }
  83078. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  83079. this._webVRCamera.useStandingMatrix();
  83080. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  83081. // Create default button
  83082. if (!this._useCustomVRButton) {
  83083. this._btnVR = document.createElement("BUTTON");
  83084. this._btnVR.className = "babylonVRicon";
  83085. this._btnVR.id = "babylonVRiconbtn";
  83086. this._btnVR.title = "Click to switch to VR";
  83087. 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) }";
  83088. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  83089. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  83090. // css += ".babylonVRicon.vrdisplaysupported { }";
  83091. // css += ".babylonVRicon.vrdisplayready { }";
  83092. // css += ".babylonVRicon.vrdisplayrequesting { }";
  83093. var style = document.createElement('style');
  83094. style.appendChild(document.createTextNode(css));
  83095. document.getElementsByTagName('head')[0].appendChild(style);
  83096. this.moveButtonToBottomRight();
  83097. }
  83098. // VR button click event
  83099. if (this._btnVR) {
  83100. this._btnVR.addEventListener("click", function () {
  83101. if (!_this.isInVRMode) {
  83102. _this.enterVR();
  83103. }
  83104. else {
  83105. _this.exitVR();
  83106. }
  83107. });
  83108. }
  83109. // Window events
  83110. window.addEventListener("resize", this._onResize);
  83111. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  83112. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  83113. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  83114. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  83115. // Display vr button when headset is connected
  83116. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83117. this.displayVRButton();
  83118. }
  83119. else {
  83120. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  83121. if (e.vrDisplay) {
  83122. _this.displayVRButton();
  83123. }
  83124. });
  83125. }
  83126. // Exiting VR mode using 'ESC' key on desktop
  83127. this._onKeyDown = function (event) {
  83128. if (event.keyCode === 27 && _this.isInVRMode) {
  83129. _this.exitVR();
  83130. }
  83131. };
  83132. document.addEventListener("keydown", this._onKeyDown);
  83133. // Exiting VR mode double tapping the touch screen
  83134. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  83135. if (_this.isInVRMode) {
  83136. _this.exitVR();
  83137. if (_this._fullscreenVRpresenting) {
  83138. _this._scene.getEngine().switchFullscreen(true);
  83139. }
  83140. }
  83141. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  83142. // Listen for WebVR display changes
  83143. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  83144. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  83145. this._onVRRequestPresentStart = function () {
  83146. _this._webVRrequesting = true;
  83147. _this.updateButtonVisibility();
  83148. };
  83149. this._onVRRequestPresentComplete = function (success) {
  83150. _this._webVRrequesting = false;
  83151. _this.updateButtonVisibility();
  83152. };
  83153. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  83154. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  83155. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  83156. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83157. scene.onDisposeObservable.add(function () {
  83158. _this.dispose();
  83159. });
  83160. // Gamepad connection events
  83161. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  83162. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  83163. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  83164. this.updateButtonVisibility();
  83165. //create easing functions
  83166. this._circleEase = new BABYLON.CircleEase();
  83167. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83168. }
  83169. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  83170. /** Return this.onEnteringVRObservable
  83171. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  83172. */
  83173. get: function () {
  83174. return this.onEnteringVRObservable;
  83175. },
  83176. enumerable: true,
  83177. configurable: true
  83178. });
  83179. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  83180. /** Return this.onExitingVRObservable
  83181. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  83182. */
  83183. get: function () {
  83184. return this.onExitingVRObservable;
  83185. },
  83186. enumerable: true,
  83187. configurable: true
  83188. });
  83189. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  83190. /** Return this.onControllerMeshLoadedObservable
  83191. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  83192. */
  83193. get: function () {
  83194. return this.onControllerMeshLoadedObservable;
  83195. },
  83196. enumerable: true,
  83197. configurable: true
  83198. });
  83199. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  83200. /**
  83201. * The mesh used to display where the user is going to teleport.
  83202. */
  83203. get: function () {
  83204. return this._teleportationTarget;
  83205. },
  83206. /**
  83207. * Sets the mesh to be used to display where the user is going to teleport.
  83208. */
  83209. set: function (value) {
  83210. if (value) {
  83211. value.name = "teleportationTarget";
  83212. this._isDefaultTeleportationTarget = false;
  83213. this._teleportationTarget = value;
  83214. }
  83215. },
  83216. enumerable: true,
  83217. configurable: true
  83218. });
  83219. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  83220. /**
  83221. * The mesh used to display where the user is selecting,
  83222. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  83223. * See http://doc.babylonjs.com/resources/baking_transformations
  83224. */
  83225. get: function () {
  83226. return this._cameraGazer._gazeTracker;
  83227. },
  83228. set: function (value) {
  83229. if (value) {
  83230. this._cameraGazer._gazeTracker = value;
  83231. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  83232. this._cameraGazer._gazeTracker.isPickable = false;
  83233. this._cameraGazer._gazeTracker.isVisible = false;
  83234. this._cameraGazer._gazeTracker.name = "gazeTracker";
  83235. if (this.leftController) {
  83236. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83237. }
  83238. if (this.rightController) {
  83239. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83240. }
  83241. }
  83242. },
  83243. enumerable: true,
  83244. configurable: true
  83245. });
  83246. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  83247. /**
  83248. * If the ray of the gaze should be displayed.
  83249. */
  83250. get: function () {
  83251. return this._displayGaze;
  83252. },
  83253. /**
  83254. * Sets if the ray of the gaze should be displayed.
  83255. */
  83256. set: function (value) {
  83257. this._displayGaze = value;
  83258. if (!value) {
  83259. this._cameraGazer._gazeTracker.isVisible = false;
  83260. if (this.leftController) {
  83261. this.leftController._gazeTracker.isVisible = false;
  83262. }
  83263. if (this.rightController) {
  83264. this.rightController._gazeTracker.isVisible = false;
  83265. }
  83266. }
  83267. },
  83268. enumerable: true,
  83269. configurable: true
  83270. });
  83271. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  83272. /**
  83273. * If the ray of the LaserPointer should be displayed.
  83274. */
  83275. get: function () {
  83276. return this._displayLaserPointer;
  83277. },
  83278. /**
  83279. * Sets if the ray of the LaserPointer should be displayed.
  83280. */
  83281. set: function (value) {
  83282. this._displayLaserPointer = value;
  83283. if (!value) {
  83284. if (this.rightController) {
  83285. this.rightController._deactivatePointer();
  83286. this.rightController._gazeTracker.isVisible = false;
  83287. }
  83288. if (this.leftController) {
  83289. this.leftController._deactivatePointer();
  83290. this.leftController._gazeTracker.isVisible = false;
  83291. }
  83292. }
  83293. else {
  83294. if (this.rightController) {
  83295. this.rightController._activatePointer();
  83296. }
  83297. else if (this.leftController) {
  83298. this.leftController._activatePointer();
  83299. }
  83300. }
  83301. },
  83302. enumerable: true,
  83303. configurable: true
  83304. });
  83305. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  83306. /**
  83307. * The deviceOrientationCamera used as the camera when not in VR.
  83308. */
  83309. get: function () {
  83310. return this._deviceOrientationCamera;
  83311. },
  83312. enumerable: true,
  83313. configurable: true
  83314. });
  83315. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  83316. /**
  83317. * Based on the current WebVR support, returns the current VR camera used.
  83318. */
  83319. get: function () {
  83320. if (this._webVRready) {
  83321. return this._webVRCamera;
  83322. }
  83323. else {
  83324. return this._scene.activeCamera;
  83325. }
  83326. },
  83327. enumerable: true,
  83328. configurable: true
  83329. });
  83330. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  83331. /**
  83332. * The webVRCamera which is used when in VR.
  83333. */
  83334. get: function () {
  83335. return this._webVRCamera;
  83336. },
  83337. enumerable: true,
  83338. configurable: true
  83339. });
  83340. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  83341. /**
  83342. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  83343. */
  83344. get: function () {
  83345. return this._vrDeviceOrientationCamera;
  83346. },
  83347. enumerable: true,
  83348. configurable: true
  83349. });
  83350. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  83351. get: function () {
  83352. var result = this._cameraGazer._teleportationRequestInitiated
  83353. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  83354. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  83355. return result;
  83356. },
  83357. enumerable: true,
  83358. configurable: true
  83359. });
  83360. // Raised when one of the controller has loaded successfully its associated default mesh
  83361. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  83362. if (this.leftController && this.leftController.webVRController == webVRController) {
  83363. if (webVRController.mesh) {
  83364. this.leftController._setLaserPointerParent(webVRController.mesh);
  83365. }
  83366. }
  83367. if (this.rightController && this.rightController.webVRController == webVRController) {
  83368. if (webVRController.mesh) {
  83369. this.rightController._setLaserPointerParent(webVRController.mesh);
  83370. }
  83371. }
  83372. try {
  83373. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83374. }
  83375. catch (err) {
  83376. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83377. }
  83378. };
  83379. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83380. /**
  83381. * Gets a value indicating if we are currently in VR mode.
  83382. */
  83383. get: function () {
  83384. return this._webVRpresenting || this._fullscreenVRpresenting;
  83385. },
  83386. enumerable: true,
  83387. configurable: true
  83388. });
  83389. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83390. var vrDisplay = this._scene.getEngine().getVRDevice();
  83391. if (vrDisplay) {
  83392. var wasPresenting = this._webVRpresenting;
  83393. // A VR display is connected
  83394. this._webVRpresenting = vrDisplay.isPresenting;
  83395. if (wasPresenting && !this._webVRpresenting)
  83396. this.exitVR();
  83397. }
  83398. else {
  83399. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83400. }
  83401. this.updateButtonVisibility();
  83402. };
  83403. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83404. this._webVRsupported = eventArgs.vrSupported;
  83405. this._webVRready = !!eventArgs.vrDisplay;
  83406. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83407. this.updateButtonVisibility();
  83408. };
  83409. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83410. if (this._canvas && !this._useCustomVRButton) {
  83411. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83412. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83413. }
  83414. };
  83415. VRExperienceHelper.prototype.displayVRButton = function () {
  83416. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83417. document.body.appendChild(this._btnVR);
  83418. this._btnVRDisplayed = true;
  83419. }
  83420. };
  83421. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83422. if (!this._btnVR || this._useCustomVRButton) {
  83423. return;
  83424. }
  83425. this._btnVR.className = "babylonVRicon";
  83426. if (this.isInVRMode) {
  83427. this._btnVR.className += " vrdisplaypresenting";
  83428. }
  83429. else {
  83430. if (this._webVRready)
  83431. this._btnVR.className += " vrdisplayready";
  83432. if (this._webVRsupported)
  83433. this._btnVR.className += " vrdisplaysupported";
  83434. if (this._webVRrequesting)
  83435. this._btnVR.className += " vrdisplayrequesting";
  83436. }
  83437. };
  83438. /**
  83439. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83440. * Otherwise, will use the fullscreen API.
  83441. */
  83442. VRExperienceHelper.prototype.enterVR = function () {
  83443. if (this.onEnteringVRObservable) {
  83444. try {
  83445. this.onEnteringVRObservable.notifyObservers(this);
  83446. }
  83447. catch (err) {
  83448. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83449. }
  83450. }
  83451. if (this._scene.activeCamera) {
  83452. this._position = this._scene.activeCamera.position.clone();
  83453. // make sure that we return to the last active camera
  83454. this._existingCamera = this._scene.activeCamera;
  83455. }
  83456. if (this._webVRrequesting)
  83457. return;
  83458. // If WebVR is supported and a headset is connected
  83459. if (this._webVRready) {
  83460. if (!this._webVRpresenting) {
  83461. this._webVRCamera.position = this._position;
  83462. this._scene.activeCamera = this._webVRCamera;
  83463. }
  83464. }
  83465. else if (this._vrDeviceOrientationCamera) {
  83466. this._vrDeviceOrientationCamera.position = this._position;
  83467. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83468. this._scene.getEngine().switchFullscreen(true);
  83469. this.updateButtonVisibility();
  83470. }
  83471. if (this._scene.activeCamera && this._canvas) {
  83472. this._scene.activeCamera.attachControl(this._canvas);
  83473. }
  83474. if (this._interactionsEnabled) {
  83475. this._scene.registerBeforeRender(this.beforeRender);
  83476. }
  83477. };
  83478. /**
  83479. * Attempt to exit VR, or fullscreen.
  83480. */
  83481. VRExperienceHelper.prototype.exitVR = function () {
  83482. if (this.onExitingVRObservable) {
  83483. try {
  83484. this.onExitingVRObservable.notifyObservers(this);
  83485. }
  83486. catch (err) {
  83487. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83488. }
  83489. }
  83490. if (this._webVRpresenting) {
  83491. this._scene.getEngine().disableVR();
  83492. }
  83493. if (this._scene.activeCamera) {
  83494. this._position = this._scene.activeCamera.position.clone();
  83495. }
  83496. if (this._deviceOrientationCamera) {
  83497. this._deviceOrientationCamera.position = this._position;
  83498. this._scene.activeCamera = this._deviceOrientationCamera;
  83499. if (this._canvas) {
  83500. this._scene.activeCamera.attachControl(this._canvas);
  83501. }
  83502. }
  83503. else if (this._existingCamera) {
  83504. this._existingCamera.position = this._position;
  83505. this._scene.activeCamera = this._existingCamera;
  83506. }
  83507. this.updateButtonVisibility();
  83508. if (this._interactionsEnabled) {
  83509. this._scene.unregisterBeforeRender(this.beforeRender);
  83510. }
  83511. };
  83512. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83513. /**
  83514. * The position of the vr experience helper.
  83515. */
  83516. get: function () {
  83517. return this._position;
  83518. },
  83519. /**
  83520. * Sets the position of the vr experience helper.
  83521. */
  83522. set: function (value) {
  83523. this._position = value;
  83524. if (this._scene.activeCamera) {
  83525. this._scene.activeCamera.position = value;
  83526. }
  83527. },
  83528. enumerable: true,
  83529. configurable: true
  83530. });
  83531. /**
  83532. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83533. */
  83534. VRExperienceHelper.prototype.enableInteractions = function () {
  83535. var _this = this;
  83536. if (!this._interactionsEnabled) {
  83537. this._interactionsRequested = true;
  83538. if (this.leftController) {
  83539. this._enableInteractionOnController(this.leftController);
  83540. }
  83541. if (this.rightController) {
  83542. this._enableInteractionOnController(this.rightController);
  83543. }
  83544. this.raySelectionPredicate = function (mesh) {
  83545. return mesh.isVisible;
  83546. };
  83547. this.meshSelectionPredicate = function (mesh) {
  83548. return true;
  83549. };
  83550. this._raySelectionPredicate = function (mesh) {
  83551. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83552. && mesh.name.indexOf("teleportationTarget") === -1
  83553. && mesh.name.indexOf("torusTeleportation") === -1
  83554. && mesh.name.indexOf("laserPointer") === -1)) {
  83555. return _this.raySelectionPredicate(mesh);
  83556. }
  83557. return false;
  83558. };
  83559. this._interactionsEnabled = true;
  83560. }
  83561. };
  83562. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83563. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83564. if (this._floorMeshesCollection[i].id === mesh.id) {
  83565. return true;
  83566. }
  83567. }
  83568. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83569. return true;
  83570. }
  83571. return false;
  83572. };
  83573. /**
  83574. * Adds a floor mesh to be used for teleportation.
  83575. * @param floorMesh the mesh to be used for teleportation.
  83576. */
  83577. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83578. if (!this._floorMeshesCollection) {
  83579. return;
  83580. }
  83581. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83582. return;
  83583. }
  83584. this._floorMeshesCollection.push(floorMesh);
  83585. };
  83586. /**
  83587. * Removes a floor mesh from being used for teleportation.
  83588. * @param floorMesh the mesh to be removed.
  83589. */
  83590. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83591. if (!this._floorMeshesCollection) {
  83592. return;
  83593. }
  83594. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83595. if (meshIndex !== -1) {
  83596. this._floorMeshesCollection.splice(meshIndex, 1);
  83597. }
  83598. };
  83599. /**
  83600. * Enables interactions and teleportation using the VR controllers and gaze.
  83601. * @param vrTeleportationOptions options to modify teleportation behavior.
  83602. */
  83603. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83604. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83605. if (!this._teleportationInitialized) {
  83606. this._teleportationRequested = true;
  83607. this.enableInteractions();
  83608. if (vrTeleportationOptions.floorMeshName) {
  83609. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83610. }
  83611. if (vrTeleportationOptions.floorMeshes) {
  83612. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83613. }
  83614. if (this.leftController != null) {
  83615. this._enableTeleportationOnController(this.leftController);
  83616. }
  83617. if (this.rightController != null) {
  83618. this._enableTeleportationOnController(this.rightController);
  83619. }
  83620. // Creates an image processing post process for the vignette not relying
  83621. // on the main scene configuration for image processing to reduce setup and spaces
  83622. // (gamma/linear) conflicts.
  83623. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83624. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83625. imageProcessingConfiguration.vignetteEnabled = true;
  83626. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83627. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83628. this._teleportationInitialized = true;
  83629. if (this._isDefaultTeleportationTarget) {
  83630. this._createTeleportationCircles();
  83631. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83632. }
  83633. }
  83634. };
  83635. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83636. var _this = this;
  83637. var controllerMesh = controller.webVRController.mesh;
  83638. if (controllerMesh) {
  83639. controller._interactionsEnabled = true;
  83640. controller._activatePointer();
  83641. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83642. // Enabling / disabling laserPointer
  83643. if (_this._displayLaserPointer && stateObject.value === 1) {
  83644. if (controller._activePointer) {
  83645. controller._deactivatePointer();
  83646. }
  83647. else {
  83648. controller._activatePointer();
  83649. }
  83650. if (_this.displayGaze) {
  83651. controller._gazeTracker.isVisible = controller._activePointer;
  83652. }
  83653. }
  83654. });
  83655. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83656. if (!controller._pointerDownOnMeshAsked) {
  83657. if (stateObject.value > _this._padSensibilityUp) {
  83658. controller._selectionPointerDown();
  83659. }
  83660. }
  83661. else if (stateObject.value < _this._padSensibilityDown) {
  83662. controller._selectionPointerUp();
  83663. }
  83664. });
  83665. }
  83666. };
  83667. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83668. // Dont teleport if another gaze already requested teleportation
  83669. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83670. return;
  83671. }
  83672. if (!gazer._teleportationRequestInitiated) {
  83673. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83674. gazer._activatePointer();
  83675. gazer._teleportationRequestInitiated = true;
  83676. }
  83677. }
  83678. else {
  83679. // Listening to the proper controller values changes to confirm teleportation
  83680. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83681. if (this._teleportActive) {
  83682. this._teleportCamera(this._haloCenter);
  83683. }
  83684. gazer._teleportationRequestInitiated = false;
  83685. }
  83686. }
  83687. };
  83688. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83689. // Only rotate when user is not currently selecting a teleportation location
  83690. if (gazer._teleportationRequestInitiated) {
  83691. return;
  83692. }
  83693. if (!this._rotationLeftAsked) {
  83694. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83695. this._rotationLeftAsked = true;
  83696. if (this._rotationAllowed) {
  83697. this._rotateCamera(false);
  83698. }
  83699. }
  83700. }
  83701. else {
  83702. if (stateObject.x > -this._padSensibilityDown) {
  83703. this._rotationLeftAsked = false;
  83704. }
  83705. }
  83706. if (!this._rotationRightAsked) {
  83707. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83708. this._rotationRightAsked = true;
  83709. if (this._rotationAllowed) {
  83710. this._rotateCamera(true);
  83711. }
  83712. }
  83713. }
  83714. else {
  83715. if (stateObject.x < this._padSensibilityDown) {
  83716. this._rotationRightAsked = false;
  83717. }
  83718. }
  83719. };
  83720. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83721. // Only teleport backwards when user is not currently selecting a teleportation location
  83722. if (gazer._teleportationRequestInitiated) {
  83723. return;
  83724. }
  83725. // Teleport backwards
  83726. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83727. if (!gazer._teleportationBackRequestInitiated) {
  83728. if (!this.currentVRCamera) {
  83729. return;
  83730. }
  83731. // Get rotation and position of the current camera
  83732. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83733. var position = this.currentVRCamera.position;
  83734. // If the camera has device position, use that instead
  83735. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83736. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83737. position = this.currentVRCamera.devicePosition;
  83738. }
  83739. // Get matrix with only the y rotation of the device rotation
  83740. rotation.toEulerAnglesToRef(this._workingVector);
  83741. this._workingVector.z = 0;
  83742. this._workingVector.x = 0;
  83743. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83744. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83745. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83746. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83747. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83748. var ray = new BABYLON.Ray(position, this._workingVector);
  83749. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83750. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83751. this._teleportCamera(hit.pickedPoint);
  83752. }
  83753. gazer._teleportationBackRequestInitiated = true;
  83754. }
  83755. }
  83756. else {
  83757. gazer._teleportationBackRequestInitiated = false;
  83758. }
  83759. };
  83760. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83761. var _this = this;
  83762. var controllerMesh = controller.webVRController.mesh;
  83763. if (controllerMesh) {
  83764. if (!controller._interactionsEnabled) {
  83765. this._enableInteractionOnController(controller);
  83766. }
  83767. controller._interactionsEnabled = true;
  83768. controller._teleportationEnabled = true;
  83769. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83770. controller._dpadPressed = false;
  83771. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83772. controller._dpadPressed = stateObject.pressed;
  83773. if (!controller._dpadPressed) {
  83774. _this._rotationLeftAsked = false;
  83775. _this._rotationRightAsked = false;
  83776. controller._teleportationBackRequestInitiated = false;
  83777. }
  83778. });
  83779. }
  83780. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83781. if (_this.teleportationEnabled) {
  83782. _this._checkTeleportBackwards(stateObject, controller);
  83783. _this._checkTeleportWithRay(stateObject, controller);
  83784. }
  83785. _this._checkRotate(stateObject, controller);
  83786. });
  83787. }
  83788. };
  83789. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83790. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83791. this._teleportationTarget.isPickable = false;
  83792. var length = 512;
  83793. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83794. dynamicTexture.hasAlpha = true;
  83795. var context = dynamicTexture.getContext();
  83796. var centerX = length / 2;
  83797. var centerY = length / 2;
  83798. var radius = 200;
  83799. context.beginPath();
  83800. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83801. context.fillStyle = this._teleportationFillColor;
  83802. context.fill();
  83803. context.lineWidth = 10;
  83804. context.strokeStyle = this._teleportationBorderColor;
  83805. context.stroke();
  83806. context.closePath();
  83807. dynamicTexture.update();
  83808. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83809. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83810. this._teleportationTarget.material = teleportationCircleMaterial;
  83811. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83812. torus.isPickable = false;
  83813. torus.parent = this._teleportationTarget;
  83814. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83815. var keys = [];
  83816. keys.push({
  83817. frame: 0,
  83818. value: 0
  83819. });
  83820. keys.push({
  83821. frame: 30,
  83822. value: 0.4
  83823. });
  83824. keys.push({
  83825. frame: 60,
  83826. value: 0
  83827. });
  83828. animationInnerCircle.setKeys(keys);
  83829. var easingFunction = new BABYLON.SineEase();
  83830. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83831. animationInnerCircle.setEasingFunction(easingFunction);
  83832. torus.animations = [];
  83833. torus.animations.push(animationInnerCircle);
  83834. this._scene.beginAnimation(torus, 0, 60, true);
  83835. this._hideTeleportationTarget();
  83836. };
  83837. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  83838. this._teleportActive = true;
  83839. if (this._teleportationInitialized) {
  83840. this._teleportationTarget.isVisible = true;
  83841. if (this._isDefaultTeleportationTarget) {
  83842. this._teleportationTarget.getChildren()[0].isVisible = true;
  83843. }
  83844. }
  83845. };
  83846. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  83847. this._teleportActive = false;
  83848. if (this._teleportationInitialized) {
  83849. this._teleportationTarget.isVisible = false;
  83850. if (this._isDefaultTeleportationTarget) {
  83851. this._teleportationTarget.getChildren()[0].isVisible = false;
  83852. }
  83853. }
  83854. };
  83855. VRExperienceHelper.prototype._rotateCamera = function (right) {
  83856. var _this = this;
  83857. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83858. return;
  83859. }
  83860. if (right) {
  83861. this._rotationAngle++;
  83862. }
  83863. else {
  83864. this._rotationAngle--;
  83865. }
  83866. this.currentVRCamera.animations = [];
  83867. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  83868. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83869. var animationRotationKeys = [];
  83870. animationRotationKeys.push({
  83871. frame: 0,
  83872. value: this.currentVRCamera.rotationQuaternion
  83873. });
  83874. animationRotationKeys.push({
  83875. frame: 6,
  83876. value: target
  83877. });
  83878. animationRotation.setKeys(animationRotationKeys);
  83879. animationRotation.setEasingFunction(this._circleEase);
  83880. this.currentVRCamera.animations.push(animationRotation);
  83881. this._postProcessMove.animations = [];
  83882. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83883. var vignetteWeightKeys = [];
  83884. vignetteWeightKeys.push({
  83885. frame: 0,
  83886. value: 0
  83887. });
  83888. vignetteWeightKeys.push({
  83889. frame: 3,
  83890. value: 4
  83891. });
  83892. vignetteWeightKeys.push({
  83893. frame: 6,
  83894. value: 0
  83895. });
  83896. animationPP.setKeys(vignetteWeightKeys);
  83897. animationPP.setEasingFunction(this._circleEase);
  83898. this._postProcessMove.animations.push(animationPP);
  83899. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83900. var vignetteStretchKeys = [];
  83901. vignetteStretchKeys.push({
  83902. frame: 0,
  83903. value: 0
  83904. });
  83905. vignetteStretchKeys.push({
  83906. frame: 3,
  83907. value: 10
  83908. });
  83909. vignetteStretchKeys.push({
  83910. frame: 6,
  83911. value: 0
  83912. });
  83913. animationPP2.setKeys(vignetteStretchKeys);
  83914. animationPP2.setEasingFunction(this._circleEase);
  83915. this._postProcessMove.animations.push(animationPP2);
  83916. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83917. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83918. this._postProcessMove.samples = 4;
  83919. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83920. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  83921. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83922. });
  83923. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  83924. };
  83925. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  83926. if (hit.pickedPoint) {
  83927. if (gazer._teleportationRequestInitiated) {
  83928. this._displayTeleportationTarget();
  83929. this._haloCenter.copyFrom(hit.pickedPoint);
  83930. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  83931. }
  83932. var pickNormal = hit.getNormal(true, false);
  83933. if (pickNormal) {
  83934. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83935. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83936. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  83937. }
  83938. this._teleportationTarget.position.y += 0.1;
  83939. }
  83940. };
  83941. VRExperienceHelper.prototype._teleportCamera = function (location) {
  83942. var _this = this;
  83943. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83944. return;
  83945. }
  83946. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  83947. // offset of the headset from the anchor.
  83948. if (this.webVRCamera.leftCamera) {
  83949. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  83950. this._workingVector.subtractInPlace(this.webVRCamera.position);
  83951. location.subtractToRef(this._workingVector, this._workingVector);
  83952. }
  83953. else {
  83954. this._workingVector.copyFrom(location);
  83955. }
  83956. // Add height to account for user's height offset
  83957. if (this.isInVRMode) {
  83958. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  83959. }
  83960. else {
  83961. this._workingVector.y += this._defaultHeight;
  83962. }
  83963. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  83964. // Create animation from the camera's position to the new location
  83965. this.currentVRCamera.animations = [];
  83966. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83967. var animationCameraTeleportationKeys = [{
  83968. frame: 0,
  83969. value: this.currentVRCamera.position
  83970. },
  83971. {
  83972. frame: 11,
  83973. value: this._workingVector
  83974. }
  83975. ];
  83976. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  83977. animationCameraTeleportation.setEasingFunction(this._circleEase);
  83978. this.currentVRCamera.animations.push(animationCameraTeleportation);
  83979. this._postProcessMove.animations = [];
  83980. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83981. var vignetteWeightKeys = [];
  83982. vignetteWeightKeys.push({
  83983. frame: 0,
  83984. value: 0
  83985. });
  83986. vignetteWeightKeys.push({
  83987. frame: 5,
  83988. value: 8
  83989. });
  83990. vignetteWeightKeys.push({
  83991. frame: 11,
  83992. value: 0
  83993. });
  83994. animationPP.setKeys(vignetteWeightKeys);
  83995. this._postProcessMove.animations.push(animationPP);
  83996. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83997. var vignetteStretchKeys = [];
  83998. vignetteStretchKeys.push({
  83999. frame: 0,
  84000. value: 0
  84001. });
  84002. vignetteStretchKeys.push({
  84003. frame: 5,
  84004. value: 10
  84005. });
  84006. vignetteStretchKeys.push({
  84007. frame: 11,
  84008. value: 0
  84009. });
  84010. animationPP2.setKeys(vignetteStretchKeys);
  84011. this._postProcessMove.animations.push(animationPP2);
  84012. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  84013. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  84014. this._webVRCamera.attachPostProcess(this._postProcessMove);
  84015. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  84016. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  84017. });
  84018. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  84019. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  84020. });
  84021. this._hideTeleportationTarget();
  84022. };
  84023. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  84024. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84025. return;
  84026. }
  84027. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  84028. // Moving the gazeTracker on the mesh face targetted
  84029. if (hit && hit.pickedPoint) {
  84030. if (this._displayGaze) {
  84031. var multiplier = 1;
  84032. gazer._gazeTracker.isVisible = true;
  84033. if (gazer._isActionableMesh) {
  84034. multiplier = 3;
  84035. }
  84036. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  84037. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  84038. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  84039. var pickNormal = hit.getNormal();
  84040. // To avoid z-fighting
  84041. var deltaFighting = 0.002;
  84042. if (pickNormal) {
  84043. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  84044. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  84045. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  84046. }
  84047. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  84048. if (gazer._gazeTracker.position.x < 0) {
  84049. gazer._gazeTracker.position.x += deltaFighting;
  84050. }
  84051. else {
  84052. gazer._gazeTracker.position.x -= deltaFighting;
  84053. }
  84054. if (gazer._gazeTracker.position.y < 0) {
  84055. gazer._gazeTracker.position.y += deltaFighting;
  84056. }
  84057. else {
  84058. gazer._gazeTracker.position.y -= deltaFighting;
  84059. }
  84060. if (gazer._gazeTracker.position.z < 0) {
  84061. gazer._gazeTracker.position.z += deltaFighting;
  84062. }
  84063. else {
  84064. gazer._gazeTracker.position.z -= deltaFighting;
  84065. }
  84066. }
  84067. // Changing the size of the laser pointer based on the distance from the targetted point
  84068. gazer._updatePointerDistance(hit.distance);
  84069. }
  84070. else {
  84071. gazer._gazeTracker.isVisible = false;
  84072. }
  84073. if (hit && hit.pickedMesh) {
  84074. gazer._currentHit = hit;
  84075. if (gazer._pointerDownOnMeshAsked) {
  84076. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  84077. }
  84078. // The object selected is the floor, we're in a teleportation scenario
  84079. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  84080. // Moving the teleportation area to this targetted point
  84081. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  84082. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  84083. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84084. }
  84085. gazer._currentMeshSelected = null;
  84086. if (gazer._teleportationRequestInitiated) {
  84087. this._moveTeleportationSelectorTo(hit, gazer);
  84088. }
  84089. return;
  84090. }
  84091. // If not, we're in a selection scenario
  84092. //this._teleportationAllowed = false;
  84093. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  84094. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  84095. this.onNewMeshPicked.notifyObservers(hit);
  84096. gazer._currentMeshSelected = hit.pickedMesh;
  84097. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  84098. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  84099. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  84100. gazer._isActionableMesh = true;
  84101. }
  84102. else {
  84103. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84104. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84105. gazer._isActionableMesh = false;
  84106. }
  84107. try {
  84108. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  84109. }
  84110. catch (err) {
  84111. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  84112. }
  84113. }
  84114. else {
  84115. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84116. gazer._currentMeshSelected = null;
  84117. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84118. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84119. }
  84120. }
  84121. }
  84122. else {
  84123. gazer._currentHit = null;
  84124. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84125. gazer._currentMeshSelected = null;
  84126. //this._teleportationAllowed = false;
  84127. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84128. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84129. }
  84130. };
  84131. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  84132. if (mesh) {
  84133. this.onSelectedMeshUnselected.notifyObservers(mesh);
  84134. }
  84135. };
  84136. /**
  84137. * Sets the color of the laser ray from the vr controllers.
  84138. * @param color new color for the ray.
  84139. */
  84140. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  84141. if (this.leftController) {
  84142. this.leftController._setLaserPointerColor(color);
  84143. }
  84144. if (this.rightController) {
  84145. this.rightController._setLaserPointerColor(color);
  84146. }
  84147. };
  84148. /**
  84149. * Sets the color of the ray from the vr headsets gaze.
  84150. * @param color new color for the ray.
  84151. */
  84152. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  84153. if (!this._cameraGazer._gazeTracker.material) {
  84154. return;
  84155. }
  84156. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  84157. if (this.leftController) {
  84158. this.leftController._gazeTracker.material.emissiveColor = color;
  84159. }
  84160. if (this.rightController) {
  84161. this.rightController._gazeTracker.material.emissiveColor = color;
  84162. }
  84163. };
  84164. /**
  84165. * Exits VR and disposes of the vr experience helper
  84166. */
  84167. VRExperienceHelper.prototype.dispose = function () {
  84168. if (this.isInVRMode) {
  84169. this.exitVR();
  84170. }
  84171. if (this._postProcessMove) {
  84172. this._postProcessMove.dispose();
  84173. }
  84174. if (this._webVRCamera) {
  84175. this._webVRCamera.dispose();
  84176. }
  84177. if (this._vrDeviceOrientationCamera) {
  84178. this._vrDeviceOrientationCamera.dispose();
  84179. }
  84180. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  84181. document.body.removeChild(this._btnVR);
  84182. }
  84183. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  84184. this._deviceOrientationCamera.dispose();
  84185. }
  84186. if (this._cameraGazer) {
  84187. this._cameraGazer.dispose();
  84188. }
  84189. if (this.leftController) {
  84190. this.leftController.dispose();
  84191. }
  84192. if (this.rightController) {
  84193. this.rightController.dispose();
  84194. }
  84195. if (this._teleportationTarget) {
  84196. this._teleportationTarget.dispose();
  84197. }
  84198. this._floorMeshesCollection = [];
  84199. document.removeEventListener("keydown", this._onKeyDown);
  84200. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84201. window.removeEventListener("resize", this._onResize);
  84202. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  84203. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  84204. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  84205. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  84206. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  84207. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  84208. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  84209. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84210. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  84211. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  84212. this._scene.unregisterBeforeRender(this.beforeRender);
  84213. };
  84214. /**
  84215. * Gets the name of the VRExperienceHelper class
  84216. * @returns "VRExperienceHelper"
  84217. */
  84218. VRExperienceHelper.prototype.getClassName = function () {
  84219. return "VRExperienceHelper";
  84220. };
  84221. return VRExperienceHelper;
  84222. }());
  84223. BABYLON.VRExperienceHelper = VRExperienceHelper;
  84224. })(BABYLON || (BABYLON = {}));
  84225. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  84226. "use strict";
  84227. // Mainly based on these 2 articles :
  84228. // 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
  84229. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  84230. var BABYLON;
  84231. (function (BABYLON) {
  84232. var JoystickAxis;
  84233. (function (JoystickAxis) {
  84234. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  84235. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  84236. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  84237. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  84238. var VirtualJoystick = /** @class */ (function () {
  84239. function VirtualJoystick(leftJoystick) {
  84240. var _this = this;
  84241. if (leftJoystick) {
  84242. this._leftJoystick = true;
  84243. }
  84244. else {
  84245. this._leftJoystick = false;
  84246. }
  84247. VirtualJoystick._globalJoystickIndex++;
  84248. // By default left & right arrow keys are moving the X
  84249. // and up & down keys are moving the Y
  84250. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84251. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84252. this.reverseLeftRight = false;
  84253. this.reverseUpDown = false;
  84254. // collections of pointers
  84255. this._touches = new BABYLON.StringDictionary();
  84256. this.deltaPosition = BABYLON.Vector3.Zero();
  84257. this._joystickSensibility = 25;
  84258. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84259. this._onResize = function (evt) {
  84260. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84261. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84262. if (VirtualJoystick.vjCanvas) {
  84263. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  84264. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  84265. }
  84266. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  84267. };
  84268. // injecting a canvas element on top of the canvas 3D game
  84269. if (!VirtualJoystick.vjCanvas) {
  84270. window.addEventListener("resize", this._onResize, false);
  84271. VirtualJoystick.vjCanvas = document.createElement("canvas");
  84272. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84273. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84274. VirtualJoystick.vjCanvas.width = window.innerWidth;
  84275. VirtualJoystick.vjCanvas.height = window.innerHeight;
  84276. VirtualJoystick.vjCanvas.style.width = "100%";
  84277. VirtualJoystick.vjCanvas.style.height = "100%";
  84278. VirtualJoystick.vjCanvas.style.position = "absolute";
  84279. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  84280. VirtualJoystick.vjCanvas.style.top = "0px";
  84281. VirtualJoystick.vjCanvas.style.left = "0px";
  84282. VirtualJoystick.vjCanvas.style.zIndex = "5";
  84283. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  84284. // Support for jQuery PEP polyfill
  84285. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  84286. var context = VirtualJoystick.vjCanvas.getContext('2d');
  84287. if (!context) {
  84288. throw new Error("Unable to create canvas for virtual joystick");
  84289. }
  84290. VirtualJoystick.vjCanvasContext = context;
  84291. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  84292. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84293. document.body.appendChild(VirtualJoystick.vjCanvas);
  84294. }
  84295. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  84296. this.pressed = false;
  84297. // default joystick color
  84298. this._joystickColor = "cyan";
  84299. this._joystickPointerID = -1;
  84300. // current joystick position
  84301. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  84302. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  84303. // origin joystick position
  84304. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  84305. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  84306. this._onPointerDownHandlerRef = function (evt) {
  84307. _this._onPointerDown(evt);
  84308. };
  84309. this._onPointerMoveHandlerRef = function (evt) {
  84310. _this._onPointerMove(evt);
  84311. };
  84312. this._onPointerUpHandlerRef = function (evt) {
  84313. _this._onPointerUp(evt);
  84314. };
  84315. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  84316. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  84317. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  84318. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  84319. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  84320. evt.preventDefault(); // Disables system menu
  84321. }, false);
  84322. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84323. }
  84324. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  84325. this._joystickSensibility = newJoystickSensibility;
  84326. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84327. };
  84328. VirtualJoystick.prototype._onPointerDown = function (e) {
  84329. var positionOnScreenCondition;
  84330. e.preventDefault();
  84331. if (this._leftJoystick === true) {
  84332. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  84333. }
  84334. else {
  84335. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  84336. }
  84337. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  84338. // First contact will be dedicated to the virtual joystick
  84339. this._joystickPointerID = e.pointerId;
  84340. this._joystickPointerStartPos.x = e.clientX;
  84341. this._joystickPointerStartPos.y = e.clientY;
  84342. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  84343. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  84344. this._deltaJoystickVector.x = 0;
  84345. this._deltaJoystickVector.y = 0;
  84346. this.pressed = true;
  84347. this._touches.add(e.pointerId.toString(), e);
  84348. }
  84349. else {
  84350. // You can only trigger the action buttons with a joystick declared
  84351. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  84352. this._action();
  84353. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  84354. }
  84355. }
  84356. };
  84357. VirtualJoystick.prototype._onPointerMove = function (e) {
  84358. // If the current pointer is the one associated to the joystick (first touch contact)
  84359. if (this._joystickPointerID == e.pointerId) {
  84360. this._joystickPointerPos.x = e.clientX;
  84361. this._joystickPointerPos.y = e.clientY;
  84362. this._deltaJoystickVector = this._joystickPointerPos.clone();
  84363. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  84364. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  84365. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  84366. switch (this._axisTargetedByLeftAndRight) {
  84367. case JoystickAxis.X:
  84368. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  84369. break;
  84370. case JoystickAxis.Y:
  84371. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84372. break;
  84373. case JoystickAxis.Z:
  84374. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84375. break;
  84376. }
  84377. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84378. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84379. switch (this._axisTargetedByUpAndDown) {
  84380. case JoystickAxis.X:
  84381. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84382. break;
  84383. case JoystickAxis.Y:
  84384. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84385. break;
  84386. case JoystickAxis.Z:
  84387. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84388. break;
  84389. }
  84390. }
  84391. else {
  84392. var data = this._touches.get(e.pointerId.toString());
  84393. if (data) {
  84394. data.x = e.clientX;
  84395. data.y = e.clientY;
  84396. }
  84397. }
  84398. };
  84399. VirtualJoystick.prototype._onPointerUp = function (e) {
  84400. if (this._joystickPointerID == e.pointerId) {
  84401. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84402. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84403. this._joystickPointerID = -1;
  84404. this.pressed = false;
  84405. }
  84406. else {
  84407. var touch = this._touches.get(e.pointerId.toString());
  84408. if (touch) {
  84409. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84410. }
  84411. }
  84412. this._deltaJoystickVector.x = 0;
  84413. this._deltaJoystickVector.y = 0;
  84414. this._touches.remove(e.pointerId.toString());
  84415. };
  84416. /**
  84417. * Change the color of the virtual joystick
  84418. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84419. */
  84420. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84421. this._joystickColor = newColor;
  84422. };
  84423. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84424. this._action = action;
  84425. };
  84426. // Define which axis you'd like to control for left & right
  84427. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84428. switch (axis) {
  84429. case JoystickAxis.X:
  84430. case JoystickAxis.Y:
  84431. case JoystickAxis.Z:
  84432. this._axisTargetedByLeftAndRight = axis;
  84433. break;
  84434. default:
  84435. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84436. break;
  84437. }
  84438. };
  84439. // Define which axis you'd like to control for up & down
  84440. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84441. switch (axis) {
  84442. case JoystickAxis.X:
  84443. case JoystickAxis.Y:
  84444. case JoystickAxis.Z:
  84445. this._axisTargetedByUpAndDown = axis;
  84446. break;
  84447. default:
  84448. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84449. break;
  84450. }
  84451. };
  84452. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84453. var _this = this;
  84454. if (this.pressed) {
  84455. this._touches.forEach(function (key, touch) {
  84456. if (touch.pointerId === _this._joystickPointerID) {
  84457. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84458. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84459. VirtualJoystick.vjCanvasContext.beginPath();
  84460. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84461. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84462. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84463. VirtualJoystick.vjCanvasContext.stroke();
  84464. VirtualJoystick.vjCanvasContext.closePath();
  84465. VirtualJoystick.vjCanvasContext.beginPath();
  84466. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84467. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84468. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84469. VirtualJoystick.vjCanvasContext.stroke();
  84470. VirtualJoystick.vjCanvasContext.closePath();
  84471. VirtualJoystick.vjCanvasContext.beginPath();
  84472. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84473. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84474. VirtualJoystick.vjCanvasContext.stroke();
  84475. VirtualJoystick.vjCanvasContext.closePath();
  84476. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84477. }
  84478. else {
  84479. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84480. VirtualJoystick.vjCanvasContext.beginPath();
  84481. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84482. VirtualJoystick.vjCanvasContext.beginPath();
  84483. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84484. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84485. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84486. VirtualJoystick.vjCanvasContext.stroke();
  84487. VirtualJoystick.vjCanvasContext.closePath();
  84488. touch.prevX = touch.x;
  84489. touch.prevY = touch.y;
  84490. }
  84491. ;
  84492. });
  84493. }
  84494. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84495. };
  84496. VirtualJoystick.prototype.releaseCanvas = function () {
  84497. if (VirtualJoystick.vjCanvas) {
  84498. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84499. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84500. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84501. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84502. window.removeEventListener("resize", this._onResize);
  84503. document.body.removeChild(VirtualJoystick.vjCanvas);
  84504. VirtualJoystick.vjCanvas = null;
  84505. }
  84506. };
  84507. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84508. VirtualJoystick._globalJoystickIndex = 0;
  84509. return VirtualJoystick;
  84510. }());
  84511. BABYLON.VirtualJoystick = VirtualJoystick;
  84512. })(BABYLON || (BABYLON = {}));
  84513. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84514. "use strict";
  84515. var BABYLON;
  84516. (function (BABYLON) {
  84517. // We're mainly based on the logic defined into the FreeCamera code
  84518. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84519. __extends(VirtualJoysticksCamera, _super);
  84520. function VirtualJoysticksCamera(name, position, scene) {
  84521. var _this = _super.call(this, name, position, scene) || this;
  84522. _this.inputs.addVirtualJoystick();
  84523. return _this;
  84524. }
  84525. VirtualJoysticksCamera.prototype.getClassName = function () {
  84526. return "VirtualJoysticksCamera";
  84527. };
  84528. return VirtualJoysticksCamera;
  84529. }(BABYLON.FreeCamera));
  84530. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84531. })(BABYLON || (BABYLON = {}));
  84532. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84533. "use strict";
  84534. var BABYLON;
  84535. (function (BABYLON) {
  84536. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84537. function FreeCameraVirtualJoystickInput() {
  84538. }
  84539. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84540. return this._leftjoystick;
  84541. };
  84542. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84543. return this._rightjoystick;
  84544. };
  84545. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84546. if (this._leftjoystick) {
  84547. var camera = this.camera;
  84548. var speed = camera._computeLocalCameraSpeed() * 50;
  84549. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84550. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84551. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84552. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84553. if (!this._leftjoystick.pressed) {
  84554. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84555. }
  84556. if (!this._rightjoystick.pressed) {
  84557. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84558. }
  84559. }
  84560. };
  84561. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84562. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84563. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84564. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84565. this._leftjoystick.setJoystickSensibility(0.15);
  84566. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84567. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84568. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84569. this._rightjoystick.reverseUpDown = true;
  84570. this._rightjoystick.setJoystickSensibility(0.05);
  84571. this._rightjoystick.setJoystickColor("yellow");
  84572. };
  84573. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84574. this._leftjoystick.releaseCanvas();
  84575. this._rightjoystick.releaseCanvas();
  84576. };
  84577. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84578. return "FreeCameraVirtualJoystickInput";
  84579. };
  84580. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84581. return "virtualJoystick";
  84582. };
  84583. return FreeCameraVirtualJoystickInput;
  84584. }());
  84585. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84586. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84587. })(BABYLON || (BABYLON = {}));
  84588. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84589. "use strict";
  84590. var BABYLON;
  84591. (function (BABYLON) {
  84592. var SimplificationSettings = /** @class */ (function () {
  84593. function SimplificationSettings(quality, distance, optimizeMesh) {
  84594. this.quality = quality;
  84595. this.distance = distance;
  84596. this.optimizeMesh = optimizeMesh;
  84597. }
  84598. return SimplificationSettings;
  84599. }());
  84600. BABYLON.SimplificationSettings = SimplificationSettings;
  84601. var SimplificationQueue = /** @class */ (function () {
  84602. function SimplificationQueue() {
  84603. this.running = false;
  84604. this._simplificationArray = [];
  84605. }
  84606. SimplificationQueue.prototype.addTask = function (task) {
  84607. this._simplificationArray.push(task);
  84608. };
  84609. SimplificationQueue.prototype.executeNext = function () {
  84610. var task = this._simplificationArray.pop();
  84611. if (task) {
  84612. this.running = true;
  84613. this.runSimplification(task);
  84614. }
  84615. else {
  84616. this.running = false;
  84617. }
  84618. };
  84619. SimplificationQueue.prototype.runSimplification = function (task) {
  84620. var _this = this;
  84621. if (task.parallelProcessing) {
  84622. //parallel simplifier
  84623. task.settings.forEach(function (setting) {
  84624. var simplifier = _this.getSimplifier(task);
  84625. simplifier.simplify(setting, function (newMesh) {
  84626. task.mesh.addLODLevel(setting.distance, newMesh);
  84627. newMesh.isVisible = true;
  84628. //check if it is the last
  84629. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84630. //all done, run the success callback.
  84631. task.successCallback();
  84632. }
  84633. _this.executeNext();
  84634. });
  84635. });
  84636. }
  84637. else {
  84638. //single simplifier.
  84639. var simplifier = this.getSimplifier(task);
  84640. var runDecimation = function (setting, callback) {
  84641. simplifier.simplify(setting, function (newMesh) {
  84642. task.mesh.addLODLevel(setting.distance, newMesh);
  84643. newMesh.isVisible = true;
  84644. //run the next quality level
  84645. callback();
  84646. });
  84647. };
  84648. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84649. runDecimation(task.settings[loop.index], function () {
  84650. loop.executeNext();
  84651. });
  84652. }, function () {
  84653. //execution ended, run the success callback.
  84654. if (task.successCallback) {
  84655. task.successCallback();
  84656. }
  84657. _this.executeNext();
  84658. });
  84659. }
  84660. };
  84661. SimplificationQueue.prototype.getSimplifier = function (task) {
  84662. switch (task.simplificationType) {
  84663. case SimplificationType.QUADRATIC:
  84664. default:
  84665. return new QuadraticErrorSimplification(task.mesh);
  84666. }
  84667. };
  84668. return SimplificationQueue;
  84669. }());
  84670. BABYLON.SimplificationQueue = SimplificationQueue;
  84671. /**
  84672. * The implemented types of simplification.
  84673. * At the moment only Quadratic Error Decimation is implemented.
  84674. */
  84675. var SimplificationType;
  84676. (function (SimplificationType) {
  84677. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84678. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84679. var DecimationTriangle = /** @class */ (function () {
  84680. function DecimationTriangle(vertices) {
  84681. this.vertices = vertices;
  84682. this.error = new Array(4);
  84683. this.deleted = false;
  84684. this.isDirty = false;
  84685. this.deletePending = false;
  84686. this.borderFactor = 0;
  84687. }
  84688. return DecimationTriangle;
  84689. }());
  84690. BABYLON.DecimationTriangle = DecimationTriangle;
  84691. var DecimationVertex = /** @class */ (function () {
  84692. function DecimationVertex(position, id) {
  84693. this.position = position;
  84694. this.id = id;
  84695. this.isBorder = true;
  84696. this.q = new QuadraticMatrix();
  84697. this.triangleCount = 0;
  84698. this.triangleStart = 0;
  84699. this.originalOffsets = [];
  84700. }
  84701. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84702. this.position.copyFrom(newPosition);
  84703. };
  84704. return DecimationVertex;
  84705. }());
  84706. BABYLON.DecimationVertex = DecimationVertex;
  84707. var QuadraticMatrix = /** @class */ (function () {
  84708. function QuadraticMatrix(data) {
  84709. this.data = new Array(10);
  84710. for (var i = 0; i < 10; ++i) {
  84711. if (data && data[i]) {
  84712. this.data[i] = data[i];
  84713. }
  84714. else {
  84715. this.data[i] = 0;
  84716. }
  84717. }
  84718. }
  84719. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84720. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84721. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84722. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84723. return det;
  84724. };
  84725. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84726. for (var i = 0; i < 10; ++i) {
  84727. this.data[i] += matrix.data[i];
  84728. }
  84729. };
  84730. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84731. for (var i = 0; i < 10; ++i) {
  84732. this.data[i] += data[i];
  84733. }
  84734. };
  84735. QuadraticMatrix.prototype.add = function (matrix) {
  84736. var m = new QuadraticMatrix();
  84737. for (var i = 0; i < 10; ++i) {
  84738. m.data[i] = this.data[i] + matrix.data[i];
  84739. }
  84740. return m;
  84741. };
  84742. QuadraticMatrix.FromData = function (a, b, c, d) {
  84743. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84744. };
  84745. //returning an array to avoid garbage collection
  84746. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84747. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84748. };
  84749. return QuadraticMatrix;
  84750. }());
  84751. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84752. var Reference = /** @class */ (function () {
  84753. function Reference(vertexId, triangleId) {
  84754. this.vertexId = vertexId;
  84755. this.triangleId = triangleId;
  84756. }
  84757. return Reference;
  84758. }());
  84759. BABYLON.Reference = Reference;
  84760. /**
  84761. * An implementation of the Quadratic Error simplification algorithm.
  84762. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84763. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84764. * @author RaananW
  84765. */
  84766. var QuadraticErrorSimplification = /** @class */ (function () {
  84767. function QuadraticErrorSimplification(_mesh) {
  84768. this._mesh = _mesh;
  84769. this.syncIterations = 5000;
  84770. this.aggressiveness = 7;
  84771. this.decimationIterations = 100;
  84772. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84773. }
  84774. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84775. var _this = this;
  84776. this.initDecimatedMesh();
  84777. //iterating through the submeshes array, one after the other.
  84778. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84779. _this.initWithMesh(loop.index, function () {
  84780. _this.runDecimation(settings, loop.index, function () {
  84781. loop.executeNext();
  84782. });
  84783. }, settings.optimizeMesh);
  84784. }, function () {
  84785. setTimeout(function () {
  84786. successCallback(_this._reconstructedMesh);
  84787. }, 0);
  84788. });
  84789. };
  84790. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84791. var _this = this;
  84792. var targetCount = ~~(this.triangles.length * settings.quality);
  84793. var deletedTriangles = 0;
  84794. var triangleCount = this.triangles.length;
  84795. var iterationFunction = function (iteration, callback) {
  84796. setTimeout(function () {
  84797. if (iteration % 5 === 0) {
  84798. _this.updateMesh(iteration === 0);
  84799. }
  84800. for (var i = 0; i < _this.triangles.length; ++i) {
  84801. _this.triangles[i].isDirty = false;
  84802. }
  84803. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84804. var trianglesIterator = function (i) {
  84805. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84806. var t = _this.triangles[tIdx];
  84807. if (!t)
  84808. return;
  84809. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84810. return;
  84811. }
  84812. for (var j = 0; j < 3; ++j) {
  84813. if (t.error[j] < threshold) {
  84814. var deleted0 = [];
  84815. var deleted1 = [];
  84816. var v0 = t.vertices[j];
  84817. var v1 = t.vertices[(j + 1) % 3];
  84818. if (v0.isBorder || v1.isBorder)
  84819. continue;
  84820. var p = BABYLON.Vector3.Zero();
  84821. var n = BABYLON.Vector3.Zero();
  84822. var uv = BABYLON.Vector2.Zero();
  84823. var color = new BABYLON.Color4(0, 0, 0, 1);
  84824. _this.calculateError(v0, v1, p, n, uv, color);
  84825. var delTr = new Array();
  84826. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84827. continue;
  84828. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84829. continue;
  84830. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84831. continue;
  84832. var uniqueArray = new Array();
  84833. delTr.forEach(function (deletedT) {
  84834. if (uniqueArray.indexOf(deletedT) === -1) {
  84835. deletedT.deletePending = true;
  84836. uniqueArray.push(deletedT);
  84837. }
  84838. });
  84839. if (uniqueArray.length % 2 !== 0) {
  84840. continue;
  84841. }
  84842. v0.q = v1.q.add(v0.q);
  84843. v0.updatePosition(p);
  84844. var tStart = _this.references.length;
  84845. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  84846. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  84847. var tCount = _this.references.length - tStart;
  84848. if (tCount <= v0.triangleCount) {
  84849. if (tCount) {
  84850. for (var c = 0; c < tCount; c++) {
  84851. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  84852. }
  84853. }
  84854. }
  84855. else {
  84856. v0.triangleStart = tStart;
  84857. }
  84858. v0.triangleCount = tCount;
  84859. break;
  84860. }
  84861. }
  84862. };
  84863. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  84864. }, 0);
  84865. };
  84866. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  84867. if (triangleCount - deletedTriangles <= targetCount)
  84868. loop.breakLoop();
  84869. else {
  84870. iterationFunction(loop.index, function () {
  84871. loop.executeNext();
  84872. });
  84873. }
  84874. }, function () {
  84875. setTimeout(function () {
  84876. //reconstruct this part of the mesh
  84877. _this.reconstructMesh(submeshIndex);
  84878. successCallback();
  84879. }, 0);
  84880. });
  84881. };
  84882. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  84883. var _this = this;
  84884. this.vertices = [];
  84885. this.triangles = [];
  84886. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84887. var indices = this._mesh.getIndices();
  84888. var submesh = this._mesh.subMeshes[submeshIndex];
  84889. var findInVertices = function (positionToSearch) {
  84890. if (optimizeMesh) {
  84891. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  84892. if (_this.vertices[ii].position.equals(positionToSearch)) {
  84893. return _this.vertices[ii];
  84894. }
  84895. }
  84896. }
  84897. return null;
  84898. };
  84899. var vertexReferences = [];
  84900. var vertexInit = function (i) {
  84901. if (!positionData) {
  84902. return;
  84903. }
  84904. var offset = i + submesh.verticesStart;
  84905. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  84906. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  84907. vertex.originalOffsets.push(offset);
  84908. if (vertex.id === _this.vertices.length) {
  84909. _this.vertices.push(vertex);
  84910. }
  84911. vertexReferences.push(vertex.id);
  84912. };
  84913. //var totalVertices = mesh.getTotalVertices();
  84914. var totalVertices = submesh.verticesCount;
  84915. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  84916. var indicesInit = function (i) {
  84917. if (!indices) {
  84918. return;
  84919. }
  84920. var offset = (submesh.indexStart / 3) + i;
  84921. var pos = (offset * 3);
  84922. var i0 = indices[pos + 0];
  84923. var i1 = indices[pos + 1];
  84924. var i2 = indices[pos + 2];
  84925. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  84926. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  84927. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  84928. var triangle = new DecimationTriangle([v0, v1, v2]);
  84929. triangle.originalOffset = pos;
  84930. _this.triangles.push(triangle);
  84931. };
  84932. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  84933. _this.init(callback);
  84934. });
  84935. });
  84936. };
  84937. QuadraticErrorSimplification.prototype.init = function (callback) {
  84938. var _this = this;
  84939. var triangleInit1 = function (i) {
  84940. var t = _this.triangles[i];
  84941. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  84942. for (var j = 0; j < 3; j++) {
  84943. 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))));
  84944. }
  84945. };
  84946. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  84947. var triangleInit2 = function (i) {
  84948. var t = _this.triangles[i];
  84949. for (var j = 0; j < 3; ++j) {
  84950. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  84951. }
  84952. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84953. };
  84954. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  84955. callback();
  84956. });
  84957. });
  84958. };
  84959. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  84960. var newTriangles = [];
  84961. var i;
  84962. for (i = 0; i < this.vertices.length; ++i) {
  84963. this.vertices[i].triangleCount = 0;
  84964. }
  84965. var t;
  84966. var j;
  84967. for (i = 0; i < this.triangles.length; ++i) {
  84968. if (!this.triangles[i].deleted) {
  84969. t = this.triangles[i];
  84970. for (j = 0; j < 3; ++j) {
  84971. t.vertices[j].triangleCount = 1;
  84972. }
  84973. newTriangles.push(t);
  84974. }
  84975. }
  84976. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  84977. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  84978. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  84979. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  84980. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  84981. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84982. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  84983. var vertexCount = 0;
  84984. for (i = 0; i < this.vertices.length; ++i) {
  84985. var vertex = this.vertices[i];
  84986. vertex.id = vertexCount;
  84987. if (vertex.triangleCount) {
  84988. vertex.originalOffsets.forEach(function (originalOffset) {
  84989. if (!normalData) {
  84990. return;
  84991. }
  84992. newPositionData.push(vertex.position.x);
  84993. newPositionData.push(vertex.position.y);
  84994. newPositionData.push(vertex.position.z);
  84995. newNormalData.push(normalData[originalOffset * 3]);
  84996. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  84997. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  84998. if (uvs && uvs.length) {
  84999. newUVsData.push(uvs[(originalOffset * 2)]);
  85000. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  85001. }
  85002. else if (colorsData && colorsData.length) {
  85003. newColorsData.push(colorsData[(originalOffset * 4)]);
  85004. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  85005. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  85006. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  85007. }
  85008. ++vertexCount;
  85009. });
  85010. }
  85011. }
  85012. var startingIndex = this._reconstructedMesh.getTotalIndices();
  85013. var startingVertex = this._reconstructedMesh.getTotalVertices();
  85014. var submeshesArray = this._reconstructedMesh.subMeshes;
  85015. this._reconstructedMesh.subMeshes = [];
  85016. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  85017. var originalIndices = this._mesh.getIndices();
  85018. for (i = 0; i < newTriangles.length; ++i) {
  85019. t = newTriangles[i]; //now get the new referencing point for each vertex
  85020. [0, 1, 2].forEach(function (idx) {
  85021. var id = originalIndices[t.originalOffset + idx];
  85022. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  85023. if (offset < 0)
  85024. offset = 0;
  85025. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  85026. });
  85027. }
  85028. //overwriting the old vertex buffers and indices.
  85029. this._reconstructedMesh.setIndices(newIndicesArray);
  85030. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  85031. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  85032. if (newUVsData.length > 0)
  85033. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  85034. if (newColorsData.length > 0)
  85035. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  85036. //create submesh
  85037. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  85038. if (submeshIndex > 0) {
  85039. this._reconstructedMesh.subMeshes = [];
  85040. submeshesArray.forEach(function (submesh) {
  85041. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  85042. });
  85043. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  85044. }
  85045. };
  85046. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  85047. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  85048. this._reconstructedMesh.material = this._mesh.material;
  85049. this._reconstructedMesh.parent = this._mesh.parent;
  85050. this._reconstructedMesh.isVisible = false;
  85051. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  85052. };
  85053. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  85054. for (var i = 0; i < vertex1.triangleCount; ++i) {
  85055. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  85056. if (t.deleted)
  85057. continue;
  85058. var s = this.references[vertex1.triangleStart + i].vertexId;
  85059. var v1 = t.vertices[(s + 1) % 3];
  85060. var v2 = t.vertices[(s + 2) % 3];
  85061. if ((v1 === vertex2 || v2 === vertex2)) {
  85062. deletedArray[i] = true;
  85063. delTr.push(t);
  85064. continue;
  85065. }
  85066. var d1 = v1.position.subtract(point);
  85067. d1 = d1.normalize();
  85068. var d2 = v2.position.subtract(point);
  85069. d2 = d2.normalize();
  85070. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  85071. return true;
  85072. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  85073. deletedArray[i] = false;
  85074. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  85075. return true;
  85076. }
  85077. return false;
  85078. };
  85079. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  85080. var newDeleted = deletedTriangles;
  85081. for (var i = 0; i < vertex.triangleCount; ++i) {
  85082. var ref = this.references[vertex.triangleStart + i];
  85083. var t = this.triangles[ref.triangleId];
  85084. if (t.deleted)
  85085. continue;
  85086. if (deletedArray[i] && t.deletePending) {
  85087. t.deleted = true;
  85088. newDeleted++;
  85089. continue;
  85090. }
  85091. t.vertices[ref.vertexId] = origVertex;
  85092. t.isDirty = true;
  85093. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  85094. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  85095. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  85096. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  85097. this.references.push(ref);
  85098. }
  85099. return newDeleted;
  85100. };
  85101. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  85102. for (var i = 0; i < this.vertices.length; ++i) {
  85103. var vCount = [];
  85104. var vId = [];
  85105. var v = this.vertices[i];
  85106. var j;
  85107. for (j = 0; j < v.triangleCount; ++j) {
  85108. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  85109. for (var ii = 0; ii < 3; ii++) {
  85110. var ofs = 0;
  85111. var vv = triangle.vertices[ii];
  85112. while (ofs < vCount.length) {
  85113. if (vId[ofs] === vv.id)
  85114. break;
  85115. ++ofs;
  85116. }
  85117. if (ofs === vCount.length) {
  85118. vCount.push(1);
  85119. vId.push(vv.id);
  85120. }
  85121. else {
  85122. vCount[ofs]++;
  85123. }
  85124. }
  85125. }
  85126. for (j = 0; j < vCount.length; ++j) {
  85127. if (vCount[j] === 1) {
  85128. this.vertices[vId[j]].isBorder = true;
  85129. }
  85130. else {
  85131. this.vertices[vId[j]].isBorder = false;
  85132. }
  85133. }
  85134. }
  85135. };
  85136. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  85137. if (identifyBorders === void 0) { identifyBorders = false; }
  85138. var i;
  85139. if (!identifyBorders) {
  85140. var newTrianglesVector = [];
  85141. for (i = 0; i < this.triangles.length; ++i) {
  85142. if (!this.triangles[i].deleted) {
  85143. newTrianglesVector.push(this.triangles[i]);
  85144. }
  85145. }
  85146. this.triangles = newTrianglesVector;
  85147. }
  85148. for (i = 0; i < this.vertices.length; ++i) {
  85149. this.vertices[i].triangleCount = 0;
  85150. this.vertices[i].triangleStart = 0;
  85151. }
  85152. var t;
  85153. var j;
  85154. var v;
  85155. for (i = 0; i < this.triangles.length; ++i) {
  85156. t = this.triangles[i];
  85157. for (j = 0; j < 3; ++j) {
  85158. v = t.vertices[j];
  85159. v.triangleCount++;
  85160. }
  85161. }
  85162. var tStart = 0;
  85163. for (i = 0; i < this.vertices.length; ++i) {
  85164. this.vertices[i].triangleStart = tStart;
  85165. tStart += this.vertices[i].triangleCount;
  85166. this.vertices[i].triangleCount = 0;
  85167. }
  85168. var newReferences = new Array(this.triangles.length * 3);
  85169. for (i = 0; i < this.triangles.length; ++i) {
  85170. t = this.triangles[i];
  85171. for (j = 0; j < 3; ++j) {
  85172. v = t.vertices[j];
  85173. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  85174. v.triangleCount++;
  85175. }
  85176. }
  85177. this.references = newReferences;
  85178. if (identifyBorders) {
  85179. this.identifyBorder();
  85180. }
  85181. };
  85182. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  85183. var x = point.x;
  85184. var y = point.y;
  85185. var z = point.z;
  85186. 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
  85187. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  85188. };
  85189. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  85190. var q = vertex1.q.add(vertex2.q);
  85191. var border = vertex1.isBorder && vertex2.isBorder;
  85192. var error = 0;
  85193. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  85194. if (qDet !== 0 && !border) {
  85195. if (!pointResult) {
  85196. pointResult = BABYLON.Vector3.Zero();
  85197. }
  85198. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  85199. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  85200. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  85201. error = this.vertexError(q, pointResult);
  85202. }
  85203. else {
  85204. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  85205. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  85206. var error1 = this.vertexError(q, vertex1.position);
  85207. var error2 = this.vertexError(q, vertex2.position);
  85208. var error3 = this.vertexError(q, p3);
  85209. error = Math.min(error1, error2, error3);
  85210. if (error === error1) {
  85211. if (pointResult) {
  85212. pointResult.copyFrom(vertex1.position);
  85213. }
  85214. }
  85215. else if (error === error2) {
  85216. if (pointResult) {
  85217. pointResult.copyFrom(vertex2.position);
  85218. }
  85219. }
  85220. else {
  85221. if (pointResult) {
  85222. pointResult.copyFrom(p3);
  85223. }
  85224. }
  85225. }
  85226. return error;
  85227. };
  85228. return QuadraticErrorSimplification;
  85229. }());
  85230. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  85231. })(BABYLON || (BABYLON = {}));
  85232. //# sourceMappingURL=babylon.meshSimplification.js.map
  85233. "use strict";
  85234. var BABYLON;
  85235. (function (BABYLON) {
  85236. var MeshLODLevel = /** @class */ (function () {
  85237. function MeshLODLevel(distance, mesh) {
  85238. this.distance = distance;
  85239. this.mesh = mesh;
  85240. }
  85241. return MeshLODLevel;
  85242. }());
  85243. BABYLON.MeshLODLevel = MeshLODLevel;
  85244. })(BABYLON || (BABYLON = {}));
  85245. //# sourceMappingURL=babylon.meshLODLevel.js.map
  85246. "use strict";
  85247. var BABYLON;
  85248. (function (BABYLON) {
  85249. /**
  85250. * Defines the root class used to create scene optimization to use with SceneOptimizer
  85251. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85252. */
  85253. var SceneOptimization = /** @class */ (function () {
  85254. /**
  85255. * Creates the SceneOptimization object
  85256. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85257. * @param desc defines the description associated with the optimization
  85258. */
  85259. function SceneOptimization(
  85260. /**
  85261. * Defines the priority of this optimization (0 by default which means first in the list)
  85262. */
  85263. priority) {
  85264. if (priority === void 0) { priority = 0; }
  85265. this.priority = priority;
  85266. }
  85267. /**
  85268. * Gets a string describing the action executed by the current optimization
  85269. * @returns description string
  85270. */
  85271. SceneOptimization.prototype.getDescription = function () {
  85272. return "";
  85273. };
  85274. /**
  85275. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85276. * @param scene defines the current scene where to apply this optimization
  85277. * @param optimizer defines the current optimizer
  85278. * @returns true if everything that can be done was applied
  85279. */
  85280. SceneOptimization.prototype.apply = function (scene, optimizer) {
  85281. return true;
  85282. };
  85283. ;
  85284. return SceneOptimization;
  85285. }());
  85286. BABYLON.SceneOptimization = SceneOptimization;
  85287. /**
  85288. * Defines an optimization used to reduce the size of render target textures
  85289. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85290. */
  85291. var TextureOptimization = /** @class */ (function (_super) {
  85292. __extends(TextureOptimization, _super);
  85293. /**
  85294. * Creates the TextureOptimization object
  85295. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85296. * @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
  85297. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85298. */
  85299. function TextureOptimization(
  85300. /**
  85301. * Defines the priority of this optimization (0 by default which means first in the list)
  85302. */
  85303. priority,
  85304. /**
  85305. * 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
  85306. */
  85307. maximumSize,
  85308. /**
  85309. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85310. */
  85311. step) {
  85312. if (priority === void 0) { priority = 0; }
  85313. if (maximumSize === void 0) { maximumSize = 1024; }
  85314. if (step === void 0) { step = 0.5; }
  85315. var _this = _super.call(this, priority) || this;
  85316. _this.priority = priority;
  85317. _this.maximumSize = maximumSize;
  85318. _this.step = step;
  85319. return _this;
  85320. }
  85321. /**
  85322. * Gets a string describing the action executed by the current optimization
  85323. * @returns description string
  85324. */
  85325. TextureOptimization.prototype.getDescription = function () {
  85326. return "Reducing render target texture size to " + this.maximumSize;
  85327. };
  85328. /**
  85329. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85330. * @param scene defines the current scene where to apply this optimization
  85331. * @param optimizer defines the current optimizer
  85332. * @returns true if everything that can be done was applied
  85333. */
  85334. TextureOptimization.prototype.apply = function (scene, optimizer) {
  85335. var allDone = true;
  85336. for (var index = 0; index < scene.textures.length; index++) {
  85337. var texture = scene.textures[index];
  85338. if (!texture.canRescale || texture.getContext) {
  85339. continue;
  85340. }
  85341. var currentSize = texture.getSize();
  85342. var maxDimension = Math.max(currentSize.width, currentSize.height);
  85343. if (maxDimension > this.maximumSize) {
  85344. texture.scale(this.step);
  85345. allDone = false;
  85346. }
  85347. }
  85348. return allDone;
  85349. };
  85350. return TextureOptimization;
  85351. }(SceneOptimization));
  85352. BABYLON.TextureOptimization = TextureOptimization;
  85353. /**
  85354. * Defines an optimization used to increase or decrease the rendering resolution
  85355. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85356. */
  85357. var HardwareScalingOptimization = /** @class */ (function (_super) {
  85358. __extends(HardwareScalingOptimization, _super);
  85359. /**
  85360. * Creates the HardwareScalingOptimization object
  85361. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85362. * @param maximumScale defines the maximum scale to use (2 by default)
  85363. * @param step defines the step to use between two passes (0.5 by default)
  85364. */
  85365. function HardwareScalingOptimization(
  85366. /**
  85367. * Defines the priority of this optimization (0 by default which means first in the list)
  85368. */
  85369. priority,
  85370. /**
  85371. * Defines the maximum scale to use (2 by default)
  85372. */
  85373. maximumScale,
  85374. /**
  85375. * Defines the step to use between two passes (0.5 by default)
  85376. */
  85377. step) {
  85378. if (priority === void 0) { priority = 0; }
  85379. if (maximumScale === void 0) { maximumScale = 2; }
  85380. if (step === void 0) { step = 0.25; }
  85381. var _this = _super.call(this, priority) || this;
  85382. _this.priority = priority;
  85383. _this.maximumScale = maximumScale;
  85384. _this.step = step;
  85385. _this._currentScale = -1;
  85386. _this._directionOffset = 1;
  85387. return _this;
  85388. }
  85389. /**
  85390. * Gets a string describing the action executed by the current optimization
  85391. * @return description string
  85392. */
  85393. HardwareScalingOptimization.prototype.getDescription = function () {
  85394. return "Setting hardware scaling level to " + this._currentScale;
  85395. };
  85396. /**
  85397. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85398. * @param scene defines the current scene where to apply this optimization
  85399. * @param optimizer defines the current optimizer
  85400. * @returns true if everything that can be done was applied
  85401. */
  85402. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85403. if (this._currentScale === -1) {
  85404. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85405. if (this._currentScale > this.maximumScale) {
  85406. this._directionOffset = -1;
  85407. }
  85408. }
  85409. this._currentScale += this._directionOffset * this.step;
  85410. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85411. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85412. };
  85413. ;
  85414. return HardwareScalingOptimization;
  85415. }(SceneOptimization));
  85416. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85417. /**
  85418. * Defines an optimization used to remove shadows
  85419. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85420. */
  85421. var ShadowsOptimization = /** @class */ (function (_super) {
  85422. __extends(ShadowsOptimization, _super);
  85423. function ShadowsOptimization() {
  85424. return _super !== null && _super.apply(this, arguments) || this;
  85425. }
  85426. /**
  85427. * Gets a string describing the action executed by the current optimization
  85428. * @return description string
  85429. */
  85430. ShadowsOptimization.prototype.getDescription = function () {
  85431. return "Turning shadows on/off";
  85432. };
  85433. /**
  85434. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85435. * @param scene defines the current scene where to apply this optimization
  85436. * @param optimizer defines the current optimizer
  85437. * @returns true if everything that can be done was applied
  85438. */
  85439. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85440. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85441. return true;
  85442. };
  85443. ;
  85444. return ShadowsOptimization;
  85445. }(SceneOptimization));
  85446. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85447. /**
  85448. * Defines an optimization used to turn post-processes off
  85449. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85450. */
  85451. var PostProcessesOptimization = /** @class */ (function (_super) {
  85452. __extends(PostProcessesOptimization, _super);
  85453. function PostProcessesOptimization() {
  85454. return _super !== null && _super.apply(this, arguments) || this;
  85455. }
  85456. /**
  85457. * Gets a string describing the action executed by the current optimization
  85458. * @return description string
  85459. */
  85460. PostProcessesOptimization.prototype.getDescription = function () {
  85461. return "Turning post-processes on/off";
  85462. };
  85463. /**
  85464. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85465. * @param scene defines the current scene where to apply this optimization
  85466. * @param optimizer defines the current optimizer
  85467. * @returns true if everything that can be done was applied
  85468. */
  85469. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85470. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85471. return true;
  85472. };
  85473. ;
  85474. return PostProcessesOptimization;
  85475. }(SceneOptimization));
  85476. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85477. /**
  85478. * Defines an optimization used to turn lens flares off
  85479. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85480. */
  85481. var LensFlaresOptimization = /** @class */ (function (_super) {
  85482. __extends(LensFlaresOptimization, _super);
  85483. function LensFlaresOptimization() {
  85484. return _super !== null && _super.apply(this, arguments) || this;
  85485. }
  85486. /**
  85487. * Gets a string describing the action executed by the current optimization
  85488. * @return description string
  85489. */
  85490. LensFlaresOptimization.prototype.getDescription = function () {
  85491. return "Turning lens flares on/off";
  85492. };
  85493. /**
  85494. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85495. * @param scene defines the current scene where to apply this optimization
  85496. * @param optimizer defines the current optimizer
  85497. * @returns true if everything that can be done was applied
  85498. */
  85499. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85500. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85501. return true;
  85502. };
  85503. ;
  85504. return LensFlaresOptimization;
  85505. }(SceneOptimization));
  85506. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85507. /**
  85508. * Defines an optimization based on user defined callback.
  85509. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85510. */
  85511. var CustomOptimization = /** @class */ (function (_super) {
  85512. __extends(CustomOptimization, _super);
  85513. function CustomOptimization() {
  85514. return _super !== null && _super.apply(this, arguments) || this;
  85515. }
  85516. /**
  85517. * Gets a string describing the action executed by the current optimization
  85518. * @returns description string
  85519. */
  85520. CustomOptimization.prototype.getDescription = function () {
  85521. if (this.onGetDescription) {
  85522. return this.onGetDescription();
  85523. }
  85524. return "Running user defined callback";
  85525. };
  85526. /**
  85527. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85528. * @param scene defines the current scene where to apply this optimization
  85529. * @param optimizer defines the current optimizer
  85530. * @returns true if everything that can be done was applied
  85531. */
  85532. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85533. if (this.onApply) {
  85534. return this.onApply(scene, optimizer);
  85535. }
  85536. return true;
  85537. };
  85538. ;
  85539. return CustomOptimization;
  85540. }(SceneOptimization));
  85541. BABYLON.CustomOptimization = CustomOptimization;
  85542. /**
  85543. * Defines an optimization used to turn particles off
  85544. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85545. */
  85546. var ParticlesOptimization = /** @class */ (function (_super) {
  85547. __extends(ParticlesOptimization, _super);
  85548. function ParticlesOptimization() {
  85549. return _super !== null && _super.apply(this, arguments) || this;
  85550. }
  85551. /**
  85552. * Gets a string describing the action executed by the current optimization
  85553. * @return description string
  85554. */
  85555. ParticlesOptimization.prototype.getDescription = function () {
  85556. return "Turning particles on/off";
  85557. };
  85558. /**
  85559. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85560. * @param scene defines the current scene where to apply this optimization
  85561. * @param optimizer defines the current optimizer
  85562. * @returns true if everything that can be done was applied
  85563. */
  85564. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85565. scene.particlesEnabled = optimizer.isInImprovementMode;
  85566. return true;
  85567. };
  85568. ;
  85569. return ParticlesOptimization;
  85570. }(SceneOptimization));
  85571. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85572. /**
  85573. * Defines an optimization used to turn render targets off
  85574. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85575. */
  85576. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85577. __extends(RenderTargetsOptimization, _super);
  85578. function RenderTargetsOptimization() {
  85579. return _super !== null && _super.apply(this, arguments) || this;
  85580. }
  85581. /**
  85582. * Gets a string describing the action executed by the current optimization
  85583. * @return description string
  85584. */
  85585. RenderTargetsOptimization.prototype.getDescription = function () {
  85586. return "Turning render targets off";
  85587. };
  85588. /**
  85589. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85590. * @param scene defines the current scene where to apply this optimization
  85591. * @param optimizer defines the current optimizer
  85592. * @returns true if everything that can be done was applied
  85593. */
  85594. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85595. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85596. return true;
  85597. };
  85598. ;
  85599. return RenderTargetsOptimization;
  85600. }(SceneOptimization));
  85601. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85602. /**
  85603. * Defines an optimization used to merge meshes with compatible materials
  85604. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85605. */
  85606. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85607. __extends(MergeMeshesOptimization, _super);
  85608. function MergeMeshesOptimization() {
  85609. var _this = _super !== null && _super.apply(this, arguments) || this;
  85610. _this._canBeMerged = function (abstractMesh) {
  85611. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85612. return false;
  85613. }
  85614. var mesh = abstractMesh;
  85615. if (!mesh.isVisible || !mesh.isEnabled()) {
  85616. return false;
  85617. }
  85618. if (mesh.instances.length > 0) {
  85619. return false;
  85620. }
  85621. if (mesh.skeleton || mesh.hasLODLevels) {
  85622. return false;
  85623. }
  85624. if (mesh.parent) {
  85625. return false;
  85626. }
  85627. return true;
  85628. };
  85629. return _this;
  85630. }
  85631. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85632. /**
  85633. * Gets or sets a boolean which defines if optimization octree has to be updated
  85634. */
  85635. get: function () {
  85636. return MergeMeshesOptimization._UpdateSelectionTree;
  85637. },
  85638. /**
  85639. * Gets or sets a boolean which defines if optimization octree has to be updated
  85640. */
  85641. set: function (value) {
  85642. MergeMeshesOptimization._UpdateSelectionTree = value;
  85643. },
  85644. enumerable: true,
  85645. configurable: true
  85646. });
  85647. /**
  85648. * Gets a string describing the action executed by the current optimization
  85649. * @return description string
  85650. */
  85651. MergeMeshesOptimization.prototype.getDescription = function () {
  85652. return "Merging similar meshes together";
  85653. };
  85654. /**
  85655. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85656. * @param scene defines the current scene where to apply this optimization
  85657. * @param optimizer defines the current optimizer
  85658. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85659. * @returns true if everything that can be done was applied
  85660. */
  85661. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85662. var globalPool = scene.meshes.slice(0);
  85663. var globalLength = globalPool.length;
  85664. for (var index = 0; index < globalLength; index++) {
  85665. var currentPool = new Array();
  85666. var current = globalPool[index];
  85667. // Checks
  85668. if (!this._canBeMerged(current)) {
  85669. continue;
  85670. }
  85671. currentPool.push(current);
  85672. // Find compatible meshes
  85673. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85674. var otherMesh = globalPool[subIndex];
  85675. if (!this._canBeMerged(otherMesh)) {
  85676. continue;
  85677. }
  85678. if (otherMesh.material !== current.material) {
  85679. continue;
  85680. }
  85681. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85682. continue;
  85683. }
  85684. currentPool.push(otherMesh);
  85685. globalLength--;
  85686. globalPool.splice(subIndex, 1);
  85687. subIndex--;
  85688. }
  85689. if (currentPool.length < 2) {
  85690. continue;
  85691. }
  85692. // Merge meshes
  85693. BABYLON.Mesh.MergeMeshes(currentPool);
  85694. }
  85695. if (updateSelectionTree != undefined) {
  85696. if (updateSelectionTree) {
  85697. scene.createOrUpdateSelectionOctree();
  85698. }
  85699. }
  85700. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85701. scene.createOrUpdateSelectionOctree();
  85702. }
  85703. return true;
  85704. };
  85705. ;
  85706. MergeMeshesOptimization._UpdateSelectionTree = false;
  85707. return MergeMeshesOptimization;
  85708. }(SceneOptimization));
  85709. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85710. /**
  85711. * Defines a list of options used by SceneOptimizer
  85712. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85713. */
  85714. var SceneOptimizerOptions = /** @class */ (function () {
  85715. /**
  85716. * Creates a new list of options used by SceneOptimizer
  85717. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85718. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85719. */
  85720. function SceneOptimizerOptions(
  85721. /**
  85722. * Defines the target frame rate to reach (60 by default)
  85723. */
  85724. targetFrameRate,
  85725. /**
  85726. * Defines the interval between two checkes (2000ms by default)
  85727. */
  85728. trackerDuration) {
  85729. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85730. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85731. this.targetFrameRate = targetFrameRate;
  85732. this.trackerDuration = trackerDuration;
  85733. /**
  85734. * Gets the list of optimizations to apply
  85735. */
  85736. this.optimizations = new Array();
  85737. }
  85738. /**
  85739. * Add a new optimization
  85740. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85741. * @returns the current SceneOptimizerOptions
  85742. */
  85743. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85744. this.optimizations.push(optimization);
  85745. return this;
  85746. };
  85747. /**
  85748. * Add a new custom optimization
  85749. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85750. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85751. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85752. * @returns the current SceneOptimizerOptions
  85753. */
  85754. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85755. if (priority === void 0) { priority = 0; }
  85756. var optimization = new CustomOptimization(priority);
  85757. optimization.onApply = onApply;
  85758. optimization.onGetDescription = onGetDescription;
  85759. this.optimizations.push(optimization);
  85760. return this;
  85761. };
  85762. /**
  85763. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85764. * @param targetFrameRate defines the target frame rate (60 by default)
  85765. * @returns a SceneOptimizerOptions object
  85766. */
  85767. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85768. var result = new SceneOptimizerOptions(targetFrameRate);
  85769. var priority = 0;
  85770. result.addOptimization(new MergeMeshesOptimization(priority));
  85771. result.addOptimization(new ShadowsOptimization(priority));
  85772. result.addOptimization(new LensFlaresOptimization(priority));
  85773. // Next priority
  85774. priority++;
  85775. result.addOptimization(new PostProcessesOptimization(priority));
  85776. result.addOptimization(new ParticlesOptimization(priority));
  85777. // Next priority
  85778. priority++;
  85779. result.addOptimization(new TextureOptimization(priority, 1024));
  85780. return result;
  85781. };
  85782. /**
  85783. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85784. * @param targetFrameRate defines the target frame rate (60 by default)
  85785. * @returns a SceneOptimizerOptions object
  85786. */
  85787. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85788. var result = new SceneOptimizerOptions(targetFrameRate);
  85789. var priority = 0;
  85790. result.addOptimization(new MergeMeshesOptimization(priority));
  85791. result.addOptimization(new ShadowsOptimization(priority));
  85792. result.addOptimization(new LensFlaresOptimization(priority));
  85793. // Next priority
  85794. priority++;
  85795. result.addOptimization(new PostProcessesOptimization(priority));
  85796. result.addOptimization(new ParticlesOptimization(priority));
  85797. // Next priority
  85798. priority++;
  85799. result.addOptimization(new TextureOptimization(priority, 512));
  85800. // Next priority
  85801. priority++;
  85802. result.addOptimization(new RenderTargetsOptimization(priority));
  85803. // Next priority
  85804. priority++;
  85805. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85806. return result;
  85807. };
  85808. /**
  85809. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85810. * @param targetFrameRate defines the target frame rate (60 by default)
  85811. * @returns a SceneOptimizerOptions object
  85812. */
  85813. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85814. var result = new SceneOptimizerOptions(targetFrameRate);
  85815. var priority = 0;
  85816. result.addOptimization(new MergeMeshesOptimization(priority));
  85817. result.addOptimization(new ShadowsOptimization(priority));
  85818. result.addOptimization(new LensFlaresOptimization(priority));
  85819. // Next priority
  85820. priority++;
  85821. result.addOptimization(new PostProcessesOptimization(priority));
  85822. result.addOptimization(new ParticlesOptimization(priority));
  85823. // Next priority
  85824. priority++;
  85825. result.addOptimization(new TextureOptimization(priority, 256));
  85826. // Next priority
  85827. priority++;
  85828. result.addOptimization(new RenderTargetsOptimization(priority));
  85829. // Next priority
  85830. priority++;
  85831. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85832. return result;
  85833. };
  85834. return SceneOptimizerOptions;
  85835. }());
  85836. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  85837. /**
  85838. * Class used to run optimizations in order to reach a target frame rate
  85839. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85840. */
  85841. var SceneOptimizer = /** @class */ (function () {
  85842. /**
  85843. * Creates a new SceneOptimizer
  85844. * @param scene defines the scene to work on
  85845. * @param options defines the options to use with the SceneOptimizer
  85846. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  85847. * @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)
  85848. */
  85849. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  85850. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  85851. if (improvementMode === void 0) { improvementMode = false; }
  85852. var _this = this;
  85853. this._isRunning = false;
  85854. this._currentPriorityLevel = 0;
  85855. this._targetFrameRate = 60;
  85856. this._trackerDuration = 2000;
  85857. this._currentFrameRate = 0;
  85858. this._improvementMode = false;
  85859. /**
  85860. * Defines an observable called when the optimizer reaches the target frame rate
  85861. */
  85862. this.onSuccessObservable = new BABYLON.Observable();
  85863. /**
  85864. * Defines an observable called when the optimizer enables an optimization
  85865. */
  85866. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  85867. /**
  85868. * Defines an observable called when the optimizer is not able to reach the target frame rate
  85869. */
  85870. this.onFailureObservable = new BABYLON.Observable();
  85871. if (!options) {
  85872. this._options = new SceneOptimizerOptions();
  85873. }
  85874. else {
  85875. this._options = options;
  85876. }
  85877. if (this._options.targetFrameRate) {
  85878. this._targetFrameRate = this._options.targetFrameRate;
  85879. }
  85880. if (this._options.trackerDuration) {
  85881. this._trackerDuration = this._options.trackerDuration;
  85882. }
  85883. if (autoGeneratePriorities) {
  85884. var priority = 0;
  85885. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  85886. var optim = _a[_i];
  85887. optim.priority = priority++;
  85888. }
  85889. }
  85890. this._improvementMode = improvementMode;
  85891. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85892. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  85893. _this._sceneDisposeObserver = null;
  85894. _this.dispose();
  85895. });
  85896. }
  85897. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  85898. /**
  85899. * Gets a boolean indicating if the optimizer is in improvement mode
  85900. */
  85901. get: function () {
  85902. return this._improvementMode;
  85903. },
  85904. enumerable: true,
  85905. configurable: true
  85906. });
  85907. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  85908. /**
  85909. * Gets the current priority level (0 at start)
  85910. */
  85911. get: function () {
  85912. return this._currentPriorityLevel;
  85913. },
  85914. enumerable: true,
  85915. configurable: true
  85916. });
  85917. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  85918. /**
  85919. * Gets the current frame rate checked by the SceneOptimizer
  85920. */
  85921. get: function () {
  85922. return this._currentFrameRate;
  85923. },
  85924. enumerable: true,
  85925. configurable: true
  85926. });
  85927. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  85928. /**
  85929. * Gets or sets the current target frame rate (60 by default)
  85930. */
  85931. get: function () {
  85932. return this._targetFrameRate;
  85933. },
  85934. /**
  85935. * Gets or sets the current target frame rate (60 by default)
  85936. */
  85937. set: function (value) {
  85938. this._targetFrameRate = value;
  85939. },
  85940. enumerable: true,
  85941. configurable: true
  85942. });
  85943. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  85944. /**
  85945. * Gets or sets the current interval between two checks (every 2000ms by default)
  85946. */
  85947. get: function () {
  85948. return this._trackerDuration;
  85949. },
  85950. /**
  85951. * Gets or sets the current interval between two checks (every 2000ms by default)
  85952. */
  85953. set: function (value) {
  85954. this._trackerDuration = value;
  85955. },
  85956. enumerable: true,
  85957. configurable: true
  85958. });
  85959. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  85960. /**
  85961. * Gets the list of active optimizations
  85962. */
  85963. get: function () {
  85964. return this._options.optimizations;
  85965. },
  85966. enumerable: true,
  85967. configurable: true
  85968. });
  85969. /**
  85970. * Stops the current optimizer
  85971. */
  85972. SceneOptimizer.prototype.stop = function () {
  85973. this._isRunning = false;
  85974. };
  85975. /**
  85976. * Reset the optimizer to initial step (current priority level = 0)
  85977. */
  85978. SceneOptimizer.prototype.reset = function () {
  85979. this._currentPriorityLevel = 0;
  85980. };
  85981. /**
  85982. * Start the optimizer. By default it will try to reach a specific framerate
  85983. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  85984. */
  85985. SceneOptimizer.prototype.start = function () {
  85986. var _this = this;
  85987. if (this._isRunning) {
  85988. return;
  85989. }
  85990. this._isRunning = true;
  85991. // Let's wait for the scene to be ready before running our check
  85992. this._scene.executeWhenReady(function () {
  85993. setTimeout(function () {
  85994. _this._checkCurrentState();
  85995. }, _this._trackerDuration);
  85996. });
  85997. };
  85998. SceneOptimizer.prototype._checkCurrentState = function () {
  85999. var _this = this;
  86000. if (!this._isRunning) {
  86001. return;
  86002. }
  86003. var scene = this._scene;
  86004. var options = this._options;
  86005. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  86006. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  86007. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  86008. this._isRunning = false;
  86009. this.onSuccessObservable.notifyObservers(this);
  86010. return;
  86011. }
  86012. // Apply current level of optimizations
  86013. var allDone = true;
  86014. var noOptimizationApplied = true;
  86015. for (var index = 0; index < options.optimizations.length; index++) {
  86016. var optimization = options.optimizations[index];
  86017. if (optimization.priority === this._currentPriorityLevel) {
  86018. noOptimizationApplied = false;
  86019. allDone = allDone && optimization.apply(scene, this);
  86020. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  86021. }
  86022. }
  86023. // If no optimization was applied, this is a failure :(
  86024. if (noOptimizationApplied) {
  86025. this._isRunning = false;
  86026. this.onFailureObservable.notifyObservers(this);
  86027. return;
  86028. }
  86029. // If all optimizations were done, move to next level
  86030. if (allDone) {
  86031. this._currentPriorityLevel++;
  86032. }
  86033. // Let's the system running for a specific amount of time before checking FPS
  86034. scene.executeWhenReady(function () {
  86035. setTimeout(function () {
  86036. _this._checkCurrentState();
  86037. }, _this._trackerDuration);
  86038. });
  86039. };
  86040. /**
  86041. * Release all resources
  86042. */
  86043. SceneOptimizer.prototype.dispose = function () {
  86044. this.stop();
  86045. this.onSuccessObservable.clear();
  86046. this.onFailureObservable.clear();
  86047. this.onNewOptimizationAppliedObservable.clear();
  86048. if (this._sceneDisposeObserver) {
  86049. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86050. }
  86051. };
  86052. /**
  86053. * Helper function to create a SceneOptimizer with one single line of code
  86054. * @param scene defines the scene to work on
  86055. * @param options defines the options to use with the SceneOptimizer
  86056. * @param onSuccess defines a callback to call on success
  86057. * @param onFailure defines a callback to call on failure
  86058. * @returns the new SceneOptimizer object
  86059. */
  86060. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  86061. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  86062. if (onSuccess) {
  86063. optimizer.onSuccessObservable.add(function () {
  86064. onSuccess();
  86065. });
  86066. }
  86067. if (onFailure) {
  86068. optimizer.onFailureObservable.add(function () {
  86069. onFailure();
  86070. });
  86071. }
  86072. optimizer.start();
  86073. return optimizer;
  86074. };
  86075. return SceneOptimizer;
  86076. }());
  86077. BABYLON.SceneOptimizer = SceneOptimizer;
  86078. })(BABYLON || (BABYLON = {}));
  86079. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  86080. "use strict";
  86081. var BABYLON;
  86082. (function (BABYLON) {
  86083. var OutlineRenderer = /** @class */ (function () {
  86084. function OutlineRenderer(scene) {
  86085. this.zOffset = 1;
  86086. this._scene = scene;
  86087. }
  86088. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  86089. var _this = this;
  86090. if (useOverlay === void 0) { useOverlay = false; }
  86091. var scene = this._scene;
  86092. var engine = this._scene.getEngine();
  86093. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86094. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  86095. return;
  86096. }
  86097. var mesh = subMesh.getRenderingMesh();
  86098. var material = subMesh.getMaterial();
  86099. if (!material || !scene.activeCamera) {
  86100. return;
  86101. }
  86102. engine.enableEffect(this._effect);
  86103. // Logarithmic depth
  86104. if (material.useLogarithmicDepth) {
  86105. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  86106. }
  86107. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  86108. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  86109. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  86110. // Bones
  86111. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86112. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86113. }
  86114. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  86115. // Alpha test
  86116. if (material && material.needAlphaTesting()) {
  86117. var alphaTexture = material.getAlphaTestTexture();
  86118. if (alphaTexture) {
  86119. this._effect.setTexture("diffuseSampler", alphaTexture);
  86120. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86121. }
  86122. }
  86123. engine.setZOffset(-this.zOffset);
  86124. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  86125. engine.setZOffset(0);
  86126. };
  86127. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  86128. var defines = [];
  86129. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  86130. var mesh = subMesh.getMesh();
  86131. var material = subMesh.getMaterial();
  86132. if (material) {
  86133. // Alpha test
  86134. if (material.needAlphaTesting()) {
  86135. defines.push("#define ALPHATEST");
  86136. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86137. attribs.push(BABYLON.VertexBuffer.UVKind);
  86138. defines.push("#define UV1");
  86139. }
  86140. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  86141. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86142. defines.push("#define UV2");
  86143. }
  86144. }
  86145. //Logarithmic depth
  86146. if (material.useLogarithmicDepth) {
  86147. defines.push("#define LOGARITHMICDEPTH");
  86148. }
  86149. }
  86150. // Bones
  86151. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86152. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86153. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86154. if (mesh.numBoneInfluencers > 4) {
  86155. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86156. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86157. }
  86158. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86159. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  86160. }
  86161. else {
  86162. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86163. }
  86164. // Instances
  86165. if (useInstances) {
  86166. defines.push("#define INSTANCES");
  86167. attribs.push("world0");
  86168. attribs.push("world1");
  86169. attribs.push("world2");
  86170. attribs.push("world3");
  86171. }
  86172. // Get correct effect
  86173. var join = defines.join("\n");
  86174. if (this._cachedDefines !== join) {
  86175. this._cachedDefines = join;
  86176. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  86177. }
  86178. return this._effect.isReady();
  86179. };
  86180. return OutlineRenderer;
  86181. }());
  86182. BABYLON.OutlineRenderer = OutlineRenderer;
  86183. })(BABYLON || (BABYLON = {}));
  86184. //# sourceMappingURL=babylon.outlineRenderer.js.map
  86185. "use strict";
  86186. var BABYLON;
  86187. (function (BABYLON) {
  86188. var FaceAdjacencies = /** @class */ (function () {
  86189. function FaceAdjacencies() {
  86190. this.edges = new Array();
  86191. this.edgesConnectedCount = 0;
  86192. }
  86193. return FaceAdjacencies;
  86194. }());
  86195. var EdgesRenderer = /** @class */ (function () {
  86196. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  86197. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  86198. if (epsilon === void 0) { epsilon = 0.95; }
  86199. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  86200. this.edgesWidthScalerForOrthographic = 1000.0;
  86201. this.edgesWidthScalerForPerspective = 50.0;
  86202. this._linesPositions = new Array();
  86203. this._linesNormals = new Array();
  86204. this._linesIndices = new Array();
  86205. this._buffers = {};
  86206. this._checkVerticesInsteadOfIndices = false;
  86207. this._source = source;
  86208. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  86209. this._epsilon = epsilon;
  86210. this._prepareRessources();
  86211. this._generateEdgesLines();
  86212. }
  86213. EdgesRenderer.prototype._prepareRessources = function () {
  86214. if (this._lineShader) {
  86215. return;
  86216. }
  86217. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  86218. attributes: ["position", "normal"],
  86219. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  86220. });
  86221. this._lineShader.disableDepthWrite = true;
  86222. this._lineShader.backFaceCulling = false;
  86223. };
  86224. EdgesRenderer.prototype._rebuild = function () {
  86225. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86226. if (buffer) {
  86227. buffer._rebuild();
  86228. }
  86229. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86230. if (buffer) {
  86231. buffer._rebuild();
  86232. }
  86233. var scene = this._source.getScene();
  86234. var engine = scene.getEngine();
  86235. this._ib = engine.createIndexBuffer(this._linesIndices);
  86236. };
  86237. EdgesRenderer.prototype.dispose = function () {
  86238. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86239. if (buffer) {
  86240. buffer.dispose();
  86241. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  86242. }
  86243. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86244. if (buffer) {
  86245. buffer.dispose();
  86246. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  86247. }
  86248. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  86249. this._lineShader.dispose();
  86250. };
  86251. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  86252. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  86253. return 0;
  86254. }
  86255. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  86256. return 1;
  86257. }
  86258. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  86259. return 2;
  86260. }
  86261. return -1;
  86262. };
  86263. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  86264. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  86265. return 0;
  86266. }
  86267. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  86268. return 1;
  86269. }
  86270. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  86271. return 2;
  86272. }
  86273. return -1;
  86274. };
  86275. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  86276. var needToCreateLine;
  86277. if (edge === undefined) {
  86278. needToCreateLine = true;
  86279. }
  86280. else {
  86281. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  86282. needToCreateLine = dotProduct < this._epsilon;
  86283. }
  86284. if (needToCreateLine) {
  86285. var offset = this._linesPositions.length / 3;
  86286. var normal = p0.subtract(p1);
  86287. normal.normalize();
  86288. // Positions
  86289. this._linesPositions.push(p0.x);
  86290. this._linesPositions.push(p0.y);
  86291. this._linesPositions.push(p0.z);
  86292. this._linesPositions.push(p0.x);
  86293. this._linesPositions.push(p0.y);
  86294. this._linesPositions.push(p0.z);
  86295. this._linesPositions.push(p1.x);
  86296. this._linesPositions.push(p1.y);
  86297. this._linesPositions.push(p1.z);
  86298. this._linesPositions.push(p1.x);
  86299. this._linesPositions.push(p1.y);
  86300. this._linesPositions.push(p1.z);
  86301. // Normals
  86302. this._linesNormals.push(p1.x);
  86303. this._linesNormals.push(p1.y);
  86304. this._linesNormals.push(p1.z);
  86305. this._linesNormals.push(-1);
  86306. this._linesNormals.push(p1.x);
  86307. this._linesNormals.push(p1.y);
  86308. this._linesNormals.push(p1.z);
  86309. this._linesNormals.push(1);
  86310. this._linesNormals.push(p0.x);
  86311. this._linesNormals.push(p0.y);
  86312. this._linesNormals.push(p0.z);
  86313. this._linesNormals.push(-1);
  86314. this._linesNormals.push(p0.x);
  86315. this._linesNormals.push(p0.y);
  86316. this._linesNormals.push(p0.z);
  86317. this._linesNormals.push(1);
  86318. // Indices
  86319. this._linesIndices.push(offset);
  86320. this._linesIndices.push(offset + 1);
  86321. this._linesIndices.push(offset + 2);
  86322. this._linesIndices.push(offset);
  86323. this._linesIndices.push(offset + 2);
  86324. this._linesIndices.push(offset + 3);
  86325. }
  86326. };
  86327. EdgesRenderer.prototype._generateEdgesLines = function () {
  86328. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86329. var indices = this._source.getIndices();
  86330. if (!indices || !positions) {
  86331. return;
  86332. }
  86333. // First let's find adjacencies
  86334. var adjacencies = new Array();
  86335. var faceNormals = new Array();
  86336. var index;
  86337. var faceAdjacencies;
  86338. // Prepare faces
  86339. for (index = 0; index < indices.length; index += 3) {
  86340. faceAdjacencies = new FaceAdjacencies();
  86341. var p0Index = indices[index];
  86342. var p1Index = indices[index + 1];
  86343. var p2Index = indices[index + 2];
  86344. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  86345. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  86346. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  86347. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  86348. faceNormal.normalize();
  86349. faceNormals.push(faceNormal);
  86350. adjacencies.push(faceAdjacencies);
  86351. }
  86352. // Scan
  86353. for (index = 0; index < adjacencies.length; index++) {
  86354. faceAdjacencies = adjacencies[index];
  86355. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  86356. var otherFaceAdjacencies = adjacencies[otherIndex];
  86357. if (faceAdjacencies.edgesConnectedCount === 3) {
  86358. break;
  86359. }
  86360. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  86361. continue;
  86362. }
  86363. var otherP0 = indices[otherIndex * 3];
  86364. var otherP1 = indices[otherIndex * 3 + 1];
  86365. var otherP2 = indices[otherIndex * 3 + 2];
  86366. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  86367. var otherEdgeIndex = 0;
  86368. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  86369. continue;
  86370. }
  86371. switch (edgeIndex) {
  86372. case 0:
  86373. if (this._checkVerticesInsteadOfIndices) {
  86374. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86375. }
  86376. else {
  86377. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86378. }
  86379. break;
  86380. case 1:
  86381. if (this._checkVerticesInsteadOfIndices) {
  86382. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86383. }
  86384. else {
  86385. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86386. }
  86387. break;
  86388. case 2:
  86389. if (this._checkVerticesInsteadOfIndices) {
  86390. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86391. }
  86392. else {
  86393. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86394. }
  86395. break;
  86396. }
  86397. if (otherEdgeIndex === -1) {
  86398. continue;
  86399. }
  86400. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86401. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86402. faceAdjacencies.edgesConnectedCount++;
  86403. otherFaceAdjacencies.edgesConnectedCount++;
  86404. if (faceAdjacencies.edgesConnectedCount === 3) {
  86405. break;
  86406. }
  86407. }
  86408. }
  86409. }
  86410. // Create lines
  86411. for (index = 0; index < adjacencies.length; index++) {
  86412. // 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
  86413. var current = adjacencies[index];
  86414. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86415. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86416. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86417. }
  86418. // Merge into a single mesh
  86419. var engine = this._source.getScene().getEngine();
  86420. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86421. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86422. this._ib = engine.createIndexBuffer(this._linesIndices);
  86423. this._indicesCount = this._linesIndices.length;
  86424. };
  86425. EdgesRenderer.prototype.render = function () {
  86426. var scene = this._source.getScene();
  86427. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86428. return;
  86429. }
  86430. var engine = scene.getEngine();
  86431. this._lineShader._preBind();
  86432. // VBOs
  86433. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86434. scene.resetCachedMaterial();
  86435. this._lineShader.setColor4("color", this._source.edgesColor);
  86436. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86437. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86438. }
  86439. else {
  86440. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86441. }
  86442. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86443. this._lineShader.bind(this._source.getWorldMatrix());
  86444. // Draw order
  86445. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86446. this._lineShader.unbind();
  86447. engine.setDepthWrite(true);
  86448. };
  86449. return EdgesRenderer;
  86450. }());
  86451. BABYLON.EdgesRenderer = EdgesRenderer;
  86452. })(BABYLON || (BABYLON = {}));
  86453. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86454. "use strict";
  86455. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86456. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86457. s = arguments[i];
  86458. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86459. t[p] = s[p];
  86460. }
  86461. return t;
  86462. };
  86463. var BABYLON;
  86464. (function (BABYLON) {
  86465. /**
  86466. * The effect layer Helps adding post process effect blended with the main pass.
  86467. *
  86468. * This can be for instance use to generate glow or higlight effects on the scene.
  86469. *
  86470. * The effect layer class can not be used directly and is intented to inherited from to be
  86471. * customized per effects.
  86472. */
  86473. var EffectLayer = /** @class */ (function () {
  86474. /**
  86475. * Instantiates a new effect Layer and references it in the scene.
  86476. * @param name The name of the layer
  86477. * @param scene The scene to use the layer in
  86478. */
  86479. function EffectLayer(
  86480. /** The Friendly of the effect in the scene */
  86481. name, scene) {
  86482. this.name = name;
  86483. this._vertexBuffers = {};
  86484. this._maxSize = 0;
  86485. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86486. this._shouldRender = true;
  86487. this._postProcesses = [];
  86488. this._textures = [];
  86489. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86490. /**
  86491. * The clear color of the texture used to generate the glow map.
  86492. */
  86493. this.neutralColor = new BABYLON.Color4();
  86494. /**
  86495. * Specifies wether the highlight layer is enabled or not.
  86496. */
  86497. this.isEnabled = true;
  86498. /**
  86499. * An event triggered when the effect layer has been disposed.
  86500. */
  86501. this.onDisposeObservable = new BABYLON.Observable();
  86502. /**
  86503. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86504. */
  86505. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86506. /**
  86507. * An event triggered when the generated texture is being merged in the scene.
  86508. */
  86509. this.onBeforeComposeObservable = new BABYLON.Observable();
  86510. /**
  86511. * An event triggered when the generated texture has been merged in the scene.
  86512. */
  86513. this.onAfterComposeObservable = new BABYLON.Observable();
  86514. /**
  86515. * An event triggered when the efffect layer changes its size.
  86516. */
  86517. this.onSizeChangedObservable = new BABYLON.Observable();
  86518. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86519. this._engine = scene.getEngine();
  86520. this._maxSize = this._engine.getCaps().maxTextureSize;
  86521. this._scene.effectLayers.push(this);
  86522. // Generate Buffers
  86523. this._generateIndexBuffer();
  86524. this._genrateVertexBuffer();
  86525. }
  86526. Object.defineProperty(EffectLayer.prototype, "camera", {
  86527. /**
  86528. * Gets the camera attached to the layer.
  86529. */
  86530. get: function () {
  86531. return this._effectLayerOptions.camera;
  86532. },
  86533. enumerable: true,
  86534. configurable: true
  86535. });
  86536. /**
  86537. * Initializes the effect layer with the required options.
  86538. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86539. */
  86540. EffectLayer.prototype._init = function (options) {
  86541. // Adapt options
  86542. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86543. this._setMainTextureSize();
  86544. this._createMainTexture();
  86545. this._createTextureAndPostProcesses();
  86546. this._mergeEffect = this._createMergeEffect();
  86547. };
  86548. /**
  86549. * Generates the index buffer of the full screen quad blending to the main canvas.
  86550. */
  86551. EffectLayer.prototype._generateIndexBuffer = function () {
  86552. // Indices
  86553. var indices = [];
  86554. indices.push(0);
  86555. indices.push(1);
  86556. indices.push(2);
  86557. indices.push(0);
  86558. indices.push(2);
  86559. indices.push(3);
  86560. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86561. };
  86562. /**
  86563. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86564. */
  86565. EffectLayer.prototype._genrateVertexBuffer = function () {
  86566. // VBO
  86567. var vertices = [];
  86568. vertices.push(1, 1);
  86569. vertices.push(-1, 1);
  86570. vertices.push(-1, -1);
  86571. vertices.push(1, -1);
  86572. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86573. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86574. };
  86575. /**
  86576. * Sets the main texture desired size which is the closest power of two
  86577. * of the engine canvas size.
  86578. */
  86579. EffectLayer.prototype._setMainTextureSize = function () {
  86580. if (this._effectLayerOptions.mainTextureFixedSize) {
  86581. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86582. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86583. }
  86584. else {
  86585. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86586. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86587. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86588. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86589. }
  86590. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86591. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86592. };
  86593. /**
  86594. * Creates the main texture for the effect layer.
  86595. */
  86596. EffectLayer.prototype._createMainTexture = function () {
  86597. var _this = this;
  86598. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86599. width: this._mainTextureDesiredSize.width,
  86600. height: this._mainTextureDesiredSize.height
  86601. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86602. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86603. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86604. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86605. this._mainTexture.anisotropicFilteringLevel = 1;
  86606. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86607. this._mainTexture.renderParticles = false;
  86608. this._mainTexture.renderList = null;
  86609. this._mainTexture.ignoreCameraViewport = true;
  86610. // Custom render function
  86611. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86612. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86613. var index;
  86614. var engine = _this._scene.getEngine();
  86615. if (depthOnlySubMeshes.length) {
  86616. engine.setColorWrite(false);
  86617. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86618. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86619. }
  86620. engine.setColorWrite(true);
  86621. }
  86622. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86623. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86624. }
  86625. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86626. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86627. }
  86628. for (index = 0; index < transparentSubMeshes.length; index++) {
  86629. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86630. }
  86631. };
  86632. this._mainTexture.onClearObservable.add(function (engine) {
  86633. engine.clear(_this.neutralColor, true, true, true);
  86634. });
  86635. };
  86636. /**
  86637. * Checks for the readiness of the element composing the layer.
  86638. * @param subMesh the mesh to check for
  86639. * @param useInstances specify wether or not to use instances to render the mesh
  86640. * @param emissiveTexture the associated emissive texture used to generate the glow
  86641. * @return true if ready otherwise, false
  86642. */
  86643. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86644. var material = subMesh.getMaterial();
  86645. if (!material) {
  86646. return false;
  86647. }
  86648. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86649. return false;
  86650. }
  86651. var defines = [];
  86652. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86653. var mesh = subMesh.getMesh();
  86654. var uv1 = false;
  86655. var uv2 = false;
  86656. // Alpha test
  86657. if (material && material.needAlphaTesting()) {
  86658. var alphaTexture = material.getAlphaTestTexture();
  86659. if (alphaTexture) {
  86660. defines.push("#define ALPHATEST");
  86661. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86662. alphaTexture.coordinatesIndex === 1) {
  86663. defines.push("#define DIFFUSEUV2");
  86664. uv2 = true;
  86665. }
  86666. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86667. defines.push("#define DIFFUSEUV1");
  86668. uv1 = true;
  86669. }
  86670. }
  86671. }
  86672. // Emissive
  86673. if (emissiveTexture) {
  86674. defines.push("#define EMISSIVE");
  86675. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86676. emissiveTexture.coordinatesIndex === 1) {
  86677. defines.push("#define EMISSIVEUV2");
  86678. uv2 = true;
  86679. }
  86680. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86681. defines.push("#define EMISSIVEUV1");
  86682. uv1 = true;
  86683. }
  86684. }
  86685. if (uv1) {
  86686. attribs.push(BABYLON.VertexBuffer.UVKind);
  86687. defines.push("#define UV1");
  86688. }
  86689. if (uv2) {
  86690. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86691. defines.push("#define UV2");
  86692. }
  86693. // Bones
  86694. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86695. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86696. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86697. if (mesh.numBoneInfluencers > 4) {
  86698. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86699. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86700. }
  86701. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86702. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86703. }
  86704. else {
  86705. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86706. }
  86707. // Morph targets
  86708. var manager = mesh.morphTargetManager;
  86709. var morphInfluencers = 0;
  86710. if (manager) {
  86711. if (manager.numInfluencers > 0) {
  86712. defines.push("#define MORPHTARGETS");
  86713. morphInfluencers = manager.numInfluencers;
  86714. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  86715. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  86716. }
  86717. }
  86718. // Instances
  86719. if (useInstances) {
  86720. defines.push("#define INSTANCES");
  86721. attribs.push("world0");
  86722. attribs.push("world1");
  86723. attribs.push("world2");
  86724. attribs.push("world3");
  86725. }
  86726. // Get correct effect
  86727. var join = defines.join("\n");
  86728. if (this._cachedDefines !== join) {
  86729. this._cachedDefines = join;
  86730. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  86731. }
  86732. return this._effectLayerMapGenerationEffect.isReady();
  86733. };
  86734. /**
  86735. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86736. */
  86737. EffectLayer.prototype.render = function () {
  86738. var currentEffect = this._mergeEffect;
  86739. // Check
  86740. if (!currentEffect.isReady())
  86741. return;
  86742. for (var i = 0; i < this._postProcesses.length; i++) {
  86743. if (!this._postProcesses[i].isReady()) {
  86744. return;
  86745. }
  86746. }
  86747. var engine = this._scene.getEngine();
  86748. this.onBeforeComposeObservable.notifyObservers(this);
  86749. // Render
  86750. engine.enableEffect(currentEffect);
  86751. engine.setState(false);
  86752. // VBOs
  86753. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86754. // Cache
  86755. var previousAlphaMode = engine.getAlphaMode();
  86756. // Go Blend.
  86757. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86758. // Blends the map on the main canvas.
  86759. this._internalRender(currentEffect);
  86760. // Restore Alpha
  86761. engine.setAlphaMode(previousAlphaMode);
  86762. this.onAfterComposeObservable.notifyObservers(this);
  86763. // Handle size changes.
  86764. var size = this._mainTexture.getSize();
  86765. this._setMainTextureSize();
  86766. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86767. // Recreate RTT and post processes on size change.
  86768. this.onSizeChangedObservable.notifyObservers(this);
  86769. this._disposeTextureAndPostProcesses();
  86770. this._createMainTexture();
  86771. this._createTextureAndPostProcesses();
  86772. }
  86773. };
  86774. /**
  86775. * Determine if a given mesh will be used in the current effect.
  86776. * @param mesh mesh to test
  86777. * @returns true if the mesh will be used
  86778. */
  86779. EffectLayer.prototype.hasMesh = function (mesh) {
  86780. return true;
  86781. };
  86782. /**
  86783. * Returns true if the layer contains information to display, otherwise false.
  86784. * @returns true if the glow layer should be rendered
  86785. */
  86786. EffectLayer.prototype.shouldRender = function () {
  86787. return this.isEnabled && this._shouldRender;
  86788. };
  86789. /**
  86790. * Returns true if the mesh should render, otherwise false.
  86791. * @param mesh The mesh to render
  86792. * @returns true if it should render otherwise false
  86793. */
  86794. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86795. return true;
  86796. };
  86797. /**
  86798. * Returns true if the mesh should render, otherwise false.
  86799. * @param mesh The mesh to render
  86800. * @returns true if it should render otherwise false
  86801. */
  86802. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86803. return true;
  86804. };
  86805. /**
  86806. * Renders the submesh passed in parameter to the generation map.
  86807. */
  86808. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86809. var _this = this;
  86810. if (!this.shouldRender()) {
  86811. return;
  86812. }
  86813. var material = subMesh.getMaterial();
  86814. var mesh = subMesh.getRenderingMesh();
  86815. var scene = this._scene;
  86816. var engine = scene.getEngine();
  86817. if (!material) {
  86818. return;
  86819. }
  86820. // Do not block in blend mode.
  86821. if (material.needAlphaBlendingForMesh(mesh)) {
  86822. return;
  86823. }
  86824. // Culling
  86825. engine.setState(material.backFaceCulling);
  86826. // Managing instances
  86827. var batch = mesh._getInstancesRenderList(subMesh._id);
  86828. if (batch.mustReturn) {
  86829. return;
  86830. }
  86831. // Early Exit per mesh
  86832. if (!this._shouldRenderMesh(mesh)) {
  86833. return;
  86834. }
  86835. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86836. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  86837. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  86838. engine.enableEffect(this._effectLayerMapGenerationEffect);
  86839. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  86840. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  86841. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  86842. // Alpha test
  86843. if (material && material.needAlphaTesting()) {
  86844. var alphaTexture = material.getAlphaTestTexture();
  86845. if (alphaTexture) {
  86846. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  86847. var textureMatrix = alphaTexture.getTextureMatrix();
  86848. if (textureMatrix) {
  86849. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  86850. }
  86851. }
  86852. }
  86853. // Glow emissive only
  86854. if (this._emissiveTextureAndColor.texture) {
  86855. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  86856. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  86857. }
  86858. // Bones
  86859. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86860. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86861. }
  86862. // Morph targets
  86863. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  86864. // Draw
  86865. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  86866. }
  86867. else {
  86868. // Need to reset refresh rate of the shadowMap
  86869. this._mainTexture.resetRefreshCounter();
  86870. }
  86871. };
  86872. /**
  86873. * Rebuild the required buffers.
  86874. * @ignore Internal use only.
  86875. */
  86876. EffectLayer.prototype._rebuild = function () {
  86877. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86878. if (vb) {
  86879. vb._rebuild();
  86880. }
  86881. this._generateIndexBuffer();
  86882. };
  86883. /**
  86884. * Dispose only the render target textures and post process.
  86885. */
  86886. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  86887. this._mainTexture.dispose();
  86888. for (var i = 0; i < this._postProcesses.length; i++) {
  86889. if (this._postProcesses[i]) {
  86890. this._postProcesses[i].dispose();
  86891. }
  86892. }
  86893. this._postProcesses = [];
  86894. for (var i = 0; i < this._textures.length; i++) {
  86895. if (this._textures[i]) {
  86896. this._textures[i].dispose();
  86897. }
  86898. }
  86899. this._textures = [];
  86900. };
  86901. /**
  86902. * Dispose the highlight layer and free resources.
  86903. */
  86904. EffectLayer.prototype.dispose = function () {
  86905. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86906. if (vertexBuffer) {
  86907. vertexBuffer.dispose();
  86908. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86909. }
  86910. if (this._indexBuffer) {
  86911. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86912. this._indexBuffer = null;
  86913. }
  86914. // Clean textures and post processes
  86915. this._disposeTextureAndPostProcesses();
  86916. // Remove from scene
  86917. var index = this._scene.effectLayers.indexOf(this, 0);
  86918. if (index > -1) {
  86919. this._scene.effectLayers.splice(index, 1);
  86920. }
  86921. // Callback
  86922. this.onDisposeObservable.notifyObservers(this);
  86923. this.onDisposeObservable.clear();
  86924. this.onBeforeRenderMainTextureObservable.clear();
  86925. this.onBeforeComposeObservable.clear();
  86926. this.onAfterComposeObservable.clear();
  86927. this.onSizeChangedObservable.clear();
  86928. };
  86929. return EffectLayer;
  86930. }());
  86931. BABYLON.EffectLayer = EffectLayer;
  86932. })(BABYLON || (BABYLON = {}));
  86933. //# sourceMappingURL=babylon.effectLayer.js.map
  86934. "use strict";
  86935. var BABYLON;
  86936. (function (BABYLON) {
  86937. /**
  86938. * Special Glow Blur post process only blurring the alpha channel
  86939. * It enforces keeping the most luminous color in the color channel.
  86940. */
  86941. var GlowBlurPostProcess = /** @class */ (function (_super) {
  86942. __extends(GlowBlurPostProcess, _super);
  86943. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  86944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86945. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  86946. _this.direction = direction;
  86947. _this.kernel = kernel;
  86948. _this.onApplyObservable.add(function (effect) {
  86949. effect.setFloat2("screenSize", _this.width, _this.height);
  86950. effect.setVector2("direction", _this.direction);
  86951. effect.setFloat("blurWidth", _this.kernel);
  86952. });
  86953. return _this;
  86954. }
  86955. return GlowBlurPostProcess;
  86956. }(BABYLON.PostProcess));
  86957. /**
  86958. * The highlight layer Helps adding a glow effect around a mesh.
  86959. *
  86960. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86961. * glowy meshes to your scene.
  86962. *
  86963. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  86964. */
  86965. var HighlightLayer = /** @class */ (function (_super) {
  86966. __extends(HighlightLayer, _super);
  86967. /**
  86968. * Instantiates a new highlight Layer and references it to the scene..
  86969. * @param name The name of the layer
  86970. * @param scene The scene to use the layer in
  86971. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  86972. */
  86973. function HighlightLayer(name, scene, options) {
  86974. var _this = _super.call(this, name, scene) || this;
  86975. _this.name = name;
  86976. /**
  86977. * Specifies whether or not the inner glow is ACTIVE in the layer.
  86978. */
  86979. _this.innerGlow = true;
  86980. /**
  86981. * Specifies whether or not the outer glow is ACTIVE in the layer.
  86982. */
  86983. _this.outerGlow = true;
  86984. /**
  86985. * An event triggered when the highlight layer is being blurred.
  86986. */
  86987. _this.onBeforeBlurObservable = new BABYLON.Observable();
  86988. /**
  86989. * An event triggered when the highlight layer has been blurred.
  86990. */
  86991. _this.onAfterBlurObservable = new BABYLON.Observable();
  86992. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  86993. _this._meshes = {};
  86994. _this._excludedMeshes = {};
  86995. _this.neutralColor = HighlightLayer.NeutralColor;
  86996. // Warn on stencil
  86997. if (!_this._engine.isStencilEnable) {
  86998. 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 }");
  86999. }
  87000. // Adapt options
  87001. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  87002. // Initialize the layer
  87003. _this._init({
  87004. alphaBlendingMode: _this._options.alphaBlendingMode,
  87005. camera: _this._options.camera,
  87006. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87007. mainTextureRatio: _this._options.mainTextureRatio
  87008. });
  87009. // Do not render as long as no meshes have been added
  87010. _this._shouldRender = false;
  87011. return _this;
  87012. }
  87013. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  87014. /**
  87015. * Gets the horizontal size of the blur.
  87016. */
  87017. get: function () {
  87018. return this._horizontalBlurPostprocess.kernel;
  87019. },
  87020. /**
  87021. * Specifies the horizontal size of the blur.
  87022. */
  87023. set: function (value) {
  87024. this._horizontalBlurPostprocess.kernel = value;
  87025. },
  87026. enumerable: true,
  87027. configurable: true
  87028. });
  87029. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  87030. /**
  87031. * Gets the vertical size of the blur.
  87032. */
  87033. get: function () {
  87034. return this._verticalBlurPostprocess.kernel;
  87035. },
  87036. /**
  87037. * Specifies the vertical size of the blur.
  87038. */
  87039. set: function (value) {
  87040. this._verticalBlurPostprocess.kernel = value;
  87041. },
  87042. enumerable: true,
  87043. configurable: true
  87044. });
  87045. /**
  87046. * Get the effect name of the layer.
  87047. * @return The effect name
  87048. */
  87049. HighlightLayer.prototype.getEffectName = function () {
  87050. return HighlightLayer.EffectName;
  87051. };
  87052. /**
  87053. * Create the merge effect. This is the shader use to blit the information back
  87054. * to the main canvas at the end of the scene rendering.
  87055. */
  87056. HighlightLayer.prototype._createMergeEffect = function () {
  87057. // Effect
  87058. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  87059. };
  87060. /**
  87061. * Creates the render target textures and post processes used in the highlight layer.
  87062. */
  87063. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  87064. var _this = this;
  87065. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  87066. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  87067. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87068. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87069. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  87070. width: blurTextureWidth,
  87071. height: blurTextureHeight
  87072. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87073. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87074. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87075. this._blurTexture.anisotropicFilteringLevel = 16;
  87076. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  87077. this._blurTexture.renderParticles = false;
  87078. this._blurTexture.ignoreCameraViewport = true;
  87079. this._textures = [this._blurTexture];
  87080. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  87081. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87082. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  87083. effect.setTexture("textureSampler", _this._mainTexture);
  87084. });
  87085. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87086. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87087. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87088. });
  87089. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87090. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  87091. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87092. });
  87093. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87094. }
  87095. else {
  87096. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  87097. width: blurTextureWidth,
  87098. height: blurTextureHeight
  87099. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87100. this._horizontalBlurPostprocess.width = blurTextureWidth;
  87101. this._horizontalBlurPostprocess.height = blurTextureHeight;
  87102. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87103. effect.setTexture("textureSampler", _this._mainTexture);
  87104. });
  87105. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  87106. width: blurTextureWidth,
  87107. height: blurTextureHeight
  87108. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87109. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87110. }
  87111. this._mainTexture.onAfterUnbindObservable.add(function () {
  87112. _this.onBeforeBlurObservable.notifyObservers(_this);
  87113. var internalTexture = _this._blurTexture.getInternalTexture();
  87114. if (internalTexture) {
  87115. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  87116. }
  87117. _this.onAfterBlurObservable.notifyObservers(_this);
  87118. });
  87119. // Prevent autoClear.
  87120. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87121. };
  87122. /**
  87123. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87124. */
  87125. HighlightLayer.prototype.needStencil = function () {
  87126. return true;
  87127. };
  87128. /**
  87129. * Checks for the readiness of the element composing the layer.
  87130. * @param subMesh the mesh to check for
  87131. * @param useInstances specify wether or not to use instances to render the mesh
  87132. * @param emissiveTexture the associated emissive texture used to generate the glow
  87133. * @return true if ready otherwise, false
  87134. */
  87135. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  87136. var material = subMesh.getMaterial();
  87137. var mesh = subMesh.getRenderingMesh();
  87138. if (!material || !mesh || !this._meshes) {
  87139. return false;
  87140. }
  87141. var emissiveTexture = null;
  87142. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87143. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87144. emissiveTexture = material.emissiveTexture;
  87145. }
  87146. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87147. };
  87148. /**
  87149. * Implementation specific of rendering the generating effect on the main canvas.
  87150. * @param effect The effect used to render through
  87151. */
  87152. HighlightLayer.prototype._internalRender = function (effect) {
  87153. // Texture
  87154. effect.setTexture("textureSampler", this._blurTexture);
  87155. // Cache
  87156. var engine = this._engine;
  87157. var previousStencilBuffer = engine.getStencilBuffer();
  87158. var previousStencilFunction = engine.getStencilFunction();
  87159. var previousStencilMask = engine.getStencilMask();
  87160. var previousStencilOperationPass = engine.getStencilOperationPass();
  87161. var previousStencilOperationFail = engine.getStencilOperationFail();
  87162. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  87163. var previousStencilReference = engine.getStencilFunctionReference();
  87164. // Stencil operations
  87165. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  87166. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  87167. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  87168. // Draw order
  87169. engine.setStencilMask(0x00);
  87170. engine.setStencilBuffer(true);
  87171. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  87172. // 2 passes inner outer
  87173. if (this.outerGlow) {
  87174. effect.setFloat("offset", 0);
  87175. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  87176. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87177. }
  87178. if (this.innerGlow) {
  87179. effect.setFloat("offset", 1);
  87180. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  87181. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87182. }
  87183. // Restore Cache
  87184. engine.setStencilFunction(previousStencilFunction);
  87185. engine.setStencilMask(previousStencilMask);
  87186. engine.setStencilBuffer(previousStencilBuffer);
  87187. engine.setStencilOperationPass(previousStencilOperationPass);
  87188. engine.setStencilOperationFail(previousStencilOperationFail);
  87189. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  87190. engine.setStencilFunctionReference(previousStencilReference);
  87191. };
  87192. /**
  87193. * Returns true if the layer contains information to display, otherwise false.
  87194. */
  87195. HighlightLayer.prototype.shouldRender = function () {
  87196. if (_super.prototype.shouldRender.call(this)) {
  87197. return this._meshes ? true : false;
  87198. }
  87199. return false;
  87200. };
  87201. /**
  87202. * Returns true if the mesh should render, otherwise false.
  87203. * @param mesh The mesh to render
  87204. * @returns true if it should render otherwise false
  87205. */
  87206. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  87207. // Excluded Mesh
  87208. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  87209. return false;
  87210. }
  87211. ;
  87212. return true;
  87213. };
  87214. /**
  87215. * Sets the required values for both the emissive texture and and the main color.
  87216. */
  87217. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87218. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87219. if (highlightLayerMesh) {
  87220. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  87221. }
  87222. else {
  87223. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87224. }
  87225. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87226. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87227. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  87228. }
  87229. else {
  87230. this._emissiveTextureAndColor.texture = null;
  87231. }
  87232. };
  87233. /**
  87234. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  87235. * @param mesh The mesh to exclude from the highlight layer
  87236. */
  87237. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  87238. if (!this._excludedMeshes) {
  87239. return;
  87240. }
  87241. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87242. if (!meshExcluded) {
  87243. this._excludedMeshes[mesh.uniqueId] = {
  87244. mesh: mesh,
  87245. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  87246. mesh.getEngine().setStencilBuffer(false);
  87247. }),
  87248. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  87249. mesh.getEngine().setStencilBuffer(true);
  87250. }),
  87251. };
  87252. }
  87253. };
  87254. /**
  87255. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  87256. * @param mesh The mesh to highlight
  87257. */
  87258. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  87259. if (!this._excludedMeshes) {
  87260. return;
  87261. }
  87262. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87263. if (meshExcluded) {
  87264. if (meshExcluded.beforeRender) {
  87265. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  87266. }
  87267. if (meshExcluded.afterRender) {
  87268. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  87269. }
  87270. }
  87271. this._excludedMeshes[mesh.uniqueId] = null;
  87272. };
  87273. /**
  87274. * Determine if a given mesh will be highlighted by the current HighlightLayer
  87275. * @param mesh mesh to test
  87276. * @returns true if the mesh will be highlighted by the current HighlightLayer
  87277. */
  87278. HighlightLayer.prototype.hasMesh = function (mesh) {
  87279. if (!this._meshes) {
  87280. return false;
  87281. }
  87282. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  87283. };
  87284. /**
  87285. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  87286. * @param mesh The mesh to highlight
  87287. * @param color The color of the highlight
  87288. * @param glowEmissiveOnly Extract the glow from the emissive texture
  87289. */
  87290. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  87291. var _this = this;
  87292. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  87293. if (!this._meshes) {
  87294. return;
  87295. }
  87296. var meshHighlight = this._meshes[mesh.uniqueId];
  87297. if (meshHighlight) {
  87298. meshHighlight.color = color;
  87299. }
  87300. else {
  87301. this._meshes[mesh.uniqueId] = {
  87302. mesh: mesh,
  87303. color: color,
  87304. // Lambda required for capture due to Observable this context
  87305. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  87306. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  87307. _this._defaultStencilReference(mesh);
  87308. }
  87309. else {
  87310. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  87311. }
  87312. }),
  87313. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  87314. glowEmissiveOnly: glowEmissiveOnly
  87315. };
  87316. }
  87317. this._shouldRender = true;
  87318. };
  87319. /**
  87320. * Remove a mesh from the highlight layer in order to make it stop glowing.
  87321. * @param mesh The mesh to highlight
  87322. */
  87323. HighlightLayer.prototype.removeMesh = function (mesh) {
  87324. if (!this._meshes) {
  87325. return;
  87326. }
  87327. var meshHighlight = this._meshes[mesh.uniqueId];
  87328. if (meshHighlight) {
  87329. if (meshHighlight.observerHighlight) {
  87330. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87331. }
  87332. if (meshHighlight.observerDefault) {
  87333. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87334. }
  87335. delete this._meshes[mesh.uniqueId];
  87336. }
  87337. this._shouldRender = false;
  87338. for (var meshHighlightToCheck in this._meshes) {
  87339. if (this._meshes[meshHighlightToCheck]) {
  87340. this._shouldRender = true;
  87341. break;
  87342. }
  87343. }
  87344. };
  87345. /**
  87346. * Force the stencil to the normal expected value for none glowing parts
  87347. */
  87348. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  87349. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  87350. };
  87351. /**
  87352. * Free any resources and references associated to a mesh.
  87353. * Internal use
  87354. * @param mesh The mesh to free.
  87355. */
  87356. HighlightLayer.prototype._disposeMesh = function (mesh) {
  87357. this.removeMesh(mesh);
  87358. this.removeExcludedMesh(mesh);
  87359. };
  87360. /**
  87361. * Dispose the highlight layer and free resources.
  87362. */
  87363. HighlightLayer.prototype.dispose = function () {
  87364. if (this._meshes) {
  87365. // Clean mesh references
  87366. for (var id in this._meshes) {
  87367. var meshHighlight = this._meshes[id];
  87368. if (meshHighlight && meshHighlight.mesh) {
  87369. if (meshHighlight.observerHighlight) {
  87370. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87371. }
  87372. if (meshHighlight.observerDefault) {
  87373. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87374. }
  87375. }
  87376. }
  87377. this._meshes = null;
  87378. }
  87379. if (this._excludedMeshes) {
  87380. for (var id in this._excludedMeshes) {
  87381. var meshHighlight = this._excludedMeshes[id];
  87382. if (meshHighlight) {
  87383. if (meshHighlight.beforeRender) {
  87384. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87385. }
  87386. if (meshHighlight.afterRender) {
  87387. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87388. }
  87389. }
  87390. }
  87391. this._excludedMeshes = null;
  87392. }
  87393. _super.prototype.dispose.call(this);
  87394. };
  87395. /**
  87396. * Effect Name of the highlight layer.
  87397. */
  87398. HighlightLayer.EffectName = "HighlightLayer";
  87399. /**
  87400. * The neutral color used during the preparation of the glow effect.
  87401. * This is black by default as the blend operation is a blend operation.
  87402. */
  87403. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87404. /**
  87405. * Stencil value used for glowing meshes.
  87406. */
  87407. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87408. /**
  87409. * Stencil value used for the other meshes in the scene.
  87410. */
  87411. HighlightLayer.NormalMeshStencilReference = 0x01;
  87412. return HighlightLayer;
  87413. }(BABYLON.EffectLayer));
  87414. BABYLON.HighlightLayer = HighlightLayer;
  87415. })(BABYLON || (BABYLON = {}));
  87416. //# sourceMappingURL=babylon.highlightLayer.js.map
  87417. "use strict";
  87418. var BABYLON;
  87419. (function (BABYLON) {
  87420. /**
  87421. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87422. *
  87423. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87424. * glowy meshes to your scene.
  87425. *
  87426. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87427. */
  87428. var GlowLayer = /** @class */ (function (_super) {
  87429. __extends(GlowLayer, _super);
  87430. /**
  87431. * Instantiates a new glow Layer and references it to the scene.
  87432. * @param name The name of the layer
  87433. * @param scene The scene to use the layer in
  87434. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87435. */
  87436. function GlowLayer(name, scene, options) {
  87437. var _this = _super.call(this, name, scene) || this;
  87438. _this.name = name;
  87439. _this._intensity = 1.0;
  87440. _this._includedOnlyMeshes = [];
  87441. _this._excludedMeshes = [];
  87442. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87443. // Adapt options
  87444. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87445. // Initialize the layer
  87446. _this._init({
  87447. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87448. camera: _this._options.camera,
  87449. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87450. mainTextureRatio: _this._options.mainTextureRatio
  87451. });
  87452. return _this;
  87453. }
  87454. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87455. /**
  87456. * Gets the kernel size of the blur.
  87457. */
  87458. get: function () {
  87459. return this._horizontalBlurPostprocess1.kernel;
  87460. },
  87461. /**
  87462. * Sets the kernel size of the blur.
  87463. */
  87464. set: function (value) {
  87465. this._horizontalBlurPostprocess1.kernel = value;
  87466. this._verticalBlurPostprocess1.kernel = value;
  87467. this._horizontalBlurPostprocess2.kernel = value;
  87468. this._verticalBlurPostprocess2.kernel = value;
  87469. },
  87470. enumerable: true,
  87471. configurable: true
  87472. });
  87473. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87474. /**
  87475. * Gets the glow intensity.
  87476. */
  87477. get: function () {
  87478. return this._intensity;
  87479. },
  87480. /**
  87481. * Sets the glow intensity.
  87482. */
  87483. set: function (value) {
  87484. this._intensity = value;
  87485. },
  87486. enumerable: true,
  87487. configurable: true
  87488. });
  87489. /**
  87490. * Get the effect name of the layer.
  87491. * @return The effect name
  87492. */
  87493. GlowLayer.prototype.getEffectName = function () {
  87494. return GlowLayer.EffectName;
  87495. };
  87496. /**
  87497. * Create the merge effect. This is the shader use to blit the information back
  87498. * to the main canvas at the end of the scene rendering.
  87499. */
  87500. GlowLayer.prototype._createMergeEffect = function () {
  87501. // Effect
  87502. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87503. };
  87504. /**
  87505. * Creates the render target textures and post processes used in the glow layer.
  87506. */
  87507. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87508. var _this = this;
  87509. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87510. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87511. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87512. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87513. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87514. width: blurTextureWidth,
  87515. height: blurTextureHeight
  87516. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87517. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87518. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87519. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87520. this._blurTexture1.renderParticles = false;
  87521. this._blurTexture1.ignoreCameraViewport = true;
  87522. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87523. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87524. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87525. width: blurTextureWidth2,
  87526. height: blurTextureHeight2
  87527. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87528. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87529. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87530. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87531. this._blurTexture2.renderParticles = false;
  87532. this._blurTexture2.ignoreCameraViewport = true;
  87533. this._textures = [this._blurTexture1, this._blurTexture2];
  87534. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87535. width: blurTextureWidth,
  87536. height: blurTextureHeight
  87537. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87538. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87539. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87540. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87541. effect.setTexture("textureSampler", _this._mainTexture);
  87542. });
  87543. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87544. width: blurTextureWidth,
  87545. height: blurTextureHeight
  87546. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87547. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87548. width: blurTextureWidth2,
  87549. height: blurTextureHeight2
  87550. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87551. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87552. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87553. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87554. effect.setTexture("textureSampler", _this._blurTexture1);
  87555. });
  87556. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87557. width: blurTextureWidth2,
  87558. height: blurTextureHeight2
  87559. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87560. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87561. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87562. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87563. this._mainTexture.samples = this._options.mainTextureSamples;
  87564. this._mainTexture.onAfterUnbindObservable.add(function () {
  87565. var internalTexture = _this._blurTexture1.getInternalTexture();
  87566. if (internalTexture) {
  87567. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87568. internalTexture = _this._blurTexture2.getInternalTexture();
  87569. if (internalTexture) {
  87570. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87571. }
  87572. }
  87573. });
  87574. // Prevent autoClear.
  87575. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87576. };
  87577. /**
  87578. * Checks for the readiness of the element composing the layer.
  87579. * @param subMesh the mesh to check for
  87580. * @param useInstances specify wether or not to use instances to render the mesh
  87581. * @param emissiveTexture the associated emissive texture used to generate the glow
  87582. * @return true if ready otherwise, false
  87583. */
  87584. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87585. var material = subMesh.getMaterial();
  87586. var mesh = subMesh.getRenderingMesh();
  87587. if (!material || !mesh) {
  87588. return false;
  87589. }
  87590. var emissiveTexture = material.emissiveTexture;
  87591. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87592. };
  87593. /**
  87594. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87595. */
  87596. GlowLayer.prototype.needStencil = function () {
  87597. return false;
  87598. };
  87599. /**
  87600. * Implementation specific of rendering the generating effect on the main canvas.
  87601. * @param effect The effect used to render through
  87602. */
  87603. GlowLayer.prototype._internalRender = function (effect) {
  87604. // Texture
  87605. effect.setTexture("textureSampler", this._blurTexture1);
  87606. effect.setTexture("textureSampler2", this._blurTexture2);
  87607. effect.setFloat("offset", this._intensity);
  87608. // Cache
  87609. var engine = this._engine;
  87610. var previousStencilBuffer = engine.getStencilBuffer();
  87611. // Draw order
  87612. engine.setStencilBuffer(false);
  87613. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87614. // Draw order
  87615. engine.setStencilBuffer(previousStencilBuffer);
  87616. };
  87617. /**
  87618. * Sets the required values for both the emissive texture and and the main color.
  87619. */
  87620. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87621. var textureLevel = 1.0;
  87622. if (this.customEmissiveTextureSelector) {
  87623. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87624. }
  87625. else {
  87626. if (material) {
  87627. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87628. if (this._emissiveTextureAndColor.texture) {
  87629. textureLevel = this._emissiveTextureAndColor.texture.level;
  87630. }
  87631. }
  87632. else {
  87633. this._emissiveTextureAndColor.texture = null;
  87634. }
  87635. }
  87636. if (this.customEmissiveColorSelector) {
  87637. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87638. }
  87639. else {
  87640. if (material.emissiveColor) {
  87641. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87642. }
  87643. else {
  87644. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87645. }
  87646. }
  87647. };
  87648. /**
  87649. * Returns true if the mesh should render, otherwise false.
  87650. * @param mesh The mesh to render
  87651. * @returns true if it should render otherwise false
  87652. */
  87653. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87654. return this.hasMesh(mesh);
  87655. };
  87656. /**
  87657. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87658. * @param mesh The mesh to exclude from the glow layer
  87659. */
  87660. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87661. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87662. this._excludedMeshes.push(mesh.uniqueId);
  87663. }
  87664. };
  87665. /**
  87666. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87667. * @param mesh The mesh to remove
  87668. */
  87669. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87670. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87671. if (index !== -1) {
  87672. this._excludedMeshes.splice(index, 1);
  87673. }
  87674. };
  87675. /**
  87676. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87677. * @param mesh The mesh to include in the glow layer
  87678. */
  87679. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87680. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87681. this._includedOnlyMeshes.push(mesh.uniqueId);
  87682. }
  87683. };
  87684. /**
  87685. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87686. * @param mesh The mesh to remove
  87687. */
  87688. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87689. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87690. if (index !== -1) {
  87691. this._includedOnlyMeshes.splice(index, 1);
  87692. }
  87693. };
  87694. /**
  87695. * Determine if a given mesh will be used in the glow layer
  87696. * @param mesh The mesh to test
  87697. * @returns true if the mesh will be highlighted by the current glow layer
  87698. */
  87699. GlowLayer.prototype.hasMesh = function (mesh) {
  87700. // Included Mesh
  87701. if (this._includedOnlyMeshes.length) {
  87702. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87703. }
  87704. ;
  87705. // Excluded Mesh
  87706. if (this._excludedMeshes.length) {
  87707. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87708. }
  87709. ;
  87710. return true;
  87711. };
  87712. /**
  87713. * Free any resources and references associated to a mesh.
  87714. * Internal use
  87715. * @param mesh The mesh to free.
  87716. */
  87717. GlowLayer.prototype._disposeMesh = function (mesh) {
  87718. this.removeIncludedOnlyMesh(mesh);
  87719. this.removeExcludedMesh(mesh);
  87720. };
  87721. /**
  87722. * Effect Name of the layer.
  87723. */
  87724. GlowLayer.EffectName = "GlowLayer";
  87725. /**
  87726. * The default blur kernel size used for the glow.
  87727. */
  87728. GlowLayer.DefaultBlurKernelSize = 32;
  87729. /**
  87730. * The default texture size ratio used for the glow.
  87731. */
  87732. GlowLayer.DefaultTextureRatio = 0.5;
  87733. return GlowLayer;
  87734. }(BABYLON.EffectLayer));
  87735. BABYLON.GlowLayer = GlowLayer;
  87736. })(BABYLON || (BABYLON = {}));
  87737. //# sourceMappingURL=babylon.glowLayer.js.map
  87738. "use strict";
  87739. var BABYLON;
  87740. (function (BABYLON) {
  87741. /**
  87742. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87743. */
  87744. var AssetTaskState;
  87745. (function (AssetTaskState) {
  87746. /**
  87747. * Initialization
  87748. */
  87749. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87750. /**
  87751. * Running
  87752. */
  87753. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87754. /**
  87755. * Done
  87756. */
  87757. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87758. /**
  87759. * Error
  87760. */
  87761. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87762. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87763. /**
  87764. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87765. */
  87766. var AbstractAssetTask = /** @class */ (function () {
  87767. /**
  87768. * Creates a new {BABYLON.AssetsManager}
  87769. * @param name defines the name of the task
  87770. */
  87771. function AbstractAssetTask(
  87772. /**
  87773. * Task name
  87774. */ name) {
  87775. this.name = name;
  87776. this._isCompleted = false;
  87777. this._taskState = AssetTaskState.INIT;
  87778. }
  87779. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87780. /**
  87781. * Get if the task is completed
  87782. */
  87783. get: function () {
  87784. return this._isCompleted;
  87785. },
  87786. enumerable: true,
  87787. configurable: true
  87788. });
  87789. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87790. /**
  87791. * Gets the current state of the task
  87792. */
  87793. get: function () {
  87794. return this._taskState;
  87795. },
  87796. enumerable: true,
  87797. configurable: true
  87798. });
  87799. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87800. /**
  87801. * Gets the current error object (if task is in error)
  87802. */
  87803. get: function () {
  87804. return this._errorObject;
  87805. },
  87806. enumerable: true,
  87807. configurable: true
  87808. });
  87809. /**
  87810. * Internal only
  87811. * @ignore
  87812. */
  87813. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87814. if (this._errorObject) {
  87815. return;
  87816. }
  87817. this._errorObject = {
  87818. message: message,
  87819. exception: exception
  87820. };
  87821. };
  87822. /**
  87823. * Execute the current task
  87824. * @param scene defines the scene where you want your assets to be loaded
  87825. * @param onSuccess is a callback called when the task is successfully executed
  87826. * @param onError is a callback called if an error occurs
  87827. */
  87828. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87829. var _this = this;
  87830. this._taskState = AssetTaskState.RUNNING;
  87831. this.runTask(scene, function () {
  87832. _this.onDoneCallback(onSuccess, onError);
  87833. }, function (msg, exception) {
  87834. _this.onErrorCallback(onError, msg, exception);
  87835. });
  87836. };
  87837. /**
  87838. * Execute the current task
  87839. * @param scene defines the scene where you want your assets to be loaded
  87840. * @param onSuccess is a callback called when the task is successfully executed
  87841. * @param onError is a callback called if an error occurs
  87842. */
  87843. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87844. throw new Error("runTask is not implemented");
  87845. };
  87846. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  87847. this._taskState = AssetTaskState.ERROR;
  87848. this._errorObject = {
  87849. message: message,
  87850. exception: exception
  87851. };
  87852. if (this.onError) {
  87853. this.onError(this, message, exception);
  87854. }
  87855. onError();
  87856. };
  87857. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  87858. try {
  87859. this._taskState = AssetTaskState.DONE;
  87860. this._isCompleted = true;
  87861. if (this.onSuccess) {
  87862. this.onSuccess(this);
  87863. }
  87864. onSuccess();
  87865. }
  87866. catch (e) {
  87867. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  87868. }
  87869. };
  87870. return AbstractAssetTask;
  87871. }());
  87872. BABYLON.AbstractAssetTask = AbstractAssetTask;
  87873. /**
  87874. * Class used to share progress information about assets loading
  87875. */
  87876. var AssetsProgressEvent = /** @class */ (function () {
  87877. /**
  87878. * Creates a {BABYLON.AssetsProgressEvent}
  87879. * @param remainingCount defines the number of remaining tasks to process
  87880. * @param totalCount defines the total number of tasks
  87881. * @param task defines the task that was just processed
  87882. */
  87883. function AssetsProgressEvent(remainingCount, totalCount, task) {
  87884. this.remainingCount = remainingCount;
  87885. this.totalCount = totalCount;
  87886. this.task = task;
  87887. }
  87888. return AssetsProgressEvent;
  87889. }());
  87890. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  87891. /**
  87892. * Define a task used by {BABYLON.AssetsManager} to load meshes
  87893. */
  87894. var MeshAssetTask = /** @class */ (function (_super) {
  87895. __extends(MeshAssetTask, _super);
  87896. /**
  87897. * Creates a new {BABYLON.MeshAssetTask}
  87898. * @param name defines the name of the task
  87899. * @param meshesNames defines the list of mesh's names you want to load
  87900. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  87901. * @param sceneFilename defines the filename of the scene to load from
  87902. */
  87903. function MeshAssetTask(
  87904. /**
  87905. * Defines the name of the task
  87906. */
  87907. name,
  87908. /**
  87909. * Defines the list of mesh's names you want to load
  87910. */
  87911. meshesNames,
  87912. /**
  87913. * Defines the root url to use as a base to load your meshes and associated resources
  87914. */
  87915. rootUrl,
  87916. /**
  87917. * Defines the filename of the scene to load from
  87918. */
  87919. sceneFilename) {
  87920. var _this = _super.call(this, name) || this;
  87921. _this.name = name;
  87922. _this.meshesNames = meshesNames;
  87923. _this.rootUrl = rootUrl;
  87924. _this.sceneFilename = sceneFilename;
  87925. return _this;
  87926. }
  87927. /**
  87928. * Execute the current task
  87929. * @param scene defines the scene where you want your assets to be loaded
  87930. * @param onSuccess is a callback called when the task is successfully executed
  87931. * @param onError is a callback called if an error occurs
  87932. */
  87933. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87934. var _this = this;
  87935. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  87936. _this.loadedMeshes = meshes;
  87937. _this.loadedParticleSystems = particleSystems;
  87938. _this.loadedSkeletons = skeletons;
  87939. onSuccess();
  87940. }, null, function (scene, message, exception) {
  87941. onError(message, exception);
  87942. });
  87943. };
  87944. return MeshAssetTask;
  87945. }(AbstractAssetTask));
  87946. BABYLON.MeshAssetTask = MeshAssetTask;
  87947. /**
  87948. * Define a task used by {BABYLON.AssetsManager} to load text content
  87949. */
  87950. var TextFileAssetTask = /** @class */ (function (_super) {
  87951. __extends(TextFileAssetTask, _super);
  87952. /**
  87953. * Creates a new TextFileAssetTask object
  87954. * @param name defines the name of the task
  87955. * @param url defines the location of the file to load
  87956. */
  87957. function TextFileAssetTask(
  87958. /**
  87959. * Defines the name of the task
  87960. */
  87961. name,
  87962. /**
  87963. * Defines the location of the file to load
  87964. */
  87965. url) {
  87966. var _this = _super.call(this, name) || this;
  87967. _this.name = name;
  87968. _this.url = url;
  87969. return _this;
  87970. }
  87971. /**
  87972. * Execute the current task
  87973. * @param scene defines the scene where you want your assets to be loaded
  87974. * @param onSuccess is a callback called when the task is successfully executed
  87975. * @param onError is a callback called if an error occurs
  87976. */
  87977. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87978. var _this = this;
  87979. scene._loadFile(this.url, function (data) {
  87980. _this.text = data;
  87981. onSuccess();
  87982. }, undefined, false, false, function (request, exception) {
  87983. if (request) {
  87984. onError(request.status + " " + request.statusText, exception);
  87985. }
  87986. });
  87987. };
  87988. return TextFileAssetTask;
  87989. }(AbstractAssetTask));
  87990. BABYLON.TextFileAssetTask = TextFileAssetTask;
  87991. /**
  87992. * Define a task used by {BABYLON.AssetsManager} to load binary data
  87993. */
  87994. var BinaryFileAssetTask = /** @class */ (function (_super) {
  87995. __extends(BinaryFileAssetTask, _super);
  87996. /**
  87997. * Creates a new BinaryFileAssetTask object
  87998. * @param name defines the name of the new task
  87999. * @param url defines the location of the file to load
  88000. */
  88001. function BinaryFileAssetTask(
  88002. /**
  88003. * Defines the name of the task
  88004. */
  88005. name,
  88006. /**
  88007. * Defines the location of the file to load
  88008. */
  88009. url) {
  88010. var _this = _super.call(this, name) || this;
  88011. _this.name = name;
  88012. _this.url = url;
  88013. return _this;
  88014. }
  88015. /**
  88016. * Execute the current task
  88017. * @param scene defines the scene where you want your assets to be loaded
  88018. * @param onSuccess is a callback called when the task is successfully executed
  88019. * @param onError is a callback called if an error occurs
  88020. */
  88021. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88022. var _this = this;
  88023. scene._loadFile(this.url, function (data) {
  88024. _this.data = data;
  88025. onSuccess();
  88026. }, undefined, true, true, function (request, exception) {
  88027. if (request) {
  88028. onError(request.status + " " + request.statusText, exception);
  88029. }
  88030. });
  88031. };
  88032. return BinaryFileAssetTask;
  88033. }(AbstractAssetTask));
  88034. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  88035. /**
  88036. * Define a task used by {BABYLON.AssetsManager} to load images
  88037. */
  88038. var ImageAssetTask = /** @class */ (function (_super) {
  88039. __extends(ImageAssetTask, _super);
  88040. /**
  88041. * Creates a new ImageAssetTask
  88042. * @param name defines the name of the task
  88043. * @param url defines the location of the image to load
  88044. */
  88045. function ImageAssetTask(
  88046. /**
  88047. * Defines the name of the task
  88048. */
  88049. name,
  88050. /**
  88051. * Defines the location of the image to load
  88052. */
  88053. url) {
  88054. var _this = _super.call(this, name) || this;
  88055. _this.name = name;
  88056. _this.url = url;
  88057. return _this;
  88058. }
  88059. /**
  88060. * Execute the current task
  88061. * @param scene defines the scene where you want your assets to be loaded
  88062. * @param onSuccess is a callback called when the task is successfully executed
  88063. * @param onError is a callback called if an error occurs
  88064. */
  88065. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88066. var _this = this;
  88067. var img = new Image();
  88068. BABYLON.Tools.SetCorsBehavior(this.url, img);
  88069. img.onload = function () {
  88070. _this.image = img;
  88071. onSuccess();
  88072. };
  88073. img.onerror = function (err) {
  88074. onError("Error loading image", err);
  88075. };
  88076. img.src = this.url;
  88077. };
  88078. return ImageAssetTask;
  88079. }(AbstractAssetTask));
  88080. BABYLON.ImageAssetTask = ImageAssetTask;
  88081. /**
  88082. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  88083. */
  88084. var TextureAssetTask = /** @class */ (function (_super) {
  88085. __extends(TextureAssetTask, _super);
  88086. /**
  88087. * Creates a new TextureAssetTask object
  88088. * @param name defines the name of the task
  88089. * @param url defines the location of the file to load
  88090. * @param noMipmap defines if mipmap should not be generated (default is false)
  88091. * @param invertY defines if texture must be inverted on Y axis (default is false)
  88092. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88093. */
  88094. function TextureAssetTask(
  88095. /**
  88096. * Defines the name of the task
  88097. */
  88098. name,
  88099. /**
  88100. * Defines the location of the file to load
  88101. */
  88102. url,
  88103. /**
  88104. * Defines if mipmap should not be generated (default is false)
  88105. */
  88106. noMipmap,
  88107. /**
  88108. * Defines if texture must be inverted on Y axis (default is false)
  88109. */
  88110. invertY,
  88111. /**
  88112. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88113. */
  88114. samplingMode) {
  88115. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88116. var _this = _super.call(this, name) || this;
  88117. _this.name = name;
  88118. _this.url = url;
  88119. _this.noMipmap = noMipmap;
  88120. _this.invertY = invertY;
  88121. _this.samplingMode = samplingMode;
  88122. return _this;
  88123. }
  88124. /**
  88125. * Execute the current task
  88126. * @param scene defines the scene where you want your assets to be loaded
  88127. * @param onSuccess is a callback called when the task is successfully executed
  88128. * @param onError is a callback called if an error occurs
  88129. */
  88130. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88131. var onload = function () {
  88132. onSuccess();
  88133. };
  88134. var onerror = function (message, exception) {
  88135. onError(message, exception);
  88136. };
  88137. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  88138. };
  88139. return TextureAssetTask;
  88140. }(AbstractAssetTask));
  88141. BABYLON.TextureAssetTask = TextureAssetTask;
  88142. /**
  88143. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  88144. */
  88145. var CubeTextureAssetTask = /** @class */ (function (_super) {
  88146. __extends(CubeTextureAssetTask, _super);
  88147. /**
  88148. * Creates a new CubeTextureAssetTask
  88149. * @param name defines the name of the task
  88150. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88151. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88152. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88153. * @param files defines the explicit list of files (undefined by default)
  88154. */
  88155. function CubeTextureAssetTask(
  88156. /**
  88157. * Defines the name of the task
  88158. */
  88159. name,
  88160. /**
  88161. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88162. */
  88163. url,
  88164. /**
  88165. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88166. */
  88167. extensions,
  88168. /**
  88169. * Defines if mipmaps should not be generated (default is false)
  88170. */
  88171. noMipmap,
  88172. /**
  88173. * Defines the explicit list of files (undefined by default)
  88174. */
  88175. files) {
  88176. var _this = _super.call(this, name) || this;
  88177. _this.name = name;
  88178. _this.url = url;
  88179. _this.extensions = extensions;
  88180. _this.noMipmap = noMipmap;
  88181. _this.files = files;
  88182. return _this;
  88183. }
  88184. /**
  88185. * Execute the current task
  88186. * @param scene defines the scene where you want your assets to be loaded
  88187. * @param onSuccess is a callback called when the task is successfully executed
  88188. * @param onError is a callback called if an error occurs
  88189. */
  88190. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88191. var onload = function () {
  88192. onSuccess();
  88193. };
  88194. var onerror = function (message, exception) {
  88195. onError(message, exception);
  88196. };
  88197. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  88198. };
  88199. return CubeTextureAssetTask;
  88200. }(AbstractAssetTask));
  88201. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  88202. /**
  88203. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  88204. */
  88205. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  88206. __extends(HDRCubeTextureAssetTask, _super);
  88207. /**
  88208. * Creates a new HDRCubeTextureAssetTask object
  88209. * @param name defines the name of the task
  88210. * @param url defines the location of the file to load
  88211. * @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.
  88212. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88213. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88214. * @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)
  88215. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88216. */
  88217. function HDRCubeTextureAssetTask(
  88218. /**
  88219. * Defines the name of the task
  88220. */
  88221. name,
  88222. /**
  88223. * Defines the location of the file to load
  88224. */
  88225. url,
  88226. /**
  88227. * 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.
  88228. */
  88229. size,
  88230. /**
  88231. * Defines if mipmaps should not be generated (default is false)
  88232. */
  88233. noMipmap,
  88234. /**
  88235. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88236. */
  88237. generateHarmonics,
  88238. /**
  88239. * 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)
  88240. */
  88241. useInGammaSpace,
  88242. /**
  88243. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88244. */
  88245. usePMREMGenerator) {
  88246. if (noMipmap === void 0) { noMipmap = false; }
  88247. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88248. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88249. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88250. var _this = _super.call(this, name) || this;
  88251. _this.name = name;
  88252. _this.url = url;
  88253. _this.size = size;
  88254. _this.noMipmap = noMipmap;
  88255. _this.generateHarmonics = generateHarmonics;
  88256. _this.useInGammaSpace = useInGammaSpace;
  88257. _this.usePMREMGenerator = usePMREMGenerator;
  88258. return _this;
  88259. }
  88260. /**
  88261. * Execute the current task
  88262. * @param scene defines the scene where you want your assets to be loaded
  88263. * @param onSuccess is a callback called when the task is successfully executed
  88264. * @param onError is a callback called if an error occurs
  88265. */
  88266. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  88267. var onload = function () {
  88268. onSuccess();
  88269. };
  88270. var onerror = function (message, exception) {
  88271. onError(message, exception);
  88272. };
  88273. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  88274. };
  88275. return HDRCubeTextureAssetTask;
  88276. }(AbstractAssetTask));
  88277. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  88278. /**
  88279. * This class can be used to easily import assets into a scene
  88280. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  88281. */
  88282. var AssetsManager = /** @class */ (function () {
  88283. /**
  88284. * Creates a new AssetsManager
  88285. * @param scene defines the scene to work on
  88286. */
  88287. function AssetsManager(scene) {
  88288. this._isLoading = false;
  88289. this._tasks = new Array();
  88290. this._waitingTasksCount = 0;
  88291. this._totalTasksCount = 0;
  88292. /**
  88293. * Observable called when all tasks are processed
  88294. */
  88295. this.onTaskSuccessObservable = new BABYLON.Observable();
  88296. /**
  88297. * Observable called when a task had an error
  88298. */
  88299. this.onTaskErrorObservable = new BABYLON.Observable();
  88300. /**
  88301. * Observable called when a task is successful
  88302. */
  88303. this.onTasksDoneObservable = new BABYLON.Observable();
  88304. /**
  88305. * Observable called when a task is done (whatever the result is)
  88306. */
  88307. this.onProgressObservable = new BABYLON.Observable();
  88308. /**
  88309. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  88310. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  88311. */
  88312. this.useDefaultLoadingScreen = true;
  88313. this._scene = scene;
  88314. }
  88315. /**
  88316. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  88317. * @param taskName defines the name of the new task
  88318. * @param meshesNames defines the name of meshes to load
  88319. * @param rootUrl defines the root url to use to locate files
  88320. * @param sceneFilename defines the filename of the scene file
  88321. * @returns a new {BABYLON.MeshAssetTask} object
  88322. */
  88323. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  88324. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  88325. this._tasks.push(task);
  88326. return task;
  88327. };
  88328. /**
  88329. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  88330. * @param taskName defines the name of the new task
  88331. * @param url defines the url of the file to load
  88332. * @returns a new {BABYLON.TextFileAssetTask} object
  88333. */
  88334. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  88335. var task = new TextFileAssetTask(taskName, url);
  88336. this._tasks.push(task);
  88337. return task;
  88338. };
  88339. /**
  88340. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  88341. * @param taskName defines the name of the new task
  88342. * @param url defines the url of the file to load
  88343. * @returns a new {BABYLON.BinaryFileAssetTask} object
  88344. */
  88345. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  88346. var task = new BinaryFileAssetTask(taskName, url);
  88347. this._tasks.push(task);
  88348. return task;
  88349. };
  88350. /**
  88351. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  88352. * @param taskName defines the name of the new task
  88353. * @param url defines the url of the file to load
  88354. * @returns a new {BABYLON.ImageAssetTask} object
  88355. */
  88356. AssetsManager.prototype.addImageTask = function (taskName, url) {
  88357. var task = new ImageAssetTask(taskName, url);
  88358. this._tasks.push(task);
  88359. return task;
  88360. };
  88361. /**
  88362. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  88363. * @param taskName defines the name of the new task
  88364. * @param url defines the url of the file to load
  88365. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88366. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  88367. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  88368. * @returns a new {BABYLON.TextureAssetTask} object
  88369. */
  88370. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  88371. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88372. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  88373. this._tasks.push(task);
  88374. return task;
  88375. };
  88376. /**
  88377. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  88378. * @param taskName defines the name of the new task
  88379. * @param url defines the url of the file to load
  88380. * @param extensions defines the extension to use to load the cube map (can be null)
  88381. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88382. * @param files defines the list of files to load (can be null)
  88383. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88384. */
  88385. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88386. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88387. this._tasks.push(task);
  88388. return task;
  88389. };
  88390. /**
  88391. *
  88392. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88393. * @param taskName defines the name of the new task
  88394. * @param url defines the url of the file to load
  88395. * @param size defines the size you want for the cubemap (can be null)
  88396. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88397. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88398. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88399. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88400. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88401. */
  88402. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88403. if (noMipmap === void 0) { noMipmap = false; }
  88404. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88405. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88406. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88407. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88408. this._tasks.push(task);
  88409. return task;
  88410. };
  88411. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88412. var _this = this;
  88413. this._waitingTasksCount--;
  88414. try {
  88415. if (task.taskState === AssetTaskState.DONE) {
  88416. // Let's remove successfull tasks
  88417. BABYLON.Tools.SetImmediate(function () {
  88418. var index = _this._tasks.indexOf(task);
  88419. if (index > -1) {
  88420. _this._tasks.splice(index, 1);
  88421. }
  88422. });
  88423. }
  88424. if (this.onProgress) {
  88425. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88426. }
  88427. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88428. }
  88429. catch (e) {
  88430. BABYLON.Tools.Error("Error running progress callbacks.");
  88431. console.log(e);
  88432. }
  88433. if (this._waitingTasksCount === 0) {
  88434. try {
  88435. if (this.onFinish) {
  88436. this.onFinish(this._tasks);
  88437. }
  88438. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88439. }
  88440. catch (e) {
  88441. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88442. console.log(e);
  88443. }
  88444. this._isLoading = false;
  88445. this._scene.getEngine().hideLoadingUI();
  88446. }
  88447. };
  88448. AssetsManager.prototype._runTask = function (task) {
  88449. var _this = this;
  88450. var done = function () {
  88451. try {
  88452. if (_this.onTaskSuccess) {
  88453. _this.onTaskSuccess(task);
  88454. }
  88455. _this.onTaskSuccessObservable.notifyObservers(task);
  88456. _this._decreaseWaitingTasksCount(task);
  88457. }
  88458. catch (e) {
  88459. error("Error executing task success callbacks", e);
  88460. }
  88461. };
  88462. var error = function (message, exception) {
  88463. task._setErrorObject(message, exception);
  88464. if (_this.onTaskError) {
  88465. _this.onTaskError(task);
  88466. }
  88467. _this.onTaskErrorObservable.notifyObservers(task);
  88468. _this._decreaseWaitingTasksCount(task);
  88469. };
  88470. task.run(this._scene, done, error);
  88471. };
  88472. /**
  88473. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88474. * @return the current instance of the {BABYLON.AssetsManager}
  88475. */
  88476. AssetsManager.prototype.reset = function () {
  88477. this._isLoading = false;
  88478. this._tasks = new Array();
  88479. return this;
  88480. };
  88481. /**
  88482. * Start the loading process
  88483. * @return the current instance of the {BABYLON.AssetsManager}
  88484. */
  88485. AssetsManager.prototype.load = function () {
  88486. if (this._isLoading) {
  88487. return this;
  88488. }
  88489. this._isLoading = true;
  88490. this._waitingTasksCount = this._tasks.length;
  88491. this._totalTasksCount = this._tasks.length;
  88492. if (this._waitingTasksCount === 0) {
  88493. this._isLoading = false;
  88494. if (this.onFinish) {
  88495. this.onFinish(this._tasks);
  88496. }
  88497. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88498. return this;
  88499. }
  88500. if (this.useDefaultLoadingScreen) {
  88501. this._scene.getEngine().displayLoadingUI();
  88502. }
  88503. for (var index = 0; index < this._tasks.length; index++) {
  88504. var task = this._tasks[index];
  88505. this._runTask(task);
  88506. }
  88507. return this;
  88508. };
  88509. return AssetsManager;
  88510. }());
  88511. BABYLON.AssetsManager = AssetsManager;
  88512. })(BABYLON || (BABYLON = {}));
  88513. //# sourceMappingURL=babylon.assetsManager.js.map
  88514. "use strict";
  88515. var BABYLON;
  88516. (function (BABYLON) {
  88517. var serializedGeometries = [];
  88518. var serializeGeometry = function (geometry, serializationGeometries) {
  88519. if (serializedGeometries[geometry.id]) {
  88520. return;
  88521. }
  88522. if (geometry.doNotSerialize) {
  88523. return;
  88524. }
  88525. if (geometry instanceof BABYLON.BoxGeometry) {
  88526. serializationGeometries.boxes.push(geometry.serialize());
  88527. }
  88528. else if (geometry instanceof BABYLON.SphereGeometry) {
  88529. serializationGeometries.spheres.push(geometry.serialize());
  88530. }
  88531. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88532. serializationGeometries.cylinders.push(geometry.serialize());
  88533. }
  88534. else if (geometry instanceof BABYLON.TorusGeometry) {
  88535. serializationGeometries.toruses.push(geometry.serialize());
  88536. }
  88537. else if (geometry instanceof BABYLON.GroundGeometry) {
  88538. serializationGeometries.grounds.push(geometry.serialize());
  88539. }
  88540. else if (geometry instanceof BABYLON.Plane) {
  88541. serializationGeometries.planes.push(geometry.serialize());
  88542. }
  88543. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88544. serializationGeometries.torusKnots.push(geometry.serialize());
  88545. }
  88546. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88547. throw new Error("Unknown primitive type");
  88548. }
  88549. else {
  88550. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88551. }
  88552. serializedGeometries[geometry.id] = true;
  88553. };
  88554. var serializeMesh = function (mesh, serializationScene) {
  88555. var serializationObject = {};
  88556. // Geometry
  88557. var geometry = mesh._geometry;
  88558. if (geometry) {
  88559. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88560. // 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
  88561. serializeGeometry(geometry, serializationScene.geometries);
  88562. }
  88563. }
  88564. // Custom
  88565. if (mesh.serialize) {
  88566. mesh.serialize(serializationObject);
  88567. }
  88568. return serializationObject;
  88569. };
  88570. var finalizeSingleMesh = function (mesh, serializationObject) {
  88571. //only works if the mesh is already loaded
  88572. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88573. //serialize material
  88574. if (mesh.material) {
  88575. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88576. serializationObject.materials = serializationObject.materials || [];
  88577. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88578. serializationObject.materials.push(mesh.material.serialize());
  88579. }
  88580. }
  88581. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88582. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88583. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88584. serializationObject.multiMaterials.push(mesh.material.serialize());
  88585. }
  88586. }
  88587. }
  88588. //serialize geometry
  88589. var geometry = mesh._geometry;
  88590. if (geometry) {
  88591. if (!serializationObject.geometries) {
  88592. serializationObject.geometries = {};
  88593. serializationObject.geometries.boxes = [];
  88594. serializationObject.geometries.spheres = [];
  88595. serializationObject.geometries.cylinders = [];
  88596. serializationObject.geometries.toruses = [];
  88597. serializationObject.geometries.grounds = [];
  88598. serializationObject.geometries.planes = [];
  88599. serializationObject.geometries.torusKnots = [];
  88600. serializationObject.geometries.vertexData = [];
  88601. }
  88602. serializeGeometry(geometry, serializationObject.geometries);
  88603. }
  88604. // Skeletons
  88605. if (mesh.skeleton) {
  88606. serializationObject.skeletons = serializationObject.skeletons || [];
  88607. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88608. }
  88609. //serialize the actual mesh
  88610. serializationObject.meshes = serializationObject.meshes || [];
  88611. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88612. }
  88613. };
  88614. var SceneSerializer = /** @class */ (function () {
  88615. function SceneSerializer() {
  88616. }
  88617. SceneSerializer.ClearCache = function () {
  88618. serializedGeometries = [];
  88619. };
  88620. SceneSerializer.Serialize = function (scene) {
  88621. var serializationObject = {};
  88622. SceneSerializer.ClearCache();
  88623. // Scene
  88624. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88625. serializationObject.autoClear = scene.autoClear;
  88626. serializationObject.clearColor = scene.clearColor.asArray();
  88627. serializationObject.ambientColor = scene.ambientColor.asArray();
  88628. serializationObject.gravity = scene.gravity.asArray();
  88629. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88630. serializationObject.workerCollisions = scene.workerCollisions;
  88631. // Fog
  88632. if (scene.fogMode && scene.fogMode !== 0) {
  88633. serializationObject.fogMode = scene.fogMode;
  88634. serializationObject.fogColor = scene.fogColor.asArray();
  88635. serializationObject.fogStart = scene.fogStart;
  88636. serializationObject.fogEnd = scene.fogEnd;
  88637. serializationObject.fogDensity = scene.fogDensity;
  88638. }
  88639. //Physics
  88640. if (scene.isPhysicsEnabled()) {
  88641. var physicEngine = scene.getPhysicsEngine();
  88642. if (physicEngine) {
  88643. serializationObject.physicsEnabled = true;
  88644. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88645. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88646. }
  88647. }
  88648. // Metadata
  88649. if (scene.metadata) {
  88650. serializationObject.metadata = scene.metadata;
  88651. }
  88652. // Morph targets
  88653. serializationObject.morphTargetManagers = [];
  88654. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88655. var abstractMesh = _a[_i];
  88656. var manager = abstractMesh.morphTargetManager;
  88657. if (manager) {
  88658. serializationObject.morphTargetManagers.push(manager.serialize());
  88659. }
  88660. }
  88661. // Lights
  88662. serializationObject.lights = [];
  88663. var index;
  88664. var light;
  88665. for (index = 0; index < scene.lights.length; index++) {
  88666. light = scene.lights[index];
  88667. if (!light.doNotSerialize) {
  88668. serializationObject.lights.push(light.serialize());
  88669. }
  88670. }
  88671. // Cameras
  88672. serializationObject.cameras = [];
  88673. for (index = 0; index < scene.cameras.length; index++) {
  88674. var camera = scene.cameras[index];
  88675. if (!camera.doNotSerialize) {
  88676. serializationObject.cameras.push(camera.serialize());
  88677. }
  88678. }
  88679. if (scene.activeCamera) {
  88680. serializationObject.activeCameraID = scene.activeCamera.id;
  88681. }
  88682. // Animations
  88683. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88684. // Materials
  88685. serializationObject.materials = [];
  88686. serializationObject.multiMaterials = [];
  88687. var material;
  88688. for (index = 0; index < scene.materials.length; index++) {
  88689. material = scene.materials[index];
  88690. if (!material.doNotSerialize) {
  88691. serializationObject.materials.push(material.serialize());
  88692. }
  88693. }
  88694. // MultiMaterials
  88695. serializationObject.multiMaterials = [];
  88696. for (index = 0; index < scene.multiMaterials.length; index++) {
  88697. var multiMaterial = scene.multiMaterials[index];
  88698. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88699. }
  88700. // Environment texture
  88701. if (scene.environmentTexture) {
  88702. serializationObject.environmentTexture = scene.environmentTexture.name;
  88703. }
  88704. // Skeletons
  88705. serializationObject.skeletons = [];
  88706. for (index = 0; index < scene.skeletons.length; index++) {
  88707. var skeleton = scene.skeletons[index];
  88708. if (!skeleton.doNotSerialize) {
  88709. serializationObject.skeletons.push(skeleton.serialize());
  88710. }
  88711. }
  88712. // Transform nodes
  88713. serializationObject.transformNodes = [];
  88714. for (index = 0; index < scene.transformNodes.length; index++) {
  88715. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88716. }
  88717. // Geometries
  88718. serializationObject.geometries = {};
  88719. serializationObject.geometries.boxes = [];
  88720. serializationObject.geometries.spheres = [];
  88721. serializationObject.geometries.cylinders = [];
  88722. serializationObject.geometries.toruses = [];
  88723. serializationObject.geometries.grounds = [];
  88724. serializationObject.geometries.planes = [];
  88725. serializationObject.geometries.torusKnots = [];
  88726. serializationObject.geometries.vertexData = [];
  88727. serializedGeometries = [];
  88728. var geometries = scene.getGeometries();
  88729. for (index = 0; index < geometries.length; index++) {
  88730. var geometry = geometries[index];
  88731. if (geometry.isReady()) {
  88732. serializeGeometry(geometry, serializationObject.geometries);
  88733. }
  88734. }
  88735. // Meshes
  88736. serializationObject.meshes = [];
  88737. for (index = 0; index < scene.meshes.length; index++) {
  88738. var abstractMesh = scene.meshes[index];
  88739. if (abstractMesh instanceof BABYLON.Mesh) {
  88740. var mesh = abstractMesh;
  88741. if (!mesh.doNotSerialize) {
  88742. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88743. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88744. }
  88745. }
  88746. }
  88747. }
  88748. // Particles Systems
  88749. serializationObject.particleSystems = [];
  88750. for (index = 0; index < scene.particleSystems.length; index++) {
  88751. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88752. }
  88753. // Lens flares
  88754. serializationObject.lensFlareSystems = [];
  88755. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88756. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88757. }
  88758. // Shadows
  88759. serializationObject.shadowGenerators = [];
  88760. for (index = 0; index < scene.lights.length; index++) {
  88761. light = scene.lights[index];
  88762. var shadowGenerator = light.getShadowGenerator();
  88763. if (shadowGenerator) {
  88764. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88765. }
  88766. }
  88767. // Action Manager
  88768. if (scene.actionManager) {
  88769. serializationObject.actions = scene.actionManager.serialize("scene");
  88770. }
  88771. // Audio
  88772. serializationObject.sounds = [];
  88773. for (index = 0; index < scene.soundTracks.length; index++) {
  88774. var soundtrack = scene.soundTracks[index];
  88775. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88776. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88777. }
  88778. }
  88779. return serializationObject;
  88780. };
  88781. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88782. if (withParents === void 0) { withParents = false; }
  88783. if (withChildren === void 0) { withChildren = false; }
  88784. var serializationObject = {};
  88785. SceneSerializer.ClearCache();
  88786. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88787. if (withParents || withChildren) {
  88788. //deliberate for loop! not for each, appended should be processed as well.
  88789. for (var i = 0; i < toSerialize.length; ++i) {
  88790. if (withChildren) {
  88791. toSerialize[i].getDescendants().forEach(function (node) {
  88792. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88793. toSerialize.push(node);
  88794. }
  88795. });
  88796. }
  88797. //make sure the array doesn't contain the object already
  88798. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88799. toSerialize.push(toSerialize[i].parent);
  88800. }
  88801. }
  88802. }
  88803. toSerialize.forEach(function (mesh) {
  88804. finalizeSingleMesh(mesh, serializationObject);
  88805. });
  88806. return serializationObject;
  88807. };
  88808. return SceneSerializer;
  88809. }());
  88810. BABYLON.SceneSerializer = SceneSerializer;
  88811. })(BABYLON || (BABYLON = {}));
  88812. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88813. "use strict";
  88814. var BABYLON;
  88815. (function (BABYLON) {
  88816. var ReflectionProbe = /** @class */ (function () {
  88817. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88818. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88819. var _this = this;
  88820. this.name = name;
  88821. this._viewMatrix = BABYLON.Matrix.Identity();
  88822. this._target = BABYLON.Vector3.Zero();
  88823. this._add = BABYLON.Vector3.Zero();
  88824. this._invertYAxis = false;
  88825. this.position = BABYLON.Vector3.Zero();
  88826. this._scene = scene;
  88827. this._scene.reflectionProbes.push(this);
  88828. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88829. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88830. switch (faceIndex) {
  88831. case 0:
  88832. _this._add.copyFromFloats(1, 0, 0);
  88833. break;
  88834. case 1:
  88835. _this._add.copyFromFloats(-1, 0, 0);
  88836. break;
  88837. case 2:
  88838. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  88839. break;
  88840. case 3:
  88841. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  88842. break;
  88843. case 4:
  88844. _this._add.copyFromFloats(0, 0, 1);
  88845. break;
  88846. case 5:
  88847. _this._add.copyFromFloats(0, 0, -1);
  88848. break;
  88849. }
  88850. if (_this._attachedMesh) {
  88851. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  88852. }
  88853. _this.position.addToRef(_this._add, _this._target);
  88854. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  88855. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  88856. scene._forcedViewPosition = _this.position;
  88857. });
  88858. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  88859. scene._forcedViewPosition = null;
  88860. scene.updateTransformMatrix(true);
  88861. });
  88862. if (scene.activeCamera) {
  88863. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88864. }
  88865. }
  88866. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  88867. get: function () {
  88868. return this._renderTargetTexture.samples;
  88869. },
  88870. set: function (value) {
  88871. this._renderTargetTexture.samples = value;
  88872. },
  88873. enumerable: true,
  88874. configurable: true
  88875. });
  88876. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  88877. get: function () {
  88878. return this._renderTargetTexture.refreshRate;
  88879. },
  88880. set: function (value) {
  88881. this._renderTargetTexture.refreshRate = value;
  88882. },
  88883. enumerable: true,
  88884. configurable: true
  88885. });
  88886. ReflectionProbe.prototype.getScene = function () {
  88887. return this._scene;
  88888. };
  88889. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  88890. get: function () {
  88891. return this._renderTargetTexture;
  88892. },
  88893. enumerable: true,
  88894. configurable: true
  88895. });
  88896. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  88897. get: function () {
  88898. return this._renderTargetTexture.renderList;
  88899. },
  88900. enumerable: true,
  88901. configurable: true
  88902. });
  88903. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  88904. this._attachedMesh = mesh;
  88905. };
  88906. /**
  88907. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  88908. *
  88909. * @param renderingGroupId The rendering group id corresponding to its index
  88910. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  88911. */
  88912. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  88913. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  88914. };
  88915. ReflectionProbe.prototype.dispose = function () {
  88916. var index = this._scene.reflectionProbes.indexOf(this);
  88917. if (index !== -1) {
  88918. // Remove from the scene if found
  88919. this._scene.reflectionProbes.splice(index, 1);
  88920. }
  88921. if (this._renderTargetTexture) {
  88922. this._renderTargetTexture.dispose();
  88923. this._renderTargetTexture = null;
  88924. }
  88925. };
  88926. return ReflectionProbe;
  88927. }());
  88928. BABYLON.ReflectionProbe = ReflectionProbe;
  88929. })(BABYLON || (BABYLON = {}));
  88930. //# sourceMappingURL=babylon.reflectionProbe.js.map
  88931. "use strict";
  88932. var BABYLON;
  88933. (function (BABYLON) {
  88934. var Layer = /** @class */ (function () {
  88935. function Layer(name, imgUrl, scene, isBackground, color) {
  88936. this.name = name;
  88937. this.scale = new BABYLON.Vector2(1, 1);
  88938. this.offset = new BABYLON.Vector2(0, 0);
  88939. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  88940. this.layerMask = 0x0FFFFFFF;
  88941. this._vertexBuffers = {};
  88942. // Events
  88943. /**
  88944. * An event triggered when the layer is disposed.
  88945. * @type {BABYLON.Observable}
  88946. */
  88947. this.onDisposeObservable = new BABYLON.Observable();
  88948. /**
  88949. * An event triggered before rendering the scene
  88950. * @type {BABYLON.Observable}
  88951. */
  88952. this.onBeforeRenderObservable = new BABYLON.Observable();
  88953. /**
  88954. * An event triggered after rendering the scene
  88955. * @type {BABYLON.Observable}
  88956. */
  88957. this.onAfterRenderObservable = new BABYLON.Observable();
  88958. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  88959. this.isBackground = isBackground === undefined ? true : isBackground;
  88960. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  88961. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  88962. this._scene.layers.push(this);
  88963. var engine = this._scene.getEngine();
  88964. // VBO
  88965. var vertices = [];
  88966. vertices.push(1, 1);
  88967. vertices.push(-1, 1);
  88968. vertices.push(-1, -1);
  88969. vertices.push(1, -1);
  88970. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88971. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88972. this._createIndexBuffer();
  88973. // Effects
  88974. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  88975. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  88976. }
  88977. Object.defineProperty(Layer.prototype, "onDispose", {
  88978. set: function (callback) {
  88979. if (this._onDisposeObserver) {
  88980. this.onDisposeObservable.remove(this._onDisposeObserver);
  88981. }
  88982. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88983. },
  88984. enumerable: true,
  88985. configurable: true
  88986. });
  88987. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  88988. set: function (callback) {
  88989. if (this._onBeforeRenderObserver) {
  88990. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  88991. }
  88992. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  88993. },
  88994. enumerable: true,
  88995. configurable: true
  88996. });
  88997. Object.defineProperty(Layer.prototype, "onAfterRender", {
  88998. set: function (callback) {
  88999. if (this._onAfterRenderObserver) {
  89000. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89001. }
  89002. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  89003. },
  89004. enumerable: true,
  89005. configurable: true
  89006. });
  89007. Layer.prototype._createIndexBuffer = function () {
  89008. var engine = this._scene.getEngine();
  89009. // Indices
  89010. var indices = [];
  89011. indices.push(0);
  89012. indices.push(1);
  89013. indices.push(2);
  89014. indices.push(0);
  89015. indices.push(2);
  89016. indices.push(3);
  89017. this._indexBuffer = engine.createIndexBuffer(indices);
  89018. };
  89019. Layer.prototype._rebuild = function () {
  89020. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89021. if (vb) {
  89022. vb._rebuild();
  89023. }
  89024. this._createIndexBuffer();
  89025. };
  89026. Layer.prototype.render = function () {
  89027. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  89028. // Check
  89029. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  89030. return;
  89031. var engine = this._scene.getEngine();
  89032. this.onBeforeRenderObservable.notifyObservers(this);
  89033. // Render
  89034. engine.enableEffect(currentEffect);
  89035. engine.setState(false);
  89036. // Texture
  89037. currentEffect.setTexture("textureSampler", this.texture);
  89038. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  89039. // Color
  89040. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  89041. // Scale / offset
  89042. currentEffect.setVector2("offset", this.offset);
  89043. currentEffect.setVector2("scale", this.scale);
  89044. // VBOs
  89045. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  89046. // Draw order
  89047. if (!this.alphaTest) {
  89048. engine.setAlphaMode(this.alphaBlendingMode);
  89049. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89050. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89051. }
  89052. else {
  89053. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89054. }
  89055. this.onAfterRenderObservable.notifyObservers(this);
  89056. };
  89057. Layer.prototype.dispose = function () {
  89058. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89059. if (vertexBuffer) {
  89060. vertexBuffer.dispose();
  89061. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89062. }
  89063. if (this._indexBuffer) {
  89064. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89065. this._indexBuffer = null;
  89066. }
  89067. if (this.texture) {
  89068. this.texture.dispose();
  89069. this.texture = null;
  89070. }
  89071. // Remove from scene
  89072. var index = this._scene.layers.indexOf(this);
  89073. this._scene.layers.splice(index, 1);
  89074. // Callback
  89075. this.onDisposeObservable.notifyObservers(this);
  89076. this.onDisposeObservable.clear();
  89077. this.onAfterRenderObservable.clear();
  89078. this.onBeforeRenderObservable.clear();
  89079. };
  89080. return Layer;
  89081. }());
  89082. BABYLON.Layer = Layer;
  89083. })(BABYLON || (BABYLON = {}));
  89084. //# sourceMappingURL=babylon.layer.js.map
  89085. "use strict";
  89086. var BABYLON;
  89087. (function (BABYLON) {
  89088. var TextureTools = /** @class */ (function () {
  89089. function TextureTools() {
  89090. }
  89091. /**
  89092. * Uses the GPU to create a copy texture rescaled at a given size
  89093. * @param texture Texture to copy from
  89094. * @param width Desired width
  89095. * @param height Desired height
  89096. * @return Generated texture
  89097. */
  89098. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  89099. if (useBilinearMode === void 0) { useBilinearMode = true; }
  89100. var scene = texture.getScene();
  89101. var engine = scene.getEngine();
  89102. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  89103. rtt.wrapU = texture.wrapU;
  89104. rtt.wrapV = texture.wrapV;
  89105. rtt.uOffset = texture.uOffset;
  89106. rtt.vOffset = texture.vOffset;
  89107. rtt.uScale = texture.uScale;
  89108. rtt.vScale = texture.vScale;
  89109. rtt.uAng = texture.uAng;
  89110. rtt.vAng = texture.vAng;
  89111. rtt.wAng = texture.wAng;
  89112. rtt.coordinatesIndex = texture.coordinatesIndex;
  89113. rtt.level = texture.level;
  89114. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  89115. rtt._texture.isReady = false;
  89116. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89117. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89118. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89119. passPostProcess.getEffect().executeWhenCompiled(function () {
  89120. passPostProcess.onApply = function (effect) {
  89121. effect.setTexture("textureSampler", texture);
  89122. };
  89123. var internalTexture = rtt.getInternalTexture();
  89124. if (internalTexture) {
  89125. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  89126. engine.unBindFramebuffer(internalTexture);
  89127. rtt.disposeFramebufferObjects();
  89128. passPostProcess.dispose();
  89129. internalTexture.isReady = true;
  89130. }
  89131. });
  89132. return rtt;
  89133. };
  89134. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  89135. if (!scene._environmentBRDFTexture) {
  89136. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89137. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89138. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89139. scene._environmentBRDFTexture = texture;
  89140. }
  89141. return scene._environmentBRDFTexture;
  89142. };
  89143. 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=";
  89144. return TextureTools;
  89145. }());
  89146. BABYLON.TextureTools = TextureTools;
  89147. })(BABYLON || (BABYLON = {}));
  89148. //# sourceMappingURL=babylon.textureTools.js.map
  89149. "use strict";
  89150. var BABYLON;
  89151. (function (BABYLON) {
  89152. var FramingBehavior = /** @class */ (function () {
  89153. function FramingBehavior() {
  89154. this._mode = FramingBehavior.FitFrustumSidesMode;
  89155. this._radiusScale = 1.0;
  89156. this._positionScale = 0.5;
  89157. this._defaultElevation = 0.3;
  89158. this._elevationReturnTime = 1500;
  89159. this._elevationReturnWaitTime = 1000;
  89160. this._zoomStopsAnimation = false;
  89161. this._framingTime = 1500;
  89162. this._isPointerDown = false;
  89163. this._lastInteractionTime = -Infinity;
  89164. // Framing control
  89165. this._animatables = new Array();
  89166. this._betaIsAnimating = false;
  89167. }
  89168. Object.defineProperty(FramingBehavior.prototype, "name", {
  89169. get: function () {
  89170. return "Framing";
  89171. },
  89172. enumerable: true,
  89173. configurable: true
  89174. });
  89175. Object.defineProperty(FramingBehavior.prototype, "mode", {
  89176. /**
  89177. * Gets current mode used by the behavior.
  89178. */
  89179. get: function () {
  89180. return this._mode;
  89181. },
  89182. /**
  89183. * Sets the current mode used by the behavior
  89184. */
  89185. set: function (mode) {
  89186. this._mode = mode;
  89187. },
  89188. enumerable: true,
  89189. configurable: true
  89190. });
  89191. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  89192. /**
  89193. * Gets the scale applied to the radius
  89194. */
  89195. get: function () {
  89196. return this._radiusScale;
  89197. },
  89198. /**
  89199. * Sets the scale applied to the radius (1 by default)
  89200. */
  89201. set: function (radius) {
  89202. this._radiusScale = radius;
  89203. },
  89204. enumerable: true,
  89205. configurable: true
  89206. });
  89207. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  89208. /**
  89209. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89210. */
  89211. get: function () {
  89212. return this._positionScale;
  89213. },
  89214. /**
  89215. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89216. */
  89217. set: function (scale) {
  89218. this._positionScale = scale;
  89219. },
  89220. enumerable: true,
  89221. configurable: true
  89222. });
  89223. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  89224. /**
  89225. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89226. * behaviour is triggered, in radians.
  89227. */
  89228. get: function () {
  89229. return this._defaultElevation;
  89230. },
  89231. /**
  89232. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89233. * behaviour is triggered, in radians.
  89234. */
  89235. set: function (elevation) {
  89236. this._defaultElevation = elevation;
  89237. },
  89238. enumerable: true,
  89239. configurable: true
  89240. });
  89241. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  89242. /**
  89243. * Gets the time (in milliseconds) taken to return to the default beta position.
  89244. * Negative value indicates camera should not return to default.
  89245. */
  89246. get: function () {
  89247. return this._elevationReturnTime;
  89248. },
  89249. /**
  89250. * Sets the time (in milliseconds) taken to return to the default beta position.
  89251. * Negative value indicates camera should not return to default.
  89252. */
  89253. set: function (speed) {
  89254. this._elevationReturnTime = speed;
  89255. },
  89256. enumerable: true,
  89257. configurable: true
  89258. });
  89259. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  89260. /**
  89261. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89262. */
  89263. get: function () {
  89264. return this._elevationReturnWaitTime;
  89265. },
  89266. /**
  89267. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89268. */
  89269. set: function (time) {
  89270. this._elevationReturnWaitTime = time;
  89271. },
  89272. enumerable: true,
  89273. configurable: true
  89274. });
  89275. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  89276. /**
  89277. * Gets the flag that indicates if user zooming should stop animation.
  89278. */
  89279. get: function () {
  89280. return this._zoomStopsAnimation;
  89281. },
  89282. /**
  89283. * Sets the flag that indicates if user zooming should stop animation.
  89284. */
  89285. set: function (flag) {
  89286. this._zoomStopsAnimation = flag;
  89287. },
  89288. enumerable: true,
  89289. configurable: true
  89290. });
  89291. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  89292. /**
  89293. * Gets the transition time when framing the mesh, in milliseconds
  89294. */
  89295. get: function () {
  89296. return this._framingTime;
  89297. },
  89298. /**
  89299. * Sets the transition time when framing the mesh, in milliseconds
  89300. */
  89301. set: function (time) {
  89302. this._framingTime = time;
  89303. },
  89304. enumerable: true,
  89305. configurable: true
  89306. });
  89307. FramingBehavior.prototype.init = function () {
  89308. // Do notihng
  89309. };
  89310. FramingBehavior.prototype.attach = function (camera) {
  89311. var _this = this;
  89312. this._attachedCamera = camera;
  89313. var scene = this._attachedCamera.getScene();
  89314. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  89315. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89316. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89317. _this._isPointerDown = true;
  89318. return;
  89319. }
  89320. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89321. _this._isPointerDown = false;
  89322. }
  89323. });
  89324. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89325. if (mesh) {
  89326. _this.zoomOnMesh(mesh);
  89327. }
  89328. });
  89329. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89330. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89331. _this._applyUserInteraction();
  89332. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  89333. // back to the default position after a given timeout
  89334. _this._maintainCameraAboveGround();
  89335. });
  89336. };
  89337. FramingBehavior.prototype.detach = function () {
  89338. if (!this._attachedCamera) {
  89339. return;
  89340. }
  89341. var scene = this._attachedCamera.getScene();
  89342. if (this._onPrePointerObservableObserver) {
  89343. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89344. }
  89345. if (this._onAfterCheckInputsObserver) {
  89346. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89347. }
  89348. if (this._onMeshTargetChangedObserver) {
  89349. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89350. }
  89351. this._attachedCamera = null;
  89352. };
  89353. /**
  89354. * Targets the given mesh and updates zoom level accordingly.
  89355. * @param mesh The mesh to target.
  89356. * @param radius Optional. If a cached radius position already exists, overrides default.
  89357. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89358. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89359. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89360. */
  89361. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89362. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89363. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89364. mesh.computeWorldMatrix(true);
  89365. var boundingBox = mesh.getBoundingInfo().boundingBox;
  89366. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  89367. };
  89368. /**
  89369. * Targets the given mesh with its children and updates zoom level accordingly.
  89370. * @param mesh The mesh to target.
  89371. * @param radius Optional. If a cached radius position already exists, overrides default.
  89372. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89373. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89374. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89375. */
  89376. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89377. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89378. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89379. mesh.computeWorldMatrix(true);
  89380. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  89381. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  89382. };
  89383. /**
  89384. * Targets the given meshes with their children and updates zoom level accordingly.
  89385. * @param meshes The mesh to target.
  89386. * @param radius Optional. If a cached radius position already exists, overrides default.
  89387. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89388. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89389. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89390. */
  89391. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89392. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89393. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89394. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89395. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89396. for (var i = 0; i < meshes.length; i++) {
  89397. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89398. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89399. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89400. }
  89401. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89402. };
  89403. /**
  89404. * Targets the given mesh and updates zoom level accordingly.
  89405. * @param mesh The mesh to target.
  89406. * @param radius Optional. If a cached radius position already exists, overrides default.
  89407. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89408. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89409. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89410. */
  89411. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89412. var _this = this;
  89413. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89414. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89415. var zoomTarget;
  89416. if (!this._attachedCamera) {
  89417. return;
  89418. }
  89419. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89420. var bottom = minimumWorld.y;
  89421. var top = maximumWorld.y;
  89422. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89423. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89424. if (focusOnOriginXZ) {
  89425. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89426. }
  89427. else {
  89428. var centerWorld = minimumWorld.add(radiusWorld);
  89429. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89430. }
  89431. if (!this._vectorTransition) {
  89432. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89433. }
  89434. this._betaIsAnimating = true;
  89435. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89436. if (animatable) {
  89437. this._animatables.push(animatable);
  89438. }
  89439. // sets the radius and lower radius bounds
  89440. // Small delta ensures camera is not always at lower zoom limit.
  89441. var radius = 0;
  89442. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89443. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89444. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89445. radius = position;
  89446. }
  89447. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89448. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89449. if (this._attachedCamera.lowerRadiusLimit === null) {
  89450. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89451. }
  89452. }
  89453. // Set sensibilities
  89454. var extend = maximumWorld.subtract(minimumWorld).length();
  89455. this._attachedCamera.panningSensibility = 5000 / extend;
  89456. this._attachedCamera.wheelPrecision = 100 / radius;
  89457. // transition to new radius
  89458. if (!this._radiusTransition) {
  89459. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89460. }
  89461. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89462. _this.stopAllAnimations();
  89463. if (onAnimationEnd) {
  89464. onAnimationEnd();
  89465. }
  89466. if (_this._attachedCamera) {
  89467. _this._attachedCamera.storeState();
  89468. }
  89469. });
  89470. if (animatable) {
  89471. this._animatables.push(animatable);
  89472. }
  89473. };
  89474. /**
  89475. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89476. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89477. * frustum width.
  89478. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89479. * to fully enclose the mesh in the viewing frustum.
  89480. */
  89481. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89482. var size = maximumWorld.subtract(minimumWorld);
  89483. var boxVectorGlobalDiagonal = size.length();
  89484. var frustumSlope = this._getFrustumSlope();
  89485. // Formula for setting distance
  89486. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89487. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89488. // Horizon distance
  89489. var radius = radiusWithoutFraming * this._radiusScale;
  89490. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89491. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89492. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89493. var camera = this._attachedCamera;
  89494. if (!camera) {
  89495. return 0;
  89496. }
  89497. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89498. // Don't exceed the requested limit
  89499. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89500. }
  89501. // Don't exceed the upper radius limit
  89502. if (camera.upperRadiusLimit) {
  89503. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89504. }
  89505. return distance;
  89506. };
  89507. /**
  89508. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89509. * is automatically returned to its default position (expected to be above ground plane).
  89510. */
  89511. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89512. var _this = this;
  89513. if (this._elevationReturnTime < 0) {
  89514. return;
  89515. }
  89516. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89517. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89518. var limitBeta = Math.PI * 0.5;
  89519. // Bring the camera back up if below the ground plane
  89520. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89521. this._betaIsAnimating = true;
  89522. //Transition to new position
  89523. this.stopAllAnimations();
  89524. if (!this._betaTransition) {
  89525. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89526. }
  89527. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89528. _this._clearAnimationLocks();
  89529. _this.stopAllAnimations();
  89530. });
  89531. if (animatabe) {
  89532. this._animatables.push(animatabe);
  89533. }
  89534. }
  89535. };
  89536. /**
  89537. * Returns the frustum slope based on the canvas ratio and camera FOV
  89538. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89539. */
  89540. FramingBehavior.prototype._getFrustumSlope = function () {
  89541. // Calculate the viewport ratio
  89542. // Aspect Ratio is Height/Width.
  89543. var camera = this._attachedCamera;
  89544. if (!camera) {
  89545. return BABYLON.Vector2.Zero();
  89546. }
  89547. var engine = camera.getScene().getEngine();
  89548. var aspectRatio = engine.getAspectRatio(camera);
  89549. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89550. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89551. var frustumSlopeY = Math.tan(camera.fov / 2);
  89552. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89553. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89554. // along the forward vector.
  89555. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89556. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89557. };
  89558. /**
  89559. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89560. */
  89561. FramingBehavior.prototype._clearAnimationLocks = function () {
  89562. this._betaIsAnimating = false;
  89563. };
  89564. /**
  89565. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89566. */
  89567. FramingBehavior.prototype._applyUserInteraction = function () {
  89568. if (this.isUserIsMoving) {
  89569. this._lastInteractionTime = BABYLON.Tools.Now;
  89570. this.stopAllAnimations();
  89571. this._clearAnimationLocks();
  89572. }
  89573. };
  89574. /**
  89575. * Stops and removes all animations that have been applied to the camera
  89576. */
  89577. FramingBehavior.prototype.stopAllAnimations = function () {
  89578. if (this._attachedCamera) {
  89579. this._attachedCamera.animations = [];
  89580. }
  89581. while (this._animatables.length) {
  89582. if (this._animatables[0]) {
  89583. this._animatables[0].onAnimationEnd = null;
  89584. this._animatables[0].stop();
  89585. }
  89586. this._animatables.shift();
  89587. }
  89588. };
  89589. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89590. /**
  89591. * Gets a value indicating if the user is moving the camera
  89592. */
  89593. get: function () {
  89594. if (!this._attachedCamera) {
  89595. return false;
  89596. }
  89597. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89598. this._attachedCamera.inertialBetaOffset !== 0 ||
  89599. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89600. this._attachedCamera.inertialPanningX !== 0 ||
  89601. this._attachedCamera.inertialPanningY !== 0 ||
  89602. this._isPointerDown;
  89603. },
  89604. enumerable: true,
  89605. configurable: true
  89606. });
  89607. /**
  89608. * The easing function used by animations
  89609. */
  89610. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89611. /**
  89612. * The easing mode used by animations
  89613. */
  89614. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89615. // Statics
  89616. /**
  89617. * The camera can move all the way towards the mesh.
  89618. */
  89619. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89620. /**
  89621. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89622. */
  89623. FramingBehavior.FitFrustumSidesMode = 1;
  89624. return FramingBehavior;
  89625. }());
  89626. BABYLON.FramingBehavior = FramingBehavior;
  89627. })(BABYLON || (BABYLON = {}));
  89628. //# sourceMappingURL=babylon.framingBehavior.js.map
  89629. "use strict";
  89630. var BABYLON;
  89631. (function (BABYLON) {
  89632. /**
  89633. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89634. */
  89635. var BouncingBehavior = /** @class */ (function () {
  89636. function BouncingBehavior() {
  89637. /**
  89638. * The duration of the animation, in milliseconds
  89639. */
  89640. this.transitionDuration = 450;
  89641. /**
  89642. * Length of the distance animated by the transition when lower radius is reached
  89643. */
  89644. this.lowerRadiusTransitionRange = 2;
  89645. /**
  89646. * Length of the distance animated by the transition when upper radius is reached
  89647. */
  89648. this.upperRadiusTransitionRange = -2;
  89649. this._autoTransitionRange = false;
  89650. // Animations
  89651. this._radiusIsAnimating = false;
  89652. this._radiusBounceTransition = null;
  89653. this._animatables = new Array();
  89654. }
  89655. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89656. get: function () {
  89657. return "Bouncing";
  89658. },
  89659. enumerable: true,
  89660. configurable: true
  89661. });
  89662. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89663. /**
  89664. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89665. */
  89666. get: function () {
  89667. return this._autoTransitionRange;
  89668. },
  89669. /**
  89670. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89671. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89672. */
  89673. set: function (value) {
  89674. var _this = this;
  89675. if (this._autoTransitionRange === value) {
  89676. return;
  89677. }
  89678. this._autoTransitionRange = value;
  89679. var camera = this._attachedCamera;
  89680. if (!camera) {
  89681. return;
  89682. }
  89683. if (value) {
  89684. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89685. if (!mesh) {
  89686. return;
  89687. }
  89688. mesh.computeWorldMatrix(true);
  89689. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89690. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89691. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89692. });
  89693. }
  89694. else if (this._onMeshTargetChangedObserver) {
  89695. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89696. }
  89697. },
  89698. enumerable: true,
  89699. configurable: true
  89700. });
  89701. BouncingBehavior.prototype.init = function () {
  89702. // Do notihng
  89703. };
  89704. BouncingBehavior.prototype.attach = function (camera) {
  89705. var _this = this;
  89706. this._attachedCamera = camera;
  89707. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89708. if (!_this._attachedCamera) {
  89709. return;
  89710. }
  89711. // Add the bounce animation to the lower radius limit
  89712. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89713. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89714. }
  89715. // Add the bounce animation to the upper radius limit
  89716. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89717. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89718. }
  89719. });
  89720. };
  89721. BouncingBehavior.prototype.detach = function () {
  89722. if (!this._attachedCamera) {
  89723. return;
  89724. }
  89725. if (this._onAfterCheckInputsObserver) {
  89726. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89727. }
  89728. if (this._onMeshTargetChangedObserver) {
  89729. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89730. }
  89731. this._attachedCamera = null;
  89732. };
  89733. /**
  89734. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89735. * @param radiusLimit The limit to check against.
  89736. * @return Bool to indicate if at limit.
  89737. */
  89738. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89739. if (!this._attachedCamera) {
  89740. return false;
  89741. }
  89742. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89743. return true;
  89744. }
  89745. return false;
  89746. };
  89747. /**
  89748. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89749. * @param radiusDelta The delta by which to animate to. Can be negative.
  89750. */
  89751. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89752. var _this = this;
  89753. if (!this._attachedCamera) {
  89754. return;
  89755. }
  89756. if (!this._radiusBounceTransition) {
  89757. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89758. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89759. }
  89760. // Prevent zoom until bounce has completed
  89761. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89762. this._attachedCamera.wheelPrecision = Infinity;
  89763. this._attachedCamera.inertialRadiusOffset = 0;
  89764. // Animate to the radius limit
  89765. this.stopAllAnimations();
  89766. this._radiusIsAnimating = true;
  89767. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89768. if (animatable) {
  89769. this._animatables.push(animatable);
  89770. }
  89771. };
  89772. /**
  89773. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89774. */
  89775. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89776. this._radiusIsAnimating = false;
  89777. if (this._attachedCamera) {
  89778. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89779. }
  89780. };
  89781. /**
  89782. * Stops and removes all animations that have been applied to the camera
  89783. */
  89784. BouncingBehavior.prototype.stopAllAnimations = function () {
  89785. if (this._attachedCamera) {
  89786. this._attachedCamera.animations = [];
  89787. }
  89788. while (this._animatables.length) {
  89789. this._animatables[0].onAnimationEnd = null;
  89790. this._animatables[0].stop();
  89791. this._animatables.shift();
  89792. }
  89793. };
  89794. /**
  89795. * The easing function used by animations
  89796. */
  89797. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89798. /**
  89799. * The easing mode used by animations
  89800. */
  89801. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89802. return BouncingBehavior;
  89803. }());
  89804. BABYLON.BouncingBehavior = BouncingBehavior;
  89805. })(BABYLON || (BABYLON = {}));
  89806. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89807. "use strict";
  89808. var BABYLON;
  89809. (function (BABYLON) {
  89810. var AutoRotationBehavior = /** @class */ (function () {
  89811. function AutoRotationBehavior() {
  89812. this._zoomStopsAnimation = false;
  89813. this._idleRotationSpeed = 0.05;
  89814. this._idleRotationWaitTime = 2000;
  89815. this._idleRotationSpinupTime = 2000;
  89816. this._isPointerDown = false;
  89817. this._lastFrameTime = null;
  89818. this._lastInteractionTime = -Infinity;
  89819. this._cameraRotationSpeed = 0;
  89820. this._lastFrameRadius = 0;
  89821. }
  89822. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89823. get: function () {
  89824. return "AutoRotation";
  89825. },
  89826. enumerable: true,
  89827. configurable: true
  89828. });
  89829. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89830. /**
  89831. * Gets the flag that indicates if user zooming should stop animation.
  89832. */
  89833. get: function () {
  89834. return this._zoomStopsAnimation;
  89835. },
  89836. /**
  89837. * Sets the flag that indicates if user zooming should stop animation.
  89838. */
  89839. set: function (flag) {
  89840. this._zoomStopsAnimation = flag;
  89841. },
  89842. enumerable: true,
  89843. configurable: true
  89844. });
  89845. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  89846. /**
  89847. * Gets the default speed at which the camera rotates around the model.
  89848. */
  89849. get: function () {
  89850. return this._idleRotationSpeed;
  89851. },
  89852. /**
  89853. * Sets the default speed at which the camera rotates around the model.
  89854. */
  89855. set: function (speed) {
  89856. this._idleRotationSpeed = speed;
  89857. },
  89858. enumerable: true,
  89859. configurable: true
  89860. });
  89861. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  89862. /**
  89863. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  89864. */
  89865. get: function () {
  89866. return this._idleRotationWaitTime;
  89867. },
  89868. /**
  89869. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  89870. */
  89871. set: function (time) {
  89872. this._idleRotationWaitTime = time;
  89873. },
  89874. enumerable: true,
  89875. configurable: true
  89876. });
  89877. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  89878. /**
  89879. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89880. */
  89881. get: function () {
  89882. return this._idleRotationSpinupTime;
  89883. },
  89884. /**
  89885. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89886. */
  89887. set: function (time) {
  89888. this._idleRotationSpinupTime = time;
  89889. },
  89890. enumerable: true,
  89891. configurable: true
  89892. });
  89893. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  89894. /**
  89895. * Gets a value indicating if the camera is currently rotating because of this behavior
  89896. */
  89897. get: function () {
  89898. return Math.abs(this._cameraRotationSpeed) > 0;
  89899. },
  89900. enumerable: true,
  89901. configurable: true
  89902. });
  89903. AutoRotationBehavior.prototype.init = function () {
  89904. // Do notihng
  89905. };
  89906. AutoRotationBehavior.prototype.attach = function (camera) {
  89907. var _this = this;
  89908. this._attachedCamera = camera;
  89909. var scene = this._attachedCamera.getScene();
  89910. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89911. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89912. _this._isPointerDown = true;
  89913. return;
  89914. }
  89915. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89916. _this._isPointerDown = false;
  89917. }
  89918. });
  89919. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89920. var now = BABYLON.Tools.Now;
  89921. var dt = 0;
  89922. if (_this._lastFrameTime != null) {
  89923. dt = now - _this._lastFrameTime;
  89924. }
  89925. _this._lastFrameTime = now;
  89926. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89927. _this._applyUserInteraction();
  89928. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  89929. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  89930. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  89931. // Step camera rotation by rotation speed
  89932. if (_this._attachedCamera) {
  89933. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  89934. }
  89935. });
  89936. };
  89937. AutoRotationBehavior.prototype.detach = function () {
  89938. if (!this._attachedCamera) {
  89939. return;
  89940. }
  89941. var scene = this._attachedCamera.getScene();
  89942. if (this._onPrePointerObservableObserver) {
  89943. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89944. }
  89945. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89946. this._attachedCamera = null;
  89947. };
  89948. /**
  89949. * Returns true if user is scrolling.
  89950. * @return true if user is scrolling.
  89951. */
  89952. AutoRotationBehavior.prototype._userIsZooming = function () {
  89953. if (!this._attachedCamera) {
  89954. return false;
  89955. }
  89956. return this._attachedCamera.inertialRadiusOffset !== 0;
  89957. };
  89958. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  89959. if (!this._attachedCamera) {
  89960. return false;
  89961. }
  89962. var zoomHasHitLimit = false;
  89963. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  89964. zoomHasHitLimit = true;
  89965. }
  89966. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  89967. this._lastFrameRadius = this._attachedCamera.radius;
  89968. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  89969. };
  89970. /**
  89971. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89972. */
  89973. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  89974. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  89975. this._lastInteractionTime = BABYLON.Tools.Now;
  89976. }
  89977. };
  89978. // Tools
  89979. AutoRotationBehavior.prototype._userIsMoving = function () {
  89980. if (!this._attachedCamera) {
  89981. return false;
  89982. }
  89983. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89984. this._attachedCamera.inertialBetaOffset !== 0 ||
  89985. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89986. this._attachedCamera.inertialPanningX !== 0 ||
  89987. this._attachedCamera.inertialPanningY !== 0 ||
  89988. this._isPointerDown;
  89989. };
  89990. return AutoRotationBehavior;
  89991. }());
  89992. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  89993. })(BABYLON || (BABYLON = {}));
  89994. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  89995. "use strict";
  89996. var BABYLON;
  89997. (function (BABYLON) {
  89998. var NullEngineOptions = /** @class */ (function () {
  89999. function NullEngineOptions() {
  90000. this.renderWidth = 512;
  90001. this.renderHeight = 256;
  90002. this.textureSize = 512;
  90003. this.deterministicLockstep = false;
  90004. this.lockstepMaxSteps = 4;
  90005. }
  90006. return NullEngineOptions;
  90007. }());
  90008. BABYLON.NullEngineOptions = NullEngineOptions;
  90009. /**
  90010. * The null engine class provides support for headless version of babylon.js.
  90011. * This can be used in server side scenario or for testing purposes
  90012. */
  90013. var NullEngine = /** @class */ (function (_super) {
  90014. __extends(NullEngine, _super);
  90015. function NullEngine(options) {
  90016. if (options === void 0) { options = new NullEngineOptions(); }
  90017. var _this = _super.call(this, null) || this;
  90018. if (options.deterministicLockstep === undefined) {
  90019. options.deterministicLockstep = false;
  90020. }
  90021. if (options.lockstepMaxSteps === undefined) {
  90022. options.lockstepMaxSteps = 4;
  90023. }
  90024. _this._options = options;
  90025. // Init caps
  90026. // We consider we are on a webgl1 capable device
  90027. _this._caps = new BABYLON.EngineCapabilities();
  90028. _this._caps.maxTexturesImageUnits = 16;
  90029. _this._caps.maxVertexTextureImageUnits = 16;
  90030. _this._caps.maxTextureSize = 512;
  90031. _this._caps.maxCubemapTextureSize = 512;
  90032. _this._caps.maxRenderTextureSize = 512;
  90033. _this._caps.maxVertexAttribs = 16;
  90034. _this._caps.maxVaryingVectors = 16;
  90035. _this._caps.maxFragmentUniformVectors = 16;
  90036. _this._caps.maxVertexUniformVectors = 16;
  90037. // Extensions
  90038. _this._caps.standardDerivatives = false;
  90039. _this._caps.astc = null;
  90040. _this._caps.s3tc = null;
  90041. _this._caps.pvrtc = null;
  90042. _this._caps.etc1 = null;
  90043. _this._caps.etc2 = null;
  90044. _this._caps.textureAnisotropicFilterExtension = null;
  90045. _this._caps.maxAnisotropy = 0;
  90046. _this._caps.uintIndices = false;
  90047. _this._caps.fragmentDepthSupported = false;
  90048. _this._caps.highPrecisionShaderSupported = true;
  90049. _this._caps.colorBufferFloat = false;
  90050. _this._caps.textureFloat = false;
  90051. _this._caps.textureFloatLinearFiltering = false;
  90052. _this._caps.textureFloatRender = false;
  90053. _this._caps.textureHalfFloat = false;
  90054. _this._caps.textureHalfFloatLinearFiltering = false;
  90055. _this._caps.textureHalfFloatRender = false;
  90056. _this._caps.textureLOD = false;
  90057. _this._caps.drawBuffersExtension = false;
  90058. _this._caps.depthTextureExtension = false;
  90059. _this._caps.vertexArrayObject = false;
  90060. _this._caps.instancedArrays = false;
  90061. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  90062. // Wrappers
  90063. if (typeof URL === "undefined") {
  90064. URL = {
  90065. createObjectURL: function () { },
  90066. revokeObjectURL: function () { }
  90067. };
  90068. }
  90069. if (typeof Blob === "undefined") {
  90070. Blob = function () { };
  90071. }
  90072. return _this;
  90073. }
  90074. NullEngine.prototype.isDeterministicLockStep = function () {
  90075. return this._options.deterministicLockstep;
  90076. };
  90077. NullEngine.prototype.getLockstepMaxSteps = function () {
  90078. return this._options.lockstepMaxSteps;
  90079. };
  90080. NullEngine.prototype.getHardwareScalingLevel = function () {
  90081. return 1.0;
  90082. };
  90083. NullEngine.prototype.createVertexBuffer = function (vertices) {
  90084. return {
  90085. capacity: 0,
  90086. references: 1,
  90087. is32Bits: false
  90088. };
  90089. };
  90090. NullEngine.prototype.createIndexBuffer = function (indices) {
  90091. return {
  90092. capacity: 0,
  90093. references: 1,
  90094. is32Bits: false
  90095. };
  90096. };
  90097. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  90098. if (stencil === void 0) { stencil = false; }
  90099. };
  90100. NullEngine.prototype.getRenderWidth = function (useScreen) {
  90101. if (useScreen === void 0) { useScreen = false; }
  90102. if (!useScreen && this._currentRenderTarget) {
  90103. return this._currentRenderTarget.width;
  90104. }
  90105. return this._options.renderWidth;
  90106. };
  90107. NullEngine.prototype.getRenderHeight = function (useScreen) {
  90108. if (useScreen === void 0) { useScreen = false; }
  90109. if (!useScreen && this._currentRenderTarget) {
  90110. return this._currentRenderTarget.height;
  90111. }
  90112. return this._options.renderHeight;
  90113. };
  90114. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  90115. this._cachedViewport = viewport;
  90116. };
  90117. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  90118. return {
  90119. transformFeedback: null,
  90120. __SPECTOR_rebuildProgram: null
  90121. };
  90122. };
  90123. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  90124. return [];
  90125. };
  90126. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  90127. return [];
  90128. };
  90129. NullEngine.prototype.bindSamplers = function (effect) {
  90130. this._currentEffect = null;
  90131. };
  90132. NullEngine.prototype.enableEffect = function (effect) {
  90133. this._currentEffect = effect;
  90134. if (effect.onBind) {
  90135. effect.onBind(effect);
  90136. }
  90137. effect.onBindObservable.notifyObservers(effect);
  90138. };
  90139. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  90140. if (zOffset === void 0) { zOffset = 0; }
  90141. if (reverseSide === void 0) { reverseSide = false; }
  90142. };
  90143. NullEngine.prototype.setIntArray = function (uniform, array) {
  90144. };
  90145. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  90146. };
  90147. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  90148. };
  90149. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  90150. };
  90151. NullEngine.prototype.setFloatArray = function (uniform, array) {
  90152. };
  90153. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  90154. };
  90155. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  90156. };
  90157. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  90158. };
  90159. NullEngine.prototype.setArray = function (uniform, array) {
  90160. };
  90161. NullEngine.prototype.setArray2 = function (uniform, array) {
  90162. };
  90163. NullEngine.prototype.setArray3 = function (uniform, array) {
  90164. };
  90165. NullEngine.prototype.setArray4 = function (uniform, array) {
  90166. };
  90167. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  90168. };
  90169. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  90170. };
  90171. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  90172. };
  90173. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  90174. };
  90175. NullEngine.prototype.setFloat = function (uniform, value) {
  90176. };
  90177. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  90178. };
  90179. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  90180. };
  90181. NullEngine.prototype.setBool = function (uniform, bool) {
  90182. };
  90183. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  90184. };
  90185. NullEngine.prototype.setColor3 = function (uniform, color3) {
  90186. };
  90187. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  90188. };
  90189. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  90190. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  90191. if (this._alphaMode === mode) {
  90192. return;
  90193. }
  90194. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  90195. if (!noDepthWriteChange) {
  90196. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  90197. }
  90198. this._alphaMode = mode;
  90199. };
  90200. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  90201. };
  90202. NullEngine.prototype.wipeCaches = function (bruteForce) {
  90203. if (this.preventCacheWipeBetweenFrames) {
  90204. return;
  90205. }
  90206. this.resetTextureCache();
  90207. this._currentEffect = null;
  90208. if (bruteForce) {
  90209. this._currentProgram = null;
  90210. this._stencilState.reset();
  90211. this._depthCullingState.reset();
  90212. this._alphaState.reset();
  90213. }
  90214. this._cachedVertexBuffers = null;
  90215. this._cachedIndexBuffer = null;
  90216. this._cachedEffectForVertexBuffers = null;
  90217. };
  90218. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  90219. };
  90220. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  90221. };
  90222. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  90223. };
  90224. NullEngine.prototype._createTexture = function () {
  90225. return {};
  90226. };
  90227. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  90228. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90229. if (onLoad === void 0) { onLoad = null; }
  90230. if (onError === void 0) { onError = null; }
  90231. if (buffer === void 0) { buffer = null; }
  90232. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  90233. var url = String(urlArg);
  90234. texture.url = url;
  90235. texture.generateMipMaps = !noMipmap;
  90236. texture.samplingMode = samplingMode;
  90237. texture.invertY = invertY;
  90238. texture.baseWidth = this._options.textureSize;
  90239. texture.baseHeight = this._options.textureSize;
  90240. texture.width = this._options.textureSize;
  90241. texture.height = this._options.textureSize;
  90242. if (format) {
  90243. texture.format = format;
  90244. }
  90245. texture.isReady = true;
  90246. if (onLoad) {
  90247. onLoad();
  90248. }
  90249. return texture;
  90250. };
  90251. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  90252. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  90253. if (options !== undefined && typeof options === "object") {
  90254. fullOptions.generateMipMaps = options.generateMipMaps;
  90255. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  90256. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  90257. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  90258. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  90259. }
  90260. else {
  90261. fullOptions.generateMipMaps = options;
  90262. fullOptions.generateDepthBuffer = true;
  90263. fullOptions.generateStencilBuffer = false;
  90264. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90265. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90266. }
  90267. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  90268. var width = size.width || size;
  90269. var height = size.height || size;
  90270. texture._depthStencilBuffer = {};
  90271. texture._framebuffer = {};
  90272. texture.baseWidth = width;
  90273. texture.baseHeight = height;
  90274. texture.width = width;
  90275. texture.height = height;
  90276. texture.isReady = true;
  90277. texture.samples = 1;
  90278. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  90279. texture.samplingMode = fullOptions.samplingMode;
  90280. texture.type = fullOptions.type;
  90281. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  90282. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  90283. return texture;
  90284. };
  90285. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  90286. texture.samplingMode = samplingMode;
  90287. };
  90288. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  90289. if (this._currentRenderTarget) {
  90290. this.unBindFramebuffer(this._currentRenderTarget);
  90291. }
  90292. this._currentRenderTarget = texture;
  90293. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  90294. if (this._cachedViewport && !forceFullscreenViewport) {
  90295. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  90296. }
  90297. };
  90298. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  90299. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  90300. this._currentRenderTarget = null;
  90301. if (onBeforeUnbind) {
  90302. if (texture._MSAAFramebuffer) {
  90303. this._currentFramebuffer = texture._framebuffer;
  90304. }
  90305. onBeforeUnbind();
  90306. }
  90307. this._currentFramebuffer = null;
  90308. };
  90309. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  90310. var vbo = {
  90311. capacity: 1,
  90312. references: 1,
  90313. is32Bits: false
  90314. };
  90315. return vbo;
  90316. };
  90317. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  90318. if (offset === void 0) { offset = 0; }
  90319. };
  90320. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  90321. };
  90322. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  90323. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  90324. this._boundTexturesCache[this._activeChannel] = texture;
  90325. }
  90326. };
  90327. NullEngine.prototype._bindTexture = function (channel, texture) {
  90328. if (channel < 0) {
  90329. return;
  90330. }
  90331. this._bindTextureDirectly(0, texture);
  90332. };
  90333. NullEngine.prototype._releaseBuffer = function (buffer) {
  90334. buffer.references--;
  90335. if (buffer.references === 0) {
  90336. return true;
  90337. }
  90338. return false;
  90339. };
  90340. return NullEngine;
  90341. }(BABYLON.Engine));
  90342. BABYLON.NullEngine = NullEngine;
  90343. })(BABYLON || (BABYLON = {}));
  90344. //# sourceMappingURL=babylon.nullEngine.js.map
  90345. "use strict";
  90346. var BABYLON;
  90347. (function (BABYLON) {
  90348. /**
  90349. * This class can be used to get instrumentation data from a Babylon engine
  90350. */
  90351. var EngineInstrumentation = /** @class */ (function () {
  90352. function EngineInstrumentation(engine) {
  90353. this.engine = engine;
  90354. this._captureGPUFrameTime = false;
  90355. this._gpuFrameTime = new BABYLON.PerfCounter();
  90356. this._captureShaderCompilationTime = false;
  90357. this._shaderCompilationTime = new BABYLON.PerfCounter();
  90358. // Observers
  90359. this._onBeginFrameObserver = null;
  90360. this._onEndFrameObserver = null;
  90361. this._onBeforeShaderCompilationObserver = null;
  90362. this._onAfterShaderCompilationObserver = null;
  90363. }
  90364. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  90365. // Properties
  90366. /**
  90367. * Gets the perf counter used for GPU frame time
  90368. */
  90369. get: function () {
  90370. return this._gpuFrameTime;
  90371. },
  90372. enumerable: true,
  90373. configurable: true
  90374. });
  90375. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  90376. /**
  90377. * Gets the GPU frame time capture status
  90378. */
  90379. get: function () {
  90380. return this._captureGPUFrameTime;
  90381. },
  90382. /**
  90383. * Enable or disable the GPU frame time capture
  90384. */
  90385. set: function (value) {
  90386. var _this = this;
  90387. if (value === this._captureGPUFrameTime) {
  90388. return;
  90389. }
  90390. this._captureGPUFrameTime = value;
  90391. if (value) {
  90392. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90393. if (!_this._gpuFrameTimeToken) {
  90394. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90395. }
  90396. });
  90397. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90398. if (!_this._gpuFrameTimeToken) {
  90399. return;
  90400. }
  90401. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90402. if (time > -1) {
  90403. _this._gpuFrameTimeToken = null;
  90404. _this._gpuFrameTime.fetchNewFrame();
  90405. _this._gpuFrameTime.addCount(time, true);
  90406. }
  90407. });
  90408. }
  90409. else {
  90410. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90411. this._onBeginFrameObserver = null;
  90412. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90413. this._onEndFrameObserver = null;
  90414. }
  90415. },
  90416. enumerable: true,
  90417. configurable: true
  90418. });
  90419. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90420. /**
  90421. * Gets the perf counter used for shader compilation time
  90422. */
  90423. get: function () {
  90424. return this._shaderCompilationTime;
  90425. },
  90426. enumerable: true,
  90427. configurable: true
  90428. });
  90429. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90430. /**
  90431. * Gets the shader compilation time capture status
  90432. */
  90433. get: function () {
  90434. return this._captureShaderCompilationTime;
  90435. },
  90436. /**
  90437. * Enable or disable the shader compilation time capture
  90438. */
  90439. set: function (value) {
  90440. var _this = this;
  90441. if (value === this._captureShaderCompilationTime) {
  90442. return;
  90443. }
  90444. this._captureShaderCompilationTime = value;
  90445. if (value) {
  90446. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90447. _this._shaderCompilationTime.fetchNewFrame();
  90448. _this._shaderCompilationTime.beginMonitoring();
  90449. });
  90450. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90451. _this._shaderCompilationTime.endMonitoring();
  90452. });
  90453. }
  90454. else {
  90455. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90456. this._onBeforeShaderCompilationObserver = null;
  90457. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90458. this._onAfterShaderCompilationObserver = null;
  90459. }
  90460. },
  90461. enumerable: true,
  90462. configurable: true
  90463. });
  90464. EngineInstrumentation.prototype.dispose = function () {
  90465. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90466. this._onBeginFrameObserver = null;
  90467. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90468. this._onEndFrameObserver = null;
  90469. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90470. this._onBeforeShaderCompilationObserver = null;
  90471. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90472. this._onAfterShaderCompilationObserver = null;
  90473. this.engine = null;
  90474. };
  90475. return EngineInstrumentation;
  90476. }());
  90477. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90478. })(BABYLON || (BABYLON = {}));
  90479. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90480. "use strict";
  90481. var BABYLON;
  90482. (function (BABYLON) {
  90483. /**
  90484. * This class can be used to get instrumentation data from a Babylon engine
  90485. */
  90486. var SceneInstrumentation = /** @class */ (function () {
  90487. function SceneInstrumentation(scene) {
  90488. var _this = this;
  90489. this.scene = scene;
  90490. this._captureActiveMeshesEvaluationTime = false;
  90491. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90492. this._captureRenderTargetsRenderTime = false;
  90493. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90494. this._captureFrameTime = false;
  90495. this._frameTime = new BABYLON.PerfCounter();
  90496. this._captureRenderTime = false;
  90497. this._renderTime = new BABYLON.PerfCounter();
  90498. this._captureInterFrameTime = false;
  90499. this._interFrameTime = new BABYLON.PerfCounter();
  90500. this._captureParticlesRenderTime = false;
  90501. this._particlesRenderTime = new BABYLON.PerfCounter();
  90502. this._captureSpritesRenderTime = false;
  90503. this._spritesRenderTime = new BABYLON.PerfCounter();
  90504. this._capturePhysicsTime = false;
  90505. this._physicsTime = new BABYLON.PerfCounter();
  90506. this._captureAnimationsTime = false;
  90507. this._animationsTime = new BABYLON.PerfCounter();
  90508. // Observers
  90509. this._onBeforeActiveMeshesEvaluationObserver = null;
  90510. this._onAfterActiveMeshesEvaluationObserver = null;
  90511. this._onBeforeRenderTargetsRenderObserver = null;
  90512. this._onAfterRenderTargetsRenderObserver = null;
  90513. this._onAfterRenderObserver = null;
  90514. this._onBeforeDrawPhaseObserver = null;
  90515. this._onAfterDrawPhaseObserver = null;
  90516. this._onBeforeAnimationsObserver = null;
  90517. this._onBeforeParticlesRenderingObserver = null;
  90518. this._onAfterParticlesRenderingObserver = null;
  90519. this._onBeforeSpritesRenderingObserver = null;
  90520. this._onAfterSpritesRenderingObserver = null;
  90521. this._onBeforePhysicsObserver = null;
  90522. this._onAfterPhysicsObserver = null;
  90523. this._onAfterAnimationsObserver = null;
  90524. // Before render
  90525. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90526. if (_this._captureActiveMeshesEvaluationTime) {
  90527. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90528. }
  90529. if (_this._captureRenderTargetsRenderTime) {
  90530. _this._renderTargetsRenderTime.fetchNewFrame();
  90531. }
  90532. if (_this._captureFrameTime) {
  90533. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90534. _this._frameTime.beginMonitoring();
  90535. }
  90536. if (_this._captureInterFrameTime) {
  90537. _this._interFrameTime.endMonitoring();
  90538. }
  90539. if (_this._captureParticlesRenderTime) {
  90540. _this._particlesRenderTime.fetchNewFrame();
  90541. }
  90542. if (_this._captureSpritesRenderTime) {
  90543. _this._spritesRenderTime.fetchNewFrame();
  90544. }
  90545. if (_this._captureAnimationsTime) {
  90546. _this._animationsTime.beginMonitoring();
  90547. }
  90548. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90549. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90550. });
  90551. // After render
  90552. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90553. if (_this._captureFrameTime) {
  90554. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90555. _this._frameTime.endMonitoring();
  90556. }
  90557. if (_this._captureRenderTime) {
  90558. _this._renderTime.endMonitoring(false);
  90559. }
  90560. if (_this._captureInterFrameTime) {
  90561. _this._interFrameTime.beginMonitoring();
  90562. }
  90563. });
  90564. }
  90565. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90566. // Properties
  90567. /**
  90568. * Gets the perf counter used for active meshes evaluation time
  90569. */
  90570. get: function () {
  90571. return this._activeMeshesEvaluationTime;
  90572. },
  90573. enumerable: true,
  90574. configurable: true
  90575. });
  90576. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90577. /**
  90578. * Gets the active meshes evaluation time capture status
  90579. */
  90580. get: function () {
  90581. return this._captureActiveMeshesEvaluationTime;
  90582. },
  90583. /**
  90584. * Enable or disable the active meshes evaluation time capture
  90585. */
  90586. set: function (value) {
  90587. var _this = this;
  90588. if (value === this._captureActiveMeshesEvaluationTime) {
  90589. return;
  90590. }
  90591. this._captureActiveMeshesEvaluationTime = value;
  90592. if (value) {
  90593. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90594. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90595. _this._activeMeshesEvaluationTime.beginMonitoring();
  90596. });
  90597. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90598. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90599. _this._activeMeshesEvaluationTime.endMonitoring();
  90600. });
  90601. }
  90602. else {
  90603. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90604. this._onBeforeActiveMeshesEvaluationObserver = null;
  90605. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90606. this._onAfterActiveMeshesEvaluationObserver = null;
  90607. }
  90608. },
  90609. enumerable: true,
  90610. configurable: true
  90611. });
  90612. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90613. /**
  90614. * Gets the perf counter used for render targets render time
  90615. */
  90616. get: function () {
  90617. return this._renderTargetsRenderTime;
  90618. },
  90619. enumerable: true,
  90620. configurable: true
  90621. });
  90622. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90623. /**
  90624. * Gets the render targets render time capture status
  90625. */
  90626. get: function () {
  90627. return this._captureRenderTargetsRenderTime;
  90628. },
  90629. /**
  90630. * Enable or disable the render targets render time capture
  90631. */
  90632. set: function (value) {
  90633. var _this = this;
  90634. if (value === this._captureRenderTargetsRenderTime) {
  90635. return;
  90636. }
  90637. this._captureRenderTargetsRenderTime = value;
  90638. if (value) {
  90639. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  90640. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90641. _this._renderTargetsRenderTime.beginMonitoring();
  90642. });
  90643. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  90644. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90645. _this._renderTargetsRenderTime.endMonitoring(false);
  90646. });
  90647. }
  90648. else {
  90649. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90650. this._onBeforeRenderTargetsRenderObserver = null;
  90651. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90652. this._onAfterRenderTargetsRenderObserver = null;
  90653. }
  90654. },
  90655. enumerable: true,
  90656. configurable: true
  90657. });
  90658. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90659. /**
  90660. * Gets the perf counter used for particles render time
  90661. */
  90662. get: function () {
  90663. return this._particlesRenderTime;
  90664. },
  90665. enumerable: true,
  90666. configurable: true
  90667. });
  90668. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90669. /**
  90670. * Gets the particles render time capture status
  90671. */
  90672. get: function () {
  90673. return this._captureParticlesRenderTime;
  90674. },
  90675. /**
  90676. * Enable or disable the particles render time capture
  90677. */
  90678. set: function (value) {
  90679. var _this = this;
  90680. if (value === this._captureParticlesRenderTime) {
  90681. return;
  90682. }
  90683. this._captureParticlesRenderTime = value;
  90684. if (value) {
  90685. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90686. BABYLON.Tools.StartPerformanceCounter("Particles");
  90687. _this._particlesRenderTime.beginMonitoring();
  90688. });
  90689. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90690. BABYLON.Tools.EndPerformanceCounter("Particles");
  90691. _this._particlesRenderTime.endMonitoring(false);
  90692. });
  90693. }
  90694. else {
  90695. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90696. this._onBeforeParticlesRenderingObserver = null;
  90697. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90698. this._onAfterParticlesRenderingObserver = null;
  90699. }
  90700. },
  90701. enumerable: true,
  90702. configurable: true
  90703. });
  90704. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90705. /**
  90706. * Gets the perf counter used for sprites render time
  90707. */
  90708. get: function () {
  90709. return this._spritesRenderTime;
  90710. },
  90711. enumerable: true,
  90712. configurable: true
  90713. });
  90714. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90715. /**
  90716. * Gets the sprites render time capture status
  90717. */
  90718. get: function () {
  90719. return this._captureSpritesRenderTime;
  90720. },
  90721. /**
  90722. * Enable or disable the sprites render time capture
  90723. */
  90724. set: function (value) {
  90725. var _this = this;
  90726. if (value === this._captureSpritesRenderTime) {
  90727. return;
  90728. }
  90729. this._captureSpritesRenderTime = value;
  90730. if (value) {
  90731. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90732. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90733. _this._spritesRenderTime.beginMonitoring();
  90734. });
  90735. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90736. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90737. _this._spritesRenderTime.endMonitoring(false);
  90738. });
  90739. }
  90740. else {
  90741. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90742. this._onBeforeSpritesRenderingObserver = null;
  90743. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90744. this._onAfterSpritesRenderingObserver = null;
  90745. }
  90746. },
  90747. enumerable: true,
  90748. configurable: true
  90749. });
  90750. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90751. /**
  90752. * Gets the perf counter used for physics time
  90753. */
  90754. get: function () {
  90755. return this._physicsTime;
  90756. },
  90757. enumerable: true,
  90758. configurable: true
  90759. });
  90760. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90761. /**
  90762. * Gets the physics time capture status
  90763. */
  90764. get: function () {
  90765. return this._capturePhysicsTime;
  90766. },
  90767. /**
  90768. * Enable or disable the physics time capture
  90769. */
  90770. set: function (value) {
  90771. var _this = this;
  90772. if (value === this._capturePhysicsTime) {
  90773. return;
  90774. }
  90775. this._capturePhysicsTime = value;
  90776. if (value) {
  90777. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90778. BABYLON.Tools.StartPerformanceCounter("Physics");
  90779. _this._physicsTime.beginMonitoring();
  90780. });
  90781. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90782. BABYLON.Tools.EndPerformanceCounter("Physics");
  90783. _this._physicsTime.endMonitoring();
  90784. });
  90785. }
  90786. else {
  90787. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90788. this._onBeforePhysicsObserver = null;
  90789. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90790. this._onAfterPhysicsObserver = null;
  90791. }
  90792. },
  90793. enumerable: true,
  90794. configurable: true
  90795. });
  90796. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90797. /**
  90798. * Gets the perf counter used for animations time
  90799. */
  90800. get: function () {
  90801. return this._animationsTime;
  90802. },
  90803. enumerable: true,
  90804. configurable: true
  90805. });
  90806. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90807. /**
  90808. * Gets the animations time capture status
  90809. */
  90810. get: function () {
  90811. return this._captureAnimationsTime;
  90812. },
  90813. /**
  90814. * Enable or disable the animations time capture
  90815. */
  90816. set: function (value) {
  90817. var _this = this;
  90818. if (value === this._captureAnimationsTime) {
  90819. return;
  90820. }
  90821. this._captureAnimationsTime = value;
  90822. if (value) {
  90823. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90824. _this._animationsTime.endMonitoring();
  90825. });
  90826. }
  90827. else {
  90828. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90829. this._onAfterAnimationsObserver = null;
  90830. }
  90831. },
  90832. enumerable: true,
  90833. configurable: true
  90834. });
  90835. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  90836. /**
  90837. * Gets the perf counter used for frame time capture
  90838. */
  90839. get: function () {
  90840. return this._frameTime;
  90841. },
  90842. enumerable: true,
  90843. configurable: true
  90844. });
  90845. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  90846. /**
  90847. * Gets the frame time capture status
  90848. */
  90849. get: function () {
  90850. return this._captureFrameTime;
  90851. },
  90852. /**
  90853. * Enable or disable the frame time capture
  90854. */
  90855. set: function (value) {
  90856. this._captureFrameTime = value;
  90857. },
  90858. enumerable: true,
  90859. configurable: true
  90860. });
  90861. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  90862. /**
  90863. * Gets the perf counter used for inter-frames time capture
  90864. */
  90865. get: function () {
  90866. return this._interFrameTime;
  90867. },
  90868. enumerable: true,
  90869. configurable: true
  90870. });
  90871. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  90872. /**
  90873. * Gets the inter-frames time capture status
  90874. */
  90875. get: function () {
  90876. return this._captureInterFrameTime;
  90877. },
  90878. /**
  90879. * Enable or disable the inter-frames time capture
  90880. */
  90881. set: function (value) {
  90882. this._captureInterFrameTime = value;
  90883. },
  90884. enumerable: true,
  90885. configurable: true
  90886. });
  90887. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  90888. /**
  90889. * Gets the perf counter used for render time capture
  90890. */
  90891. get: function () {
  90892. return this._renderTime;
  90893. },
  90894. enumerable: true,
  90895. configurable: true
  90896. });
  90897. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  90898. /**
  90899. * Gets the render time capture status
  90900. */
  90901. get: function () {
  90902. return this._captureRenderTime;
  90903. },
  90904. /**
  90905. * Enable or disable the render time capture
  90906. */
  90907. set: function (value) {
  90908. var _this = this;
  90909. if (value === this._captureRenderTime) {
  90910. return;
  90911. }
  90912. this._captureRenderTime = value;
  90913. if (value) {
  90914. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  90915. _this._renderTime.beginMonitoring();
  90916. BABYLON.Tools.StartPerformanceCounter("Main render");
  90917. });
  90918. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  90919. _this._renderTime.endMonitoring(false);
  90920. BABYLON.Tools.EndPerformanceCounter("Main render");
  90921. });
  90922. }
  90923. else {
  90924. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90925. this._onBeforeDrawPhaseObserver = null;
  90926. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90927. this._onAfterDrawPhaseObserver = null;
  90928. }
  90929. },
  90930. enumerable: true,
  90931. configurable: true
  90932. });
  90933. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  90934. /**
  90935. * Gets the perf counter used for draw calls
  90936. */
  90937. get: function () {
  90938. return this.scene.getEngine()._drawCalls;
  90939. },
  90940. enumerable: true,
  90941. configurable: true
  90942. });
  90943. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  90944. /**
  90945. * Gets the perf counter used for texture collisions
  90946. */
  90947. get: function () {
  90948. return this.scene.getEngine()._textureCollisions;
  90949. },
  90950. enumerable: true,
  90951. configurable: true
  90952. });
  90953. SceneInstrumentation.prototype.dispose = function () {
  90954. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  90955. this._onAfterRenderObserver = null;
  90956. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90957. this._onBeforeActiveMeshesEvaluationObserver = null;
  90958. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90959. this._onAfterActiveMeshesEvaluationObserver = null;
  90960. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90961. this._onBeforeRenderTargetsRenderObserver = null;
  90962. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90963. this._onAfterRenderTargetsRenderObserver = null;
  90964. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  90965. this._onBeforeAnimationsObserver = null;
  90966. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90967. this._onBeforeParticlesRenderingObserver = null;
  90968. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90969. this._onAfterParticlesRenderingObserver = null;
  90970. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90971. this._onBeforeSpritesRenderingObserver = null;
  90972. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90973. this._onAfterSpritesRenderingObserver = null;
  90974. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90975. this._onBeforeDrawPhaseObserver = null;
  90976. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90977. this._onAfterDrawPhaseObserver = null;
  90978. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90979. this._onBeforePhysicsObserver = null;
  90980. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90981. this._onAfterPhysicsObserver = null;
  90982. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90983. this._onAfterAnimationsObserver = null;
  90984. this.scene = null;
  90985. };
  90986. return SceneInstrumentation;
  90987. }());
  90988. BABYLON.SceneInstrumentation = SceneInstrumentation;
  90989. })(BABYLON || (BABYLON = {}));
  90990. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  90991. "use strict";
  90992. var BABYLON;
  90993. (function (BABYLON) {
  90994. var _TimeToken = /** @class */ (function () {
  90995. function _TimeToken() {
  90996. this._timeElapsedQueryEnded = false;
  90997. }
  90998. return _TimeToken;
  90999. }());
  91000. BABYLON._TimeToken = _TimeToken;
  91001. })(BABYLON || (BABYLON = {}));
  91002. //# sourceMappingURL=babylon.timeToken.js.map
  91003. "use strict";
  91004. var BABYLON;
  91005. (function (BABYLON) {
  91006. /**
  91007. * Background material defines definition.
  91008. * @ignore Mainly internal Use
  91009. */
  91010. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  91011. __extends(BackgroundMaterialDefines, _super);
  91012. /**
  91013. * Constructor of the defines.
  91014. */
  91015. function BackgroundMaterialDefines() {
  91016. var _this = _super.call(this) || this;
  91017. /**
  91018. * True if the diffuse texture is in use.
  91019. */
  91020. _this.DIFFUSE = false;
  91021. /**
  91022. * The direct UV channel to use.
  91023. */
  91024. _this.DIFFUSEDIRECTUV = 0;
  91025. /**
  91026. * True if the diffuse texture is in gamma space.
  91027. */
  91028. _this.GAMMADIFFUSE = false;
  91029. /**
  91030. * True if the diffuse texture has opacity in the alpha channel.
  91031. */
  91032. _this.DIFFUSEHASALPHA = false;
  91033. /**
  91034. * True if you want the material to fade to transparent at grazing angle.
  91035. */
  91036. _this.OPACITYFRESNEL = false;
  91037. /**
  91038. * True if an extra blur needs to be added in the reflection.
  91039. */
  91040. _this.REFLECTIONBLUR = false;
  91041. /**
  91042. * True if you want the material to fade to reflection at grazing angle.
  91043. */
  91044. _this.REFLECTIONFRESNEL = false;
  91045. /**
  91046. * True if you want the material to falloff as far as you move away from the scene center.
  91047. */
  91048. _this.REFLECTIONFALLOFF = false;
  91049. /**
  91050. * False if the current Webgl implementation does not support the texture lod extension.
  91051. */
  91052. _this.TEXTURELODSUPPORT = false;
  91053. /**
  91054. * True to ensure the data are premultiplied.
  91055. */
  91056. _this.PREMULTIPLYALPHA = false;
  91057. /**
  91058. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  91059. */
  91060. _this.USERGBCOLOR = false;
  91061. /**
  91062. * True to add noise in order to reduce the banding effect.
  91063. */
  91064. _this.NOISE = false;
  91065. /**
  91066. * is the reflection texture in BGR color scheme?
  91067. * Mainly used to solve a bug in ios10 video tag
  91068. */
  91069. _this.REFLECTIONBGR = false;
  91070. _this.IMAGEPROCESSING = false;
  91071. _this.VIGNETTE = false;
  91072. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  91073. _this.VIGNETTEBLENDMODEOPAQUE = false;
  91074. _this.TONEMAPPING = false;
  91075. _this.CONTRAST = false;
  91076. _this.COLORCURVES = false;
  91077. _this.COLORGRADING = false;
  91078. _this.COLORGRADING3D = false;
  91079. _this.SAMPLER3DGREENDEPTH = false;
  91080. _this.SAMPLER3DBGRMAP = false;
  91081. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  91082. _this.EXPOSURE = false;
  91083. _this.GRAIN = false;
  91084. // Reflection.
  91085. _this.REFLECTION = false;
  91086. _this.REFLECTIONMAP_3D = false;
  91087. _this.REFLECTIONMAP_SPHERICAL = false;
  91088. _this.REFLECTIONMAP_PLANAR = false;
  91089. _this.REFLECTIONMAP_CUBIC = false;
  91090. _this.REFLECTIONMAP_PROJECTION = false;
  91091. _this.REFLECTIONMAP_SKYBOX = false;
  91092. _this.REFLECTIONMAP_EXPLICIT = false;
  91093. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91094. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91095. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91096. _this.INVERTCUBICMAP = false;
  91097. _this.REFLECTIONMAP_OPPOSITEZ = false;
  91098. _this.LODINREFLECTIONALPHA = false;
  91099. _this.GAMMAREFLECTION = false;
  91100. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  91101. // Default BJS.
  91102. _this.MAINUV1 = false;
  91103. _this.MAINUV2 = false;
  91104. _this.UV1 = false;
  91105. _this.UV2 = false;
  91106. _this.CLIPPLANE = false;
  91107. _this.POINTSIZE = false;
  91108. _this.FOG = false;
  91109. _this.NORMAL = false;
  91110. _this.NUM_BONE_INFLUENCERS = 0;
  91111. _this.BonesPerMesh = 0;
  91112. _this.INSTANCES = false;
  91113. _this.SHADOWFLOAT = false;
  91114. _this.rebuild();
  91115. return _this;
  91116. }
  91117. return BackgroundMaterialDefines;
  91118. }(BABYLON.MaterialDefines));
  91119. /**
  91120. * Background material used to create an efficient environement around your scene.
  91121. */
  91122. var BackgroundMaterial = /** @class */ (function (_super) {
  91123. __extends(BackgroundMaterial, _super);
  91124. /**
  91125. * Instantiates a Background Material in the given scene
  91126. * @param name The friendly name of the material
  91127. * @param scene The scene to add the material to
  91128. */
  91129. function BackgroundMaterial(name, scene) {
  91130. var _this = _super.call(this, name, scene) || this;
  91131. /**
  91132. * Key light Color (multiply against the R channel of the environement texture)
  91133. */
  91134. _this.primaryColor = BABYLON.Color3.White();
  91135. /**
  91136. * Key light Level (allowing HDR output of the background)
  91137. */
  91138. _this.primaryLevel = 1;
  91139. /**
  91140. * Secondary light Color (multiply against the G channel of the environement texture)
  91141. */
  91142. _this.secondaryColor = BABYLON.Color3.Gray();
  91143. /**
  91144. * Secondary light Level (allowing HDR output of the background)
  91145. */
  91146. _this.secondaryLevel = 1;
  91147. /**
  91148. * Tertiary light Color (multiply against the B channel of the environement texture)
  91149. */
  91150. _this.tertiaryColor = BABYLON.Color3.Black();
  91151. /**
  91152. * Tertiary light Level (allowing HDR output of the background)
  91153. */
  91154. _this.tertiaryLevel = 1;
  91155. /**
  91156. * Reflection Texture used in the material.
  91157. * Should be author in a specific way for the best result (refer to the documentation).
  91158. */
  91159. _this.reflectionTexture = null;
  91160. /**
  91161. * Reflection Texture level of blur.
  91162. *
  91163. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  91164. * texture twice.
  91165. */
  91166. _this.reflectionBlur = 0;
  91167. /**
  91168. * Diffuse Texture used in the material.
  91169. * Should be author in a specific way for the best result (refer to the documentation).
  91170. */
  91171. _this.diffuseTexture = null;
  91172. _this._shadowLights = null;
  91173. /**
  91174. * Specify the list of lights casting shadow on the material.
  91175. * All scene shadow lights will be included if null.
  91176. */
  91177. _this.shadowLights = null;
  91178. /**
  91179. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  91180. * soft lighting on the background.
  91181. */
  91182. _this.shadowBlurScale = 1;
  91183. /**
  91184. * Helps adjusting the shadow to a softer level if required.
  91185. * 0 means black shadows and 1 means no shadows.
  91186. */
  91187. _this.shadowLevel = 0;
  91188. /**
  91189. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  91190. * It is usually zero but might be interesting to modify according to your setup.
  91191. */
  91192. _this.sceneCenter = BABYLON.Vector3.Zero();
  91193. /**
  91194. * This helps specifying that the material is falling off to the sky box at grazing angle.
  91195. * This helps ensuring a nice transition when the camera goes under the ground.
  91196. */
  91197. _this.opacityFresnel = true;
  91198. /**
  91199. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  91200. * This helps adding a mirror texture on the ground.
  91201. */
  91202. _this.reflectionFresnel = false;
  91203. /**
  91204. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  91205. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  91206. */
  91207. _this.reflectionFalloffDistance = 0.0;
  91208. /**
  91209. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  91210. */
  91211. _this.reflectionAmount = 1.0;
  91212. /**
  91213. * This specifies the weight of the reflection at grazing angle.
  91214. */
  91215. _this.reflectionReflectance0 = 0.05;
  91216. /**
  91217. * This specifies the weight of the reflection at a perpendicular point of view.
  91218. */
  91219. _this.reflectionReflectance90 = 0.5;
  91220. /**
  91221. * Helps to directly use the maps channels instead of their level.
  91222. */
  91223. _this.useRGBColor = true;
  91224. /**
  91225. * This helps reducing the banding effect that could occur on the background.
  91226. */
  91227. _this.enableNoise = false;
  91228. _this._fovMultiplier = 1.0;
  91229. /**
  91230. * Enable the FOV adjustment feature controlled by fovMultiplier.
  91231. * @type {boolean}
  91232. */
  91233. _this.useEquirectangularFOV = false;
  91234. _this._maxSimultaneousLights = 4;
  91235. /**
  91236. * Number of Simultaneous lights allowed on the material.
  91237. */
  91238. _this.maxSimultaneousLights = 4;
  91239. /**
  91240. * Keep track of the image processing observer to allow dispose and replace.
  91241. */
  91242. _this._imageProcessingObserver = null;
  91243. /**
  91244. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  91245. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  91246. */
  91247. _this.switchToBGR = false;
  91248. // Temp values kept as cache in the material.
  91249. _this._renderTargets = new BABYLON.SmartArray(16);
  91250. _this._reflectionControls = BABYLON.Vector4.Zero();
  91251. // Setup the default processing configuration to the scene.
  91252. _this._attachImageProcessingConfiguration(null);
  91253. _this.getRenderTargetTextures = function () {
  91254. _this._renderTargets.reset();
  91255. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  91256. _this._renderTargets.push(_this._diffuseTexture);
  91257. }
  91258. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  91259. _this._renderTargets.push(_this._reflectionTexture);
  91260. }
  91261. return _this._renderTargets;
  91262. };
  91263. return _this;
  91264. }
  91265. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  91266. /**
  91267. * Sets the reflection reflectance fresnel values according to the default standard
  91268. * empirically know to work well :-)
  91269. */
  91270. set: function (value) {
  91271. var reflectionWeight = value;
  91272. if (reflectionWeight < 0.5) {
  91273. reflectionWeight = reflectionWeight * 2.0;
  91274. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  91275. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  91276. }
  91277. else {
  91278. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  91279. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  91280. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  91281. }
  91282. },
  91283. enumerable: true,
  91284. configurable: true
  91285. });
  91286. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  91287. /**
  91288. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91289. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  91290. * Recommended to be keep at 1.0 except for special cases.
  91291. */
  91292. get: function () {
  91293. return this._fovMultiplier;
  91294. },
  91295. set: function (value) {
  91296. if (isNaN(value)) {
  91297. value = 1.0;
  91298. }
  91299. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  91300. },
  91301. enumerable: true,
  91302. configurable: true
  91303. });
  91304. /**
  91305. * Attaches a new image processing configuration to the PBR Material.
  91306. * @param configuration (if null the scene configuration will be use)
  91307. */
  91308. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  91309. var _this = this;
  91310. if (configuration === this._imageProcessingConfiguration) {
  91311. return;
  91312. }
  91313. // Detaches observer.
  91314. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91315. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91316. }
  91317. // Pick the scene configuration if needed.
  91318. if (!configuration) {
  91319. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  91320. }
  91321. else {
  91322. this._imageProcessingConfiguration = configuration;
  91323. }
  91324. // Attaches observer.
  91325. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91326. _this._markAllSubMeshesAsImageProcessingDirty();
  91327. });
  91328. };
  91329. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  91330. /**
  91331. * Gets the image processing configuration used either in this material.
  91332. */
  91333. get: function () {
  91334. return this._imageProcessingConfiguration;
  91335. },
  91336. /**
  91337. * Sets the Default image processing configuration used either in the this material.
  91338. *
  91339. * If sets to null, the scene one is in use.
  91340. */
  91341. set: function (value) {
  91342. this._attachImageProcessingConfiguration(value);
  91343. // Ensure the effect will be rebuilt.
  91344. this._markAllSubMeshesAsTexturesDirty();
  91345. },
  91346. enumerable: true,
  91347. configurable: true
  91348. });
  91349. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  91350. /**
  91351. * Gets wether the color curves effect is enabled.
  91352. */
  91353. get: function () {
  91354. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91355. },
  91356. /**
  91357. * Sets wether the color curves effect is enabled.
  91358. */
  91359. set: function (value) {
  91360. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91361. },
  91362. enumerable: true,
  91363. configurable: true
  91364. });
  91365. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  91366. /**
  91367. * Gets wether the color grading effect is enabled.
  91368. */
  91369. get: function () {
  91370. return this.imageProcessingConfiguration.colorGradingEnabled;
  91371. },
  91372. /**
  91373. * Gets wether the color grading effect is enabled.
  91374. */
  91375. set: function (value) {
  91376. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91377. },
  91378. enumerable: true,
  91379. configurable: true
  91380. });
  91381. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  91382. /**
  91383. * Gets wether tonemapping is enabled or not.
  91384. */
  91385. get: function () {
  91386. return this._imageProcessingConfiguration.toneMappingEnabled;
  91387. },
  91388. /**
  91389. * Sets wether tonemapping is enabled or not
  91390. */
  91391. set: function (value) {
  91392. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91393. },
  91394. enumerable: true,
  91395. configurable: true
  91396. });
  91397. ;
  91398. ;
  91399. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91400. /**
  91401. * The camera exposure used on this material.
  91402. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91403. * This corresponds to a photographic exposure.
  91404. */
  91405. get: function () {
  91406. return this._imageProcessingConfiguration.exposure;
  91407. },
  91408. /**
  91409. * The camera exposure used on this material.
  91410. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91411. * This corresponds to a photographic exposure.
  91412. */
  91413. set: function (value) {
  91414. this._imageProcessingConfiguration.exposure = value;
  91415. },
  91416. enumerable: true,
  91417. configurable: true
  91418. });
  91419. ;
  91420. ;
  91421. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91422. /**
  91423. * Gets The camera contrast used on this material.
  91424. */
  91425. get: function () {
  91426. return this._imageProcessingConfiguration.contrast;
  91427. },
  91428. /**
  91429. * Sets The camera contrast used on this material.
  91430. */
  91431. set: function (value) {
  91432. this._imageProcessingConfiguration.contrast = value;
  91433. },
  91434. enumerable: true,
  91435. configurable: true
  91436. });
  91437. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91438. /**
  91439. * Gets the Color Grading 2D Lookup Texture.
  91440. */
  91441. get: function () {
  91442. return this._imageProcessingConfiguration.colorGradingTexture;
  91443. },
  91444. /**
  91445. * Sets the Color Grading 2D Lookup Texture.
  91446. */
  91447. set: function (value) {
  91448. this.imageProcessingConfiguration.colorGradingTexture = value;
  91449. },
  91450. enumerable: true,
  91451. configurable: true
  91452. });
  91453. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91454. /**
  91455. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91456. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91457. * 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;
  91458. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91459. */
  91460. get: function () {
  91461. return this.imageProcessingConfiguration.colorCurves;
  91462. },
  91463. /**
  91464. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91465. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91466. * 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;
  91467. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91468. */
  91469. set: function (value) {
  91470. this.imageProcessingConfiguration.colorCurves = value;
  91471. },
  91472. enumerable: true,
  91473. configurable: true
  91474. });
  91475. /**
  91476. * The entire material has been created in order to prevent overdraw.
  91477. * @returns false
  91478. */
  91479. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91480. return true;
  91481. };
  91482. /**
  91483. * The entire material has been created in order to prevent overdraw.
  91484. * @returns true if blending is enable
  91485. */
  91486. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91487. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91488. };
  91489. /**
  91490. * Checks wether the material is ready to be rendered for a given mesh.
  91491. * @param mesh The mesh to render
  91492. * @param subMesh The submesh to check against
  91493. * @param useInstances Specify wether or not the material is used with instances
  91494. * @returns true if all the dependencies are ready (Textures, Effects...)
  91495. */
  91496. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91497. var _this = this;
  91498. if (useInstances === void 0) { useInstances = false; }
  91499. if (subMesh.effect && this.isFrozen) {
  91500. if (this._wasPreviouslyReady) {
  91501. return true;
  91502. }
  91503. }
  91504. if (!subMesh._materialDefines) {
  91505. subMesh._materialDefines = new BackgroundMaterialDefines();
  91506. }
  91507. var scene = this.getScene();
  91508. var defines = subMesh._materialDefines;
  91509. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91510. if (defines._renderId === scene.getRenderId()) {
  91511. return true;
  91512. }
  91513. }
  91514. var engine = scene.getEngine();
  91515. // Lights
  91516. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91517. defines._needNormals = true;
  91518. // Textures
  91519. if (defines._areTexturesDirty) {
  91520. defines._needUVs = false;
  91521. if (scene.texturesEnabled) {
  91522. if (scene.getEngine().getCaps().textureLOD) {
  91523. defines.TEXTURELODSUPPORT = true;
  91524. }
  91525. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91526. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91527. return false;
  91528. }
  91529. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91530. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91531. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91532. defines.OPACITYFRESNEL = this._opacityFresnel;
  91533. }
  91534. else {
  91535. defines.DIFFUSE = false;
  91536. defines.DIFFUSEHASALPHA = false;
  91537. defines.GAMMADIFFUSE = false;
  91538. defines.OPACITYFRESNEL = false;
  91539. }
  91540. var reflectionTexture = this._reflectionTexture;
  91541. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91542. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91543. return false;
  91544. }
  91545. defines.REFLECTION = true;
  91546. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91547. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91548. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91549. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91550. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91551. defines.REFLECTIONBGR = this.switchToBGR;
  91552. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91553. defines.INVERTCUBICMAP = true;
  91554. }
  91555. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91556. switch (reflectionTexture.coordinatesMode) {
  91557. case BABYLON.Texture.CUBIC_MODE:
  91558. case BABYLON.Texture.INVCUBIC_MODE:
  91559. defines.REFLECTIONMAP_CUBIC = true;
  91560. break;
  91561. case BABYLON.Texture.EXPLICIT_MODE:
  91562. defines.REFLECTIONMAP_EXPLICIT = true;
  91563. break;
  91564. case BABYLON.Texture.PLANAR_MODE:
  91565. defines.REFLECTIONMAP_PLANAR = true;
  91566. break;
  91567. case BABYLON.Texture.PROJECTION_MODE:
  91568. defines.REFLECTIONMAP_PROJECTION = true;
  91569. break;
  91570. case BABYLON.Texture.SKYBOX_MODE:
  91571. defines.REFLECTIONMAP_SKYBOX = true;
  91572. break;
  91573. case BABYLON.Texture.SPHERICAL_MODE:
  91574. defines.REFLECTIONMAP_SPHERICAL = true;
  91575. break;
  91576. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91577. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91578. break;
  91579. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91580. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91581. break;
  91582. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91583. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91584. break;
  91585. }
  91586. if (this.reflectionFresnel) {
  91587. defines.REFLECTIONFRESNEL = true;
  91588. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91589. this._reflectionControls.x = this.reflectionAmount;
  91590. this._reflectionControls.y = this.reflectionReflectance0;
  91591. this._reflectionControls.z = this.reflectionReflectance90;
  91592. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91593. }
  91594. else {
  91595. defines.REFLECTIONFRESNEL = false;
  91596. defines.REFLECTIONFALLOFF = false;
  91597. }
  91598. }
  91599. else {
  91600. defines.REFLECTION = false;
  91601. defines.REFLECTIONFALLOFF = false;
  91602. defines.REFLECTIONBLUR = false;
  91603. defines.REFLECTIONMAP_3D = false;
  91604. defines.REFLECTIONMAP_SPHERICAL = false;
  91605. defines.REFLECTIONMAP_PLANAR = false;
  91606. defines.REFLECTIONMAP_CUBIC = false;
  91607. defines.REFLECTIONMAP_PROJECTION = false;
  91608. defines.REFLECTIONMAP_SKYBOX = false;
  91609. defines.REFLECTIONMAP_EXPLICIT = false;
  91610. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91611. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91612. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91613. defines.INVERTCUBICMAP = false;
  91614. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91615. defines.LODINREFLECTIONALPHA = false;
  91616. defines.GAMMAREFLECTION = false;
  91617. }
  91618. }
  91619. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91620. defines.USERGBCOLOR = this._useRGBColor;
  91621. defines.NOISE = this._enableNoise;
  91622. }
  91623. if (defines._areImageProcessingDirty) {
  91624. if (!this._imageProcessingConfiguration.isReady()) {
  91625. return false;
  91626. }
  91627. this._imageProcessingConfiguration.prepareDefines(defines);
  91628. }
  91629. // Misc.
  91630. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91631. // Values that need to be evaluated on every frame
  91632. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91633. // Attribs
  91634. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91635. if (mesh) {
  91636. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91637. mesh.createNormals(true);
  91638. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91639. }
  91640. }
  91641. }
  91642. // Get correct effect
  91643. if (defines.isDirty) {
  91644. defines.markAsProcessed();
  91645. scene.resetCachedMaterial();
  91646. // Fallbacks
  91647. var fallbacks = new BABYLON.EffectFallbacks();
  91648. if (defines.FOG) {
  91649. fallbacks.addFallback(0, "FOG");
  91650. }
  91651. if (defines.POINTSIZE) {
  91652. fallbacks.addFallback(1, "POINTSIZE");
  91653. }
  91654. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91655. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91656. fallbacks.addCPUSkinningFallback(0, mesh);
  91657. }
  91658. //Attributes
  91659. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91660. if (defines.NORMAL) {
  91661. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91662. }
  91663. if (defines.UV1) {
  91664. attribs.push(BABYLON.VertexBuffer.UVKind);
  91665. }
  91666. if (defines.UV2) {
  91667. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91668. }
  91669. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91670. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91671. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91672. "vFogInfos", "vFogColor", "pointSize",
  91673. "vClipPlane", "mBones",
  91674. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91675. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91676. "shadowLevel", "alpha",
  91677. "vBackgroundCenter", "vReflectionControl",
  91678. "vDiffuseInfos", "diffuseMatrix",
  91679. ];
  91680. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91681. var uniformBuffers = ["Material", "Scene"];
  91682. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91683. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91684. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91685. uniformsNames: uniforms,
  91686. uniformBuffersNames: uniformBuffers,
  91687. samplers: samplers,
  91688. defines: defines,
  91689. maxSimultaneousLights: this._maxSimultaneousLights
  91690. });
  91691. var onCompiled = function (effect) {
  91692. if (_this.onCompiled) {
  91693. _this.onCompiled(effect);
  91694. }
  91695. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91696. };
  91697. var join = defines.toString();
  91698. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91699. attributes: attribs,
  91700. uniformsNames: uniforms,
  91701. uniformBuffersNames: uniformBuffers,
  91702. samplers: samplers,
  91703. defines: join,
  91704. fallbacks: fallbacks,
  91705. onCompiled: onCompiled,
  91706. onError: this.onError,
  91707. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91708. }, engine), defines);
  91709. this.buildUniformLayout();
  91710. }
  91711. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91712. return false;
  91713. }
  91714. defines._renderId = scene.getRenderId();
  91715. this._wasPreviouslyReady = true;
  91716. return true;
  91717. };
  91718. /**
  91719. * Build the uniform buffer used in the material.
  91720. */
  91721. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91722. // Order is important !
  91723. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91724. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91725. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91726. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91727. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91728. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91729. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91730. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91731. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91732. this._uniformBuffer.addUniform("pointSize", 1);
  91733. this._uniformBuffer.addUniform("shadowLevel", 1);
  91734. this._uniformBuffer.addUniform("alpha", 1);
  91735. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91736. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91737. this._uniformBuffer.create();
  91738. };
  91739. /**
  91740. * Unbind the material.
  91741. */
  91742. BackgroundMaterial.prototype.unbind = function () {
  91743. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91744. this._uniformBuffer.setTexture("diffuseSampler", null);
  91745. }
  91746. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91747. this._uniformBuffer.setTexture("reflectionSampler", null);
  91748. }
  91749. _super.prototype.unbind.call(this);
  91750. };
  91751. /**
  91752. * Bind only the world matrix to the material.
  91753. * @param world The world matrix to bind.
  91754. */
  91755. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91756. this._activeEffect.setMatrix("world", world);
  91757. };
  91758. /**
  91759. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91760. * @param world The world matrix to bind.
  91761. * @param subMesh The submesh to bind for.
  91762. */
  91763. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91764. var scene = this.getScene();
  91765. var defines = subMesh._materialDefines;
  91766. if (!defines) {
  91767. return;
  91768. }
  91769. var effect = subMesh.effect;
  91770. if (!effect) {
  91771. return;
  91772. }
  91773. this._activeEffect = effect;
  91774. // Matrices
  91775. this.bindOnlyWorldMatrix(world);
  91776. // Bones
  91777. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91778. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91779. if (mustRebind) {
  91780. this._uniformBuffer.bindToEffect(effect, "Material");
  91781. this.bindViewProjection(effect);
  91782. var reflectionTexture = this._reflectionTexture;
  91783. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91784. // Texture uniforms
  91785. if (scene.texturesEnabled) {
  91786. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91787. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91788. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91789. }
  91790. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91791. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91792. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91793. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91794. }
  91795. }
  91796. if (this.shadowLevel > 0) {
  91797. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91798. }
  91799. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91800. // Point size
  91801. if (this.pointsCloud) {
  91802. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91803. }
  91804. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91805. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91806. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91807. }
  91808. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91809. // Textures
  91810. if (scene.texturesEnabled) {
  91811. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91812. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91813. }
  91814. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91815. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91816. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91817. }
  91818. else if (!defines.REFLECTIONBLUR) {
  91819. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91820. }
  91821. else {
  91822. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91823. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91824. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91825. }
  91826. if (defines.REFLECTIONFRESNEL) {
  91827. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91828. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91829. }
  91830. }
  91831. }
  91832. // Clip plane
  91833. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  91834. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  91835. }
  91836. if (mustRebind || !this.isFrozen) {
  91837. if (scene.lightsEnabled) {
  91838. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  91839. }
  91840. // View
  91841. this.bindView(effect);
  91842. // Fog
  91843. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91844. // image processing
  91845. this._imageProcessingConfiguration.bind(this._activeEffect);
  91846. }
  91847. this._uniformBuffer.update();
  91848. this._afterBind(mesh);
  91849. };
  91850. /**
  91851. * Dispose the material.
  91852. * @param forceDisposeEffect Force disposal of the associated effect.
  91853. * @param forceDisposeTextures Force disposal of the associated textures.
  91854. */
  91855. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  91856. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  91857. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  91858. if (forceDisposeTextures) {
  91859. if (this.diffuseTexture) {
  91860. this.diffuseTexture.dispose();
  91861. }
  91862. if (this.reflectionTexture) {
  91863. this.reflectionTexture.dispose();
  91864. }
  91865. }
  91866. this._renderTargets.dispose();
  91867. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91868. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91869. }
  91870. _super.prototype.dispose.call(this, forceDisposeEffect);
  91871. };
  91872. /**
  91873. * Clones the material.
  91874. * @param name The cloned name.
  91875. * @returns The cloned material.
  91876. */
  91877. BackgroundMaterial.prototype.clone = function (name) {
  91878. var _this = this;
  91879. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  91880. };
  91881. /**
  91882. * Serializes the current material to its JSON representation.
  91883. * @returns The JSON representation.
  91884. */
  91885. BackgroundMaterial.prototype.serialize = function () {
  91886. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91887. serializationObject.customType = "BABYLON.BackgroundMaterial";
  91888. return serializationObject;
  91889. };
  91890. /**
  91891. * Gets the class name of the material
  91892. * @returns "BackgroundMaterial"
  91893. */
  91894. BackgroundMaterial.prototype.getClassName = function () {
  91895. return "BackgroundMaterial";
  91896. };
  91897. /**
  91898. * Parse a JSON input to create back a background material.
  91899. * @param source The JSON data to parse
  91900. * @param scene The scene to create the parsed material in
  91901. * @param rootUrl The root url of the assets the material depends upon
  91902. * @returns the instantiated BackgroundMaterial.
  91903. */
  91904. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  91905. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  91906. };
  91907. /**
  91908. * Standard reflectance value at parallel view angle.
  91909. */
  91910. BackgroundMaterial.StandardReflectance0 = 0.05;
  91911. /**
  91912. * Standard reflectance value at grazing angle.
  91913. */
  91914. BackgroundMaterial.StandardReflectance90 = 0.5;
  91915. __decorate([
  91916. BABYLON.serializeAsColor3()
  91917. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  91918. __decorate([
  91919. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91920. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  91921. __decorate([
  91922. BABYLON.serialize()
  91923. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  91924. __decorate([
  91925. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91926. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  91927. __decorate([
  91928. BABYLON.serializeAsColor3()
  91929. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  91930. __decorate([
  91931. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91932. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  91933. __decorate([
  91934. BABYLON.serialize()
  91935. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  91936. __decorate([
  91937. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91938. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  91939. __decorate([
  91940. BABYLON.serializeAsColor3()
  91941. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  91942. __decorate([
  91943. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91944. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  91945. __decorate([
  91946. BABYLON.serialize()
  91947. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  91948. __decorate([
  91949. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91950. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  91951. __decorate([
  91952. BABYLON.serializeAsTexture()
  91953. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  91954. __decorate([
  91955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91956. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  91957. __decorate([
  91958. BABYLON.serialize()
  91959. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  91960. __decorate([
  91961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91962. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  91963. __decorate([
  91964. BABYLON.serializeAsTexture()
  91965. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  91966. __decorate([
  91967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91968. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  91969. __decorate([
  91970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91971. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  91972. __decorate([
  91973. BABYLON.serialize()
  91974. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  91975. __decorate([
  91976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91977. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  91978. __decorate([
  91979. BABYLON.serialize()
  91980. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  91981. __decorate([
  91982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91983. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  91984. __decorate([
  91985. BABYLON.serializeAsVector3()
  91986. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  91987. __decorate([
  91988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91989. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  91990. __decorate([
  91991. BABYLON.serialize()
  91992. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  91993. __decorate([
  91994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91995. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  91996. __decorate([
  91997. BABYLON.serialize()
  91998. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  91999. __decorate([
  92000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92001. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  92002. __decorate([
  92003. BABYLON.serialize()
  92004. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  92005. __decorate([
  92006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92007. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  92008. __decorate([
  92009. BABYLON.serialize()
  92010. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  92011. __decorate([
  92012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92013. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  92014. __decorate([
  92015. BABYLON.serialize()
  92016. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  92017. __decorate([
  92018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92019. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  92020. __decorate([
  92021. BABYLON.serialize()
  92022. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  92023. __decorate([
  92024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92025. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  92026. __decorate([
  92027. BABYLON.serialize()
  92028. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  92029. __decorate([
  92030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92031. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  92032. __decorate([
  92033. BABYLON.serialize()
  92034. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  92035. __decorate([
  92036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92037. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  92038. __decorate([
  92039. BABYLON.serialize()
  92040. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  92041. __decorate([
  92042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92043. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  92044. __decorate([
  92045. BABYLON.serializeAsImageProcessingConfiguration()
  92046. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  92047. return BackgroundMaterial;
  92048. }(BABYLON.PushMaterial));
  92049. BABYLON.BackgroundMaterial = BackgroundMaterial;
  92050. })(BABYLON || (BABYLON = {}));
  92051. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  92052. "use strict";
  92053. var __assign = (this && this.__assign) || Object.assign || function(t) {
  92054. for (var s, i = 1, n = arguments.length; i < n; i++) {
  92055. s = arguments[i];
  92056. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  92057. t[p] = s[p];
  92058. }
  92059. return t;
  92060. };
  92061. var BABYLON;
  92062. (function (BABYLON) {
  92063. /**
  92064. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  92065. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  92066. * It also helps with the default setup of your imageProcessing configuration.
  92067. */
  92068. var EnvironmentHelper = /** @class */ (function () {
  92069. /**
  92070. * constructor
  92071. * @param options
  92072. * @param scene The scene to add the material to
  92073. */
  92074. function EnvironmentHelper(options, scene) {
  92075. var _this = this;
  92076. this._errorHandler = function (message, exception) {
  92077. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  92078. };
  92079. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  92080. this._scene = scene;
  92081. this.onErrorObservable = new BABYLON.Observable();
  92082. this._setupBackground();
  92083. this._setupImageProcessing();
  92084. }
  92085. /**
  92086. * Creates the default options for the helper.
  92087. */
  92088. EnvironmentHelper._getDefaultOptions = function () {
  92089. return {
  92090. createGround: true,
  92091. groundSize: 15,
  92092. groundTexture: this._groundTextureCDNUrl,
  92093. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92094. groundOpacity: 0.9,
  92095. enableGroundShadow: true,
  92096. groundShadowLevel: 0.5,
  92097. enableGroundMirror: false,
  92098. groundMirrorSizeRatio: 0.3,
  92099. groundMirrorBlurKernel: 64,
  92100. groundMirrorAmount: 1,
  92101. groundMirrorFresnelWeight: 1,
  92102. groundMirrorFallOffDistance: 0,
  92103. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  92104. groundYBias: 0.00001,
  92105. createSkybox: true,
  92106. skyboxSize: 20,
  92107. skyboxTexture: this._skyboxTextureCDNUrl,
  92108. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92109. backgroundYRotation: 0,
  92110. sizeAuto: true,
  92111. rootPosition: BABYLON.Vector3.Zero(),
  92112. setupImageProcessing: true,
  92113. environmentTexture: this._environmentTextureCDNUrl,
  92114. cameraExposure: 0.8,
  92115. cameraContrast: 1.2,
  92116. toneMappingEnabled: true,
  92117. };
  92118. };
  92119. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  92120. /**
  92121. * Gets the root mesh created by the helper.
  92122. */
  92123. get: function () {
  92124. return this._rootMesh;
  92125. },
  92126. enumerable: true,
  92127. configurable: true
  92128. });
  92129. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  92130. /**
  92131. * Gets the skybox created by the helper.
  92132. */
  92133. get: function () {
  92134. return this._skybox;
  92135. },
  92136. enumerable: true,
  92137. configurable: true
  92138. });
  92139. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  92140. /**
  92141. * Gets the skybox texture created by the helper.
  92142. */
  92143. get: function () {
  92144. return this._skyboxTexture;
  92145. },
  92146. enumerable: true,
  92147. configurable: true
  92148. });
  92149. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  92150. /**
  92151. * Gets the skybox material created by the helper.
  92152. */
  92153. get: function () {
  92154. return this._skyboxMaterial;
  92155. },
  92156. enumerable: true,
  92157. configurable: true
  92158. });
  92159. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  92160. /**
  92161. * Gets the ground mesh created by the helper.
  92162. */
  92163. get: function () {
  92164. return this._ground;
  92165. },
  92166. enumerable: true,
  92167. configurable: true
  92168. });
  92169. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  92170. /**
  92171. * Gets the ground texture created by the helper.
  92172. */
  92173. get: function () {
  92174. return this._groundTexture;
  92175. },
  92176. enumerable: true,
  92177. configurable: true
  92178. });
  92179. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  92180. /**
  92181. * Gets the ground mirror created by the helper.
  92182. */
  92183. get: function () {
  92184. return this._groundMirror;
  92185. },
  92186. enumerable: true,
  92187. configurable: true
  92188. });
  92189. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  92190. /**
  92191. * Gets the ground mirror render list to helps pushing the meshes
  92192. * you wish in the ground reflection.
  92193. */
  92194. get: function () {
  92195. if (this._groundMirror) {
  92196. return this._groundMirror.renderList;
  92197. }
  92198. return null;
  92199. },
  92200. enumerable: true,
  92201. configurable: true
  92202. });
  92203. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  92204. /**
  92205. * Gets the ground material created by the helper.
  92206. */
  92207. get: function () {
  92208. return this._groundMaterial;
  92209. },
  92210. enumerable: true,
  92211. configurable: true
  92212. });
  92213. /**
  92214. * Updates the background according to the new options
  92215. * @param options
  92216. */
  92217. EnvironmentHelper.prototype.updateOptions = function (options) {
  92218. var newOptions = __assign({}, this._options, options);
  92219. if (this._ground && !newOptions.createGround) {
  92220. this._ground.dispose();
  92221. this._ground = null;
  92222. }
  92223. if (this._groundMaterial && !newOptions.createGround) {
  92224. this._groundMaterial.dispose();
  92225. this._groundMaterial = null;
  92226. }
  92227. if (this._groundTexture) {
  92228. if (this._options.groundTexture != newOptions.groundTexture) {
  92229. this._groundTexture.dispose();
  92230. this._groundTexture = null;
  92231. }
  92232. }
  92233. if (this._skybox && !newOptions.createSkybox) {
  92234. this._skybox.dispose();
  92235. this._skybox = null;
  92236. }
  92237. if (this._skyboxMaterial && !newOptions.createSkybox) {
  92238. this._skyboxMaterial.dispose();
  92239. this._skyboxMaterial = null;
  92240. }
  92241. if (this._skyboxTexture) {
  92242. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  92243. this._skyboxTexture.dispose();
  92244. this._skyboxTexture = null;
  92245. }
  92246. }
  92247. if (this._groundMirror && !newOptions.enableGroundMirror) {
  92248. this._groundMirror.dispose();
  92249. this._groundMirror = null;
  92250. }
  92251. if (this._scene.environmentTexture) {
  92252. if (this._options.environmentTexture != newOptions.environmentTexture) {
  92253. this._scene.environmentTexture.dispose();
  92254. }
  92255. }
  92256. this._options = newOptions;
  92257. this._setupBackground();
  92258. this._setupImageProcessing();
  92259. };
  92260. /**
  92261. * Sets the primary color of all the available elements.
  92262. * @param color
  92263. */
  92264. EnvironmentHelper.prototype.setMainColor = function (color) {
  92265. if (this.groundMaterial) {
  92266. this.groundMaterial.primaryColor = color;
  92267. }
  92268. if (this.skyboxMaterial) {
  92269. this.skyboxMaterial.primaryColor = color;
  92270. }
  92271. if (this.groundMirror) {
  92272. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  92273. }
  92274. };
  92275. /**
  92276. * Setup the image processing according to the specified options.
  92277. */
  92278. EnvironmentHelper.prototype._setupImageProcessing = function () {
  92279. if (this._options.setupImageProcessing) {
  92280. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  92281. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  92282. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  92283. this._setupEnvironmentTexture();
  92284. }
  92285. };
  92286. /**
  92287. * Setup the environment texture according to the specified options.
  92288. */
  92289. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  92290. if (this._scene.environmentTexture) {
  92291. return;
  92292. }
  92293. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  92294. this._scene.environmentTexture = this._options.environmentTexture;
  92295. return;
  92296. }
  92297. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  92298. this._scene.environmentTexture = environmentTexture;
  92299. };
  92300. /**
  92301. * Setup the background according to the specified options.
  92302. */
  92303. EnvironmentHelper.prototype._setupBackground = function () {
  92304. if (!this._rootMesh) {
  92305. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  92306. }
  92307. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  92308. var sceneSize = this._getSceneSize();
  92309. if (this._options.createGround) {
  92310. this._setupGround(sceneSize);
  92311. this._setupGroundMaterial();
  92312. this._setupGroundDiffuseTexture();
  92313. if (this._options.enableGroundMirror) {
  92314. this._setupGroundMirrorTexture(sceneSize);
  92315. }
  92316. this._setupMirrorInGroundMaterial();
  92317. }
  92318. if (this._options.createSkybox) {
  92319. this._setupSkybox(sceneSize);
  92320. this._setupSkyboxMaterial();
  92321. this._setupSkyboxReflectionTexture();
  92322. }
  92323. this._rootMesh.position.x = sceneSize.rootPosition.x;
  92324. this._rootMesh.position.z = sceneSize.rootPosition.z;
  92325. this._rootMesh.position.y = sceneSize.rootPosition.y;
  92326. };
  92327. /**
  92328. * Get the scene sizes according to the setup.
  92329. */
  92330. EnvironmentHelper.prototype._getSceneSize = function () {
  92331. var _this = this;
  92332. var groundSize = this._options.groundSize;
  92333. var skyboxSize = this._options.skyboxSize;
  92334. var rootPosition = this._options.rootPosition;
  92335. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  92336. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92337. }
  92338. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  92339. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  92340. });
  92341. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92342. if (this._options.sizeAuto) {
  92343. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  92344. this._scene.activeCamera.upperRadiusLimit) {
  92345. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  92346. skyboxSize = groundSize;
  92347. }
  92348. var sceneDiagonalLenght = sceneDiagonal.length();
  92349. if (sceneDiagonalLenght > groundSize) {
  92350. groundSize = sceneDiagonalLenght * 2;
  92351. skyboxSize = groundSize;
  92352. }
  92353. // 10 % bigger.
  92354. groundSize *= 1.1;
  92355. skyboxSize *= 1.5;
  92356. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  92357. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  92358. }
  92359. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92360. };
  92361. /**
  92362. * Setup the ground according to the specified options.
  92363. */
  92364. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  92365. var _this = this;
  92366. if (!this._ground) {
  92367. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  92368. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  92369. this._ground.parent = this._rootMesh;
  92370. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  92371. }
  92372. this._ground.receiveShadows = this._options.enableGroundShadow;
  92373. };
  92374. /**
  92375. * Setup the ground material according to the specified options.
  92376. */
  92377. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  92378. if (!this._groundMaterial) {
  92379. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  92380. }
  92381. this._groundMaterial.alpha = this._options.groundOpacity;
  92382. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92383. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92384. this._groundMaterial.primaryLevel = 1;
  92385. this._groundMaterial.primaryColor = this._options.groundColor;
  92386. this._groundMaterial.secondaryLevel = 0;
  92387. this._groundMaterial.tertiaryLevel = 0;
  92388. this._groundMaterial.useRGBColor = false;
  92389. this._groundMaterial.enableNoise = true;
  92390. if (this._ground) {
  92391. this._ground.material = this._groundMaterial;
  92392. }
  92393. };
  92394. /**
  92395. * Setup the ground diffuse texture according to the specified options.
  92396. */
  92397. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92398. if (!this._groundMaterial) {
  92399. return;
  92400. }
  92401. if (this._groundTexture) {
  92402. return;
  92403. }
  92404. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92405. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92406. return;
  92407. }
  92408. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92409. diffuseTexture.gammaSpace = false;
  92410. diffuseTexture.hasAlpha = true;
  92411. this._groundMaterial.diffuseTexture = diffuseTexture;
  92412. };
  92413. /**
  92414. * Setup the ground mirror texture according to the specified options.
  92415. */
  92416. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92417. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92418. if (!this._groundMirror) {
  92419. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92420. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92421. this._groundMirror.anisotropicFilteringLevel = 1;
  92422. this._groundMirror.wrapU = wrapping;
  92423. this._groundMirror.wrapV = wrapping;
  92424. this._groundMirror.gammaSpace = false;
  92425. if (this._groundMirror.renderList) {
  92426. for (var i = 0; i < this._scene.meshes.length; i++) {
  92427. var mesh = this._scene.meshes[i];
  92428. if (mesh !== this._ground &&
  92429. mesh !== this._skybox &&
  92430. mesh !== this._rootMesh) {
  92431. this._groundMirror.renderList.push(mesh);
  92432. }
  92433. }
  92434. }
  92435. }
  92436. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92437. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92438. };
  92439. /**
  92440. * Setup the ground to receive the mirror texture.
  92441. */
  92442. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92443. if (this._groundMaterial) {
  92444. this._groundMaterial.reflectionTexture = this._groundMirror;
  92445. this._groundMaterial.reflectionFresnel = true;
  92446. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92447. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92448. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92449. }
  92450. };
  92451. /**
  92452. * Setup the skybox according to the specified options.
  92453. */
  92454. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92455. var _this = this;
  92456. if (!this._skybox) {
  92457. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92458. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92459. }
  92460. this._skybox.parent = this._rootMesh;
  92461. };
  92462. /**
  92463. * Setup the skybox material according to the specified options.
  92464. */
  92465. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92466. if (!this._skybox) {
  92467. return;
  92468. }
  92469. if (!this._skyboxMaterial) {
  92470. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92471. }
  92472. this._skyboxMaterial.useRGBColor = false;
  92473. this._skyboxMaterial.primaryLevel = 1;
  92474. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92475. this._skyboxMaterial.secondaryLevel = 0;
  92476. this._skyboxMaterial.tertiaryLevel = 0;
  92477. this._skyboxMaterial.enableNoise = true;
  92478. this._skybox.material = this._skyboxMaterial;
  92479. };
  92480. /**
  92481. * Setup the skybox reflection texture according to the specified options.
  92482. */
  92483. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92484. if (!this._skyboxMaterial) {
  92485. return;
  92486. }
  92487. if (this._skyboxTexture) {
  92488. return;
  92489. }
  92490. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92491. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92492. return;
  92493. }
  92494. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92495. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92496. this._skyboxTexture.gammaSpace = false;
  92497. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92498. };
  92499. /**
  92500. * Dispose all the elements created by the Helper.
  92501. */
  92502. EnvironmentHelper.prototype.dispose = function () {
  92503. if (this._groundMaterial) {
  92504. this._groundMaterial.dispose(true, true);
  92505. }
  92506. if (this._skyboxMaterial) {
  92507. this._skyboxMaterial.dispose(true, true);
  92508. }
  92509. this._rootMesh.dispose(false);
  92510. };
  92511. /**
  92512. * Default ground texture URL.
  92513. */
  92514. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92515. /**
  92516. * Default skybox texture URL.
  92517. */
  92518. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92519. /**
  92520. * Default environment texture URL.
  92521. */
  92522. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92523. return EnvironmentHelper;
  92524. }());
  92525. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92526. })(BABYLON || (BABYLON = {}));
  92527. //# sourceMappingURL=babylon.environmentHelper.js.map
  92528. "use strict";
  92529. var BABYLON;
  92530. (function (BABYLON) {
  92531. /**
  92532. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92533. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92534. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92535. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92536. */
  92537. var VideoDome = /** @class */ (function (_super) {
  92538. __extends(VideoDome, _super);
  92539. /**
  92540. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92541. * @param name Element's name, child elements will append suffixes for their own names.
  92542. * @param urlsOrVideo
  92543. * @param options An object containing optional or exposed sub element properties:
  92544. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92545. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92546. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92547. * @param options **loop=true** Automatically loop video on end.
  92548. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92549. */
  92550. function VideoDome(name, urlsOrVideo, options, scene) {
  92551. var _this = _super.call(this, name, scene) || this;
  92552. // set defaults and manage values
  92553. name = name || "videoDome";
  92554. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92555. options.clickToPlay = Boolean(options.clickToPlay);
  92556. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92557. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92558. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92559. // create
  92560. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92561. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92562. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92563. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92564. flat: false,
  92565. radius: options.size,
  92566. subdivisions: options.resolution,
  92567. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92568. }, scene);
  92569. // configure material
  92570. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92571. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92572. material.reflectionTexture = _this._videoTexture;
  92573. material.useEquirectangularFOV = true;
  92574. material.fovMultiplier = 1.0;
  92575. // configure mesh
  92576. _this._mesh.material = material;
  92577. _this._mesh.parent = _this;
  92578. // optional configuration
  92579. if (options.clickToPlay) {
  92580. scene.onPointerUp = function () {
  92581. _this._videoTexture.video.play();
  92582. };
  92583. }
  92584. return _this;
  92585. }
  92586. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92587. /**
  92588. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92589. * Also see the options.resolution property.
  92590. */
  92591. get: function () {
  92592. return this._material.fovMultiplier;
  92593. },
  92594. set: function (value) {
  92595. this._material.fovMultiplier = value;
  92596. },
  92597. enumerable: true,
  92598. configurable: true
  92599. });
  92600. /**
  92601. * Releases resources associated with this node.
  92602. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92603. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92604. */
  92605. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92606. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92607. this._videoTexture.dispose();
  92608. this._mesh.dispose();
  92609. this._material.dispose();
  92610. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92611. };
  92612. return VideoDome;
  92613. }(BABYLON.Node));
  92614. BABYLON.VideoDome = VideoDome;
  92615. })(BABYLON || (BABYLON = {}));
  92616. //# sourceMappingURL=babylon.videoDome.js.map
  92617. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\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;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=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\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\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#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\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\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\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\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#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 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{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\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 vec3 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.z*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 radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\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);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/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;\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}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","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\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\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{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  92618. 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}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\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};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(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 computeShadowWithPoissonSampling(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#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\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\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(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#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,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#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","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","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92619. globalObject["BABYLON"] = BABYLON;
  92620. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;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 DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var 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;var VideoDome = BABYLON.VideoDome;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  92621. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,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,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,VideoDome,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,JoystickAxis ,SimplificationType ,AssetTaskState };